blob: ea597221167e107112b631c847657f2c7cd4b3df [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
Adam Lesinskice5e56e2016-10-21 17:56:45 -070020#include <queue>
21#include <unordered_map>
22#include <vector>
23
24#include "android-base/errors.h"
25#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080026#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080027#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070028
Adam Lesinski1ab598f2015-08-14 14:26:04 -070029#include "AppInfo.h"
30#include "Debug.h"
31#include "Flags.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070032#include "LoadedApk.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080033#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070034#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080035#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070036#include "ResourceValues.h"
37#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070038#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070039#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080040#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080041#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070042#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070043#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/binary/TableFlattener.h"
45#include "format/binary/XmlFlattener.h"
46#include "format/proto/ProtoDeserialize.h"
47#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070048#include "io/BigBufferStream.h"
49#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080050#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070051#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070053#include "java/JavaClassGenerator.h"
54#include "java/ManifestClassGenerator.h"
55#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070056#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070057#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080058#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080059#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070060#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070061#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080062#include "optimize/ResourceDeduper.h"
63#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "process/IResourceTableConsumer.h"
65#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080066#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080068#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070070using ::aapt::io::FileInputStream;
71using ::android::StringPiece;
72using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070073
Adam Lesinski1ab598f2015-08-14 14:26:04 -070074namespace aapt {
75
Adam Lesinskie59f0d82017-10-13 09:36:53 -070076enum class OutputFormat {
77 kApk,
78 kProto,
79};
80
Adam Lesinski1ab598f2015-08-14 14:26:04 -070081struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070082 std::string output_path;
83 std::string manifest_path;
84 std::vector<std::string> include_paths;
85 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070086 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070087 bool output_to_directory = false;
88 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070089 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070090
Adam Lesinskicacb28f2016-10-19 12:18:14 -070091 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070092 Maybe<std::string> generate_java_class_path;
93 Maybe<std::string> custom_java_package;
94 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070095 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070096 Maybe<std::string> generate_proguard_rules_path;
97 Maybe<std::string> generate_main_dex_proguard_rules_path;
Adam Koskidc21dea2017-07-21 10:55:27 -070098 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070099 bool generate_non_final_ids = false;
100 std::vector<std::string> javadoc_annotations;
101 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700102
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700103 // Optimizations/features.
104 bool no_auto_version = false;
105 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900106 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700107 bool no_resource_deduping = false;
108 bool no_xml_namespaces = false;
109 bool do_not_compress_anything = false;
110 std::unordered_set<std::string> extensions_to_not_compress;
111
112 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700113 bool no_static_lib_packages = false;
114
115 // AndroidManifest.xml massaging options.
116 ManifestFixerOptions manifest_fixer_options;
117
118 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700119 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700120
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800121 // Flattening options.
122 TableFlattenerOptions table_flattener_options;
123
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700124 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700125 TableSplitterOptions table_splitter_options;
126 std::vector<SplitConstraints> split_constraints;
127 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700128
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700129 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700130 std::unordered_map<ResourceName, ResourceId> stable_id_map;
131 Maybe<std::string> resource_id_map_path;
Todd Kennedy32512992018-04-25 16:45:59 -0700132
133 // When 'true', allow reserved package IDs to be used for applications. Pre-O, the platform
134 // treats negative resource IDs [those with a package ID of 0x80 or higher] as invalid.
135 // In order to work around this limitation, we allow the use of traditionally reserved
136 // resource IDs [those between 0x02 and 0x7E].
137 bool allow_reserved_package_id = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700138};
139
Adam Lesinski64587af2016-02-18 18:33:06 -0800140class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700141 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100142 LinkContext(IDiagnostics* diagnostics)
143 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700144 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700145
Adam Lesinskib522f042017-04-21 16:57:59 -0700146 PackageType GetPackageType() override {
147 return package_type_;
148 }
149
150 void SetPackageType(PackageType type) {
151 package_type_ = type;
152 }
153
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700154 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100155 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700156 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700157
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700158 NameMangler* GetNameMangler() override {
159 return &name_mangler_;
160 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700161
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700162 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
163 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700164 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800165
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700166 const std::string& GetCompilationPackage() override {
167 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700168 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700169
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700170 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800171 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700172 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800173
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700174 uint8_t GetPackageId() override {
175 return package_id_;
176 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700177
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700178 void SetPackageId(uint8_t id) {
179 package_id_ = id;
180 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800181
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700182 SymbolTable* GetExternalSymbols() override {
183 return &symbols_;
184 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800185
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700186 bool IsVerbose() override {
187 return verbose_;
188 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800189
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700190 void SetVerbose(bool val) {
191 verbose_ = val;
192 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800193
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700194 int GetMinSdkVersion() override {
195 return min_sdk_version_;
196 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700197
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700198 void SetMinSdkVersion(int minSdk) {
199 min_sdk_version_ = minSdk;
200 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700201
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700202 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700203 DISALLOW_COPY_AND_ASSIGN(LinkContext);
204
Adam Lesinskib522f042017-04-21 16:57:59 -0700205 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100206 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700207 NameMangler name_mangler_;
208 std::string compilation_package_;
209 uint8_t package_id_ = 0x0;
210 SymbolTable symbols_;
211 bool verbose_ = false;
212 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700213};
214
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700215// A custom delegate that generates compatible pre-O IDs for use with feature splits.
216// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
217// is interpreted as a negative number. Some verification was wrongly assuming negative values
218// were invalid.
219//
220// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
221// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
222// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800223//
224// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700225class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
226 public:
227 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
228 }
229
230 virtual ~FeatureSplitSymbolTableDelegate() = default;
231
232 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
233 const ResourceName& name,
234 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
235 std::unique_ptr<SymbolTable::Symbol> symbol =
236 DefaultSymbolTableDelegate::FindByName(name, sources);
237 if (symbol == nullptr) {
238 return {};
239 }
240
241 // Check to see if this is an 'id' with the target package.
242 if (name.type == ResourceType::kId && symbol->id) {
243 ResourceId* id = &symbol->id.value();
244 if (id->package_id() > kAppPackageId) {
245 // Rewrite the resource ID to be compatible pre-O.
246 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
247
248 // Check that this doesn't overlap another resource.
249 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
250 // The ID overlaps, so log a message (since this is a weird failure) and fail.
251 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
252 << " for pre-O feature split support");
253 return {};
254 }
255
256 if (context_->IsVerbose()) {
257 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
258 << ") -> (" << rewritten_id << ")");
259 }
260
261 *id = rewritten_id;
262 }
263 }
264 return symbol;
265 }
266
267 private:
268 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
269
270 IAaptContext* context_;
271};
272
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700273static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
274 const StringPiece& path, bool keep_raw_values, bool utf16,
275 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700276 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700277 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
278 << (keep_raw_values ? "true" : "false")
279 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700280 }
281
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700282 switch (format) {
283 case OutputFormat::kApk: {
284 BigBuffer buffer(1024);
285 XmlFlattenerOptions options = {};
286 options.keep_raw_values = keep_raw_values;
287 options.use_utf16 = utf16;
288 XmlFlattener flattener(&buffer, options);
289 if (!flattener.Consume(context, &xml_res)) {
290 return false;
291 }
292
293 io::BigBufferInputStream input_stream(&buffer);
294 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
295 ArchiveEntry::kCompress, writer);
296 } break;
297
298 case OutputFormat::kProto: {
299 pb::XmlNode pb_node;
300 SerializeXmlResourceToPb(xml_res, &pb_node);
301 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
302 writer);
303 } break;
304 }
305 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800306}
307
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700308// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700309static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700310 FileInputStream fin(path);
311 if (fin.HadError()) {
312 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700313 return {};
314 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700315 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800316}
317
Adam Lesinski355f2852016-02-13 20:26:45 -0800318struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700319 bool no_auto_version = false;
320 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900321 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700322 bool no_xml_namespaces = false;
323 bool keep_raw_values = false;
324 bool do_not_compress_anything = false;
325 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700326 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700327 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800328};
329
Adam Lesinskic744ae82017-05-17 19:28:38 -0700330// A sampling of public framework resource IDs.
331struct R {
332 struct attr {
333 enum : uint32_t {
334 paddingLeft = 0x010100d6u,
335 paddingRight = 0x010100d8u,
336 paddingHorizontal = 0x0101053du,
337
338 paddingTop = 0x010100d7u,
339 paddingBottom = 0x010100d9u,
340 paddingVertical = 0x0101053eu,
341
342 layout_marginLeft = 0x010100f7u,
343 layout_marginRight = 0x010100f9u,
344 layout_marginHorizontal = 0x0101053bu,
345
346 layout_marginTop = 0x010100f8u,
347 layout_marginBottom = 0x010100fau,
348 layout_marginVertical = 0x0101053cu,
349 };
350 };
351};
352
Adam Lesinski355f2852016-02-13 20:26:45 -0800353class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700354 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700355 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700356 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800357
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700358 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800359
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700360 private:
361 struct FileOperation {
362 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700363
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700365 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700366
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700368 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700369
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700370 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700371 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700372
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700373 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700374 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700375 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800376
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700377 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800378
Adam Lesinskic744ae82017-05-17 19:28:38 -0700379 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
380 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800381
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700382 ResourceFileFlattenerOptions options_;
383 IAaptContext* context_;
384 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700385 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800386};
387
Adam Lesinskic744ae82017-05-17 19:28:38 -0700388ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
389 IAaptContext* context, proguard::KeepSet* keep_set)
390 : options_(options), context_(context), keep_set_(keep_set) {
391 SymbolTable* symm = context_->GetExternalSymbols();
392
393 // Build up the rules for degrading newer attributes to older ones.
394 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
395 // generated from the attribute definitions themselves (b/62028956).
396 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
397 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800398 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
399 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700400 };
401 rules_[R::attr::paddingHorizontal] =
402 util::make_unique<DegradeToManyRule>(std::move(replacements));
403 }
404
405 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
406 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800407 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
408 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700409 };
410 rules_[R::attr::paddingVertical] =
411 util::make_unique<DegradeToManyRule>(std::move(replacements));
412 }
413
414 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
415 std::vector<ReplacementAttr> replacements{
416 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800417 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700418 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800419 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700420 };
421 rules_[R::attr::layout_marginHorizontal] =
422 util::make_unique<DegradeToManyRule>(std::move(replacements));
423 }
424
425 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
426 std::vector<ReplacementAttr> replacements{
427 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800428 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700429 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800430 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700431 };
432 rules_[R::attr::layout_marginVertical] =
433 util::make_unique<DegradeToManyRule>(std::move(replacements));
434 }
435}
436
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700437uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
438 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700439 return 0;
440 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800441
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700442 for (const std::string& extension : options_.extensions_to_not_compress) {
443 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700444 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800445 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700446 }
447 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800448}
449
Adam Lesinskibb94f322017-07-12 07:41:55 -0700450static bool IsTransitionElement(const std::string& name) {
451 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
452 name == "changeImageTransform" || name == "changeTransform" ||
453 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
454 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
455 name == "transitionManager";
456}
457
458static bool IsVectorElement(const std::string& name) {
459 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000460 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700461}
462
Adam Lesinskic744ae82017-05-17 19:28:38 -0700463template <typename T>
464std::vector<T> make_singleton_vec(T&& val) {
465 std::vector<T> vec;
466 vec.emplace_back(std::forward<T>(val));
467 return vec;
468}
469
470std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
471 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700472 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700473 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700474
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700475 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700476 context_->GetDiagnostics()->Note(DiagMessage()
477 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700478 }
479
Adam Lesinski00451162017-10-03 07:44:08 -0700480 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
481 // that existing projects have out-of-date references which pass compilation.
482 xml::StripAndroidStudioAttributes(doc->root.get());
483
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700484 XmlReferenceLinker xml_linker;
485 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700486 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700487 }
488
Adam Koskidc21dea2017-07-21 10:55:27 -0700489 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700490 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700491 }
492
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700493 if (options_.no_xml_namespaces) {
494 XmlNamespaceRemover namespace_remover;
495 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700496 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800497 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700498 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800499
Adam Lesinskibb94f322017-07-12 07:41:55 -0700500 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700501 return make_singleton_vec(std::move(file_op->xml_to_flatten));
502 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700503
Adam Lesinskibb94f322017-07-12 07:41:55 -0700504 if (options_.no_version_vectors || options_.no_version_transitions) {
505 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700506 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700507 if (el && el->namespace_uri.empty()) {
508 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
509 (options_.no_version_transitions && IsTransitionElement(el->name))) {
510 return make_singleton_vec(std::move(file_op->xml_to_flatten));
511 }
512 }
513 }
514
Adam Lesinskic744ae82017-05-17 19:28:38 -0700515 const ConfigDescription& config = file_op->config;
516 ResourceEntry* entry = file_op->entry;
517
518 XmlCompatVersioner xml_compat_versioner(&rules_);
519 const util::Range<ApiVersion> api_range{config.sdkVersion,
520 FindNextApiVersionForConfig(entry, config)};
521 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800522}
523
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800524ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
525 switch (format) {
526 case OutputFormat::kApk:
527 return ResourceFile::Type::kBinaryXml;
528 case OutputFormat::kProto:
529 return ResourceFile::Type::kProtoXml;
530 }
531 LOG_ALWAYS_FATAL("unreachable");
532 return ResourceFile::Type::kUnknown;
533}
534
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700535bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700536 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700537 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800538
Adam Koskidc21dea2017-07-21 10:55:27 -0700539 proguard::CollectResourceReferences(context_, table, keep_set_);
540
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700541 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700542 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
543
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700545 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700547 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800548
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 // Populate the queue with all files in the ResourceTable.
550 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700551 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700552 // WARNING! Do not insert or remove any resources while executing in this scope. It will
553 // corrupt the iteration order.
554
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700555 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700556 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700557 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700558 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700559
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700560 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700561 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700562 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700564 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565 }
566
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700567 FileOperation file_op;
568 file_op.entry = entry.get();
569 file_op.dst_path = *file_ref->path;
570 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700571 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700572
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700574 (file_ref->type == ResourceFile::Type::kBinaryXml ||
575 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700576 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700577 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700578 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700579 << "failed to open file");
580 return false;
581 }
582
Adam Lesinski00451162017-10-03 07:44:08 -0700583 if (file_ref->type == ResourceFile::Type::kProtoXml) {
584 pb::XmlNode pb_xml_node;
585 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
586 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700587 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700588 return false;
589 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700590
Adam Lesinski00451162017-10-03 07:44:08 -0700591 std::string error;
592 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
593 if (file_op.xml_to_flatten == nullptr) {
594 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700595 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700596 return false;
597 }
598 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700599 std::string error_str;
600 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700601 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700602 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
603 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700604 return false;
605 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700606 }
607
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800608 // Update the type that this file will be written as.
609 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
610
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700611 file_op.xml_to_flatten->file.config = config_value->config;
612 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700613 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700614 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700615
616 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
617 // else we end up copying the string in the std::make_pair() method,
618 // then creating a StringPiece from the copy, which would cause us
619 // to end up referencing garbage in the map.
620 const StringPiece entry_name(entry->name);
621 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
622 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700623 }
624 }
625
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700626 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700627 for (auto& map_entry : config_sorted_files) {
628 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700629 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700630
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700631 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700632 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
633 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700634 if (versioned_docs.empty()) {
635 error = true;
636 continue;
637 }
638
Adam Lesinskic744ae82017-05-17 19:28:38 -0700639 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
640 std::string dst_path = file_op.dst_path;
641 if (doc->file.config != file_op.config) {
642 // Only add the new versioned configurations.
643 if (context_->IsVerbose()) {
644 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
645 << "auto-versioning resource from config '"
646 << config << "' -> '" << doc->file.config << "'");
647 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800649 const ResourceFile& file = doc->file;
650 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
651
652 std::unique_ptr<FileReference> file_ref =
653 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
654 file_ref->SetSource(doc->file.source);
655 // Update the output format of this XML file.
656 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
657 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
658 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700659 return false;
660 }
661 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700662
663 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
664 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700665 }
666 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700667 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
668 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700669 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700670 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700671 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700672 }
673 return !error;
674}
675
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700676static bool WriteStableIdMapToPath(IDiagnostics* diag,
677 const std::unordered_map<ResourceName, ResourceId>& id_map,
678 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800679 io::FileOutputStream fout(id_map_path);
680 if (fout.HadError()) {
681 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 return false;
683 }
684
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800685 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700686 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700687 const ResourceName& name = entry.first;
688 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800689 printer.Print(name.to_string());
690 printer.Print(" = ");
691 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700692 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800693 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700694
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800695 if (fout.HadError()) {
696 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700697 return false;
698 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700699 return true;
700}
701
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700702static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
703 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700704 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700705 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700706 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700707 return false;
708 }
709
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700710 out_id_map->clear();
711 size_t line_no = 0;
712 for (StringPiece line : util::Tokenize(content, '\n')) {
713 line_no++;
714 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700715 if (line.empty()) {
716 continue;
717 }
718
719 auto iter = std::find(line.begin(), line.end(), '=');
720 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700721 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700722 return false;
723 }
724
725 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700726 StringPiece res_name_str =
727 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
728 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700729 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
730 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731 return false;
732 }
733
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
735 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700736 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700737
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700738 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
739 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700740 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
741 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700742 return false;
743 }
744
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700745 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700746 }
747 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700748}
749
Adam Lesinskic6284372017-12-04 13:46:23 -0800750static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
751 using namespace android;
752
753 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
754 // we're looking for the first attribute resource in the system package.
755 const ResTable& table = assets.getResources(true);
756 Res_value val;
757 ssize_t idx = table.getResource(0x01010000, &val, true);
758 if (idx != NO_ERROR) {
759 // Try as a bag.
760 const ResTable::bag_entry* entry;
761 ssize_t cnt = table.lockBag(0x01010000, &entry);
762 if (cnt >= 0) {
763 idx = entry->stringBlock;
764 }
765 table.unlockBag(entry);
766 }
767
768 if (idx < 0) {
769 return 0;
770 }
771 return table.getTableCookie(idx);
772}
773
Adam Lesinskifb48d292015-11-07 15:52:13 -0800774class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700775 public:
776 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700777 : options_(options),
778 context_(context),
779 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700780 file_collection_(util::make_unique<io::FileCollection>()) {
781 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700782
Adam Lesinskic6284372017-12-04 13:46:23 -0800783 void ExtractCompileSdkVersions(android::AssetManager* assets) {
784 using namespace android;
785
786 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
787 if (cookie == 0) {
788 // No Framework assets loaded. Not a failure.
789 return;
790 }
791
792 std::unique_ptr<Asset> manifest(
793 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
794 if (manifest == nullptr) {
795 // No errors.
796 return;
797 }
798
799 std::string error;
800 std::unique_ptr<xml::XmlResource> manifest_xml =
801 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
802 if (manifest_xml == nullptr) {
803 // No errors.
804 return;
805 }
806
807 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
808 if (attr != nullptr) {
809 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
810 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
811 switch (prim->value.dataType) {
812 case Res_value::TYPE_INT_DEC:
813 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
814 break;
815 case Res_value::TYPE_INT_HEX:
816 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
817 break;
818 default:
819 break;
820 }
821 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
822 compile_sdk_version = *str->value;
823 } else {
824 compile_sdk_version = attr->value;
825 }
826 }
827
828 attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
829 if (attr != nullptr) {
830 Maybe<std::string>& compile_sdk_version_codename =
831 options_.manifest_fixer_options.compile_sdk_version_codename;
832 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
833 compile_sdk_version_codename = *str->value;
834 } else {
835 compile_sdk_version_codename = attr->value;
836 }
837 }
838 }
839
Adam Lesinski8780eb62017-10-31 17:44:39 -0700840 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800841 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700842 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700843 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700844 for (const std::string& path : options_.include_paths) {
845 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700846 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700847 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700848
Adam Lesinski8780eb62017-10-31 17:44:39 -0700849 std::string error;
850 auto zip_collection = io::ZipFileCollection::Create(path, &error);
851 if (zip_collection == nullptr) {
852 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
853 return false;
854 }
855
856 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
857 // Load this as a static library include.
858 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
859 Source(path), std::move(zip_collection), context_->GetDiagnostics());
860 if (static_apk == nullptr) {
861 return false;
862 }
863
Adam Lesinskib522f042017-04-21 16:57:59 -0700864 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800865 // Can't include static libraries when not building a static library (they have no IDs
866 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700867 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800868 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700869 return false;
870 }
871
Adam Lesinski8780eb62017-10-31 17:44:39 -0700872 ResourceTable* table = static_apk->GetResourceTable();
873
874 // If we are using --no-static-lib-packages, we need to rename the package of this table to
875 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700876 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800877 // Since package names can differ, and multiple packages can exist in a ResourceTable,
878 // we place the requirement that all static libraries are built with the package
879 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700880 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700881 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800882 } else {
883 context_->GetDiagnostics()->Error(DiagMessage(path)
884 << "no package with ID 0x7f found in static library");
885 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700886 }
887 }
888
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700889 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700890 util::make_unique<ResourceTableSymbolSource>(table));
891 static_library_includes_.push_back(std::move(static_apk));
892 } else {
893 if (!asset_source->AddAssetPath(path)) {
894 context_->GetDiagnostics()->Error(DiagMessage()
895 << "failed to load include path " << path);
896 return false;
897 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700898 }
899 }
900
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800901 // Capture the shared libraries so that the final resource table can be properly flattened
902 // with support for shared libraries.
903 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700904 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800905 // Capture the included base feature package.
906 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800907 } else if (entry.first == kFrameworkPackageId) {
908 // Try to embed which version of the framework we're compiling against.
909 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
910 // when linking our synthesized 'android:compileSdkVersion' attribute.
911 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
912 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
913 if (symbol != nullptr && symbol->is_public) {
914 // The symbol is present and public, extract the android:versionName and
915 // android:versionCode from the framework AndroidManifest.xml.
916 ExtractCompileSdkVersions(asset_source->GetAssetManager());
917 }
Todd Kennedy32512992018-04-25 16:45:59 -0700918 } else if (asset_source->IsPackageDynamic(entry.first)) {
919 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800920 }
921 }
922
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700923 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700924 return true;
925 }
926
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800927 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700928 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800929 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
930 if (manifest_el == nullptr) {
931 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700932 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800933
934 AppInfo app_info;
935
936 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
937 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
938 return {};
939 }
940
941 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
942 if (!package_attr) {
943 diag->Error(DiagMessage(xml_res->file.source)
944 << "<manifest> must have a 'package' attribute");
945 return {};
946 }
947 app_info.package = package_attr->value;
948
949 if (xml::Attribute* version_code_attr =
950 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
951 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
952 if (!maybe_code) {
953 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
954 << "invalid android:versionCode '" << version_code_attr->value << "'");
955 return {};
956 }
957 app_info.version_code = maybe_code.value();
958 }
959
960 if (xml::Attribute* revision_code_attr =
961 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
962 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
963 if (!maybe_code) {
964 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
965 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
966 return {};
967 }
968 app_info.revision_code = maybe_code.value();
969 }
970
971 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
972 if (!split_name_attr->value.empty()) {
973 app_info.split_name = split_name_attr->value;
974 }
975 }
976
977 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
978 if (xml::Attribute* min_sdk =
979 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700980 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800981 }
982 }
983 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700984 }
985
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700986 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
987 // Postcondition: ResourceTable has only one package left. All others are
988 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700989 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700990 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700991 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
992 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700993 };
994
995 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700996 for (const auto& package : final_table_.packages) {
997 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700998 // We have a package that is not related to the one we're building!
999 for (const auto& type : package->types) {
1000 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001001 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001002
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001003 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001005 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001006 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1007 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1008 << "generated id '" << res_name
1009 << "' for external package '" << package->name
1010 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001011 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001012 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1013 << "defined resource '" << res_name
1014 << "' for external package '" << package->name
1015 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001016 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001018 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001019 }
1020 }
1021 }
1022 }
1023
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001024 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1025 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001026 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001027 return !error;
1028 }
1029
1030 /**
1031 * Returns true if no IDs have been set, false otherwise.
1032 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001033 bool VerifyNoIdsSet() {
1034 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001035 for (const auto& type : package->types) {
1036 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001037 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1038 << StringPrintf("%02x", type->id.value())
1039 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001040 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001041 }
1042
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001043 for (const auto& entry : type->entries) {
1044 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001045 ResourceNameRef res_name(package->name, type->type, entry->name);
1046 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001047 DiagMessage() << "entry " << res_name << " has ID "
1048 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001049 return false;
1050 }
1051 }
1052 }
1053 }
1054 return true;
1055 }
1056
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001057 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1058 if (options_.output_to_directory) {
1059 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001060 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001061 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001062 }
1063 }
1064
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001065 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1066 switch (format) {
1067 case OutputFormat::kApk: {
1068 BigBuffer buffer(1024);
1069 TableFlattener flattener(options_.table_flattener_options, &buffer);
1070 if (!flattener.Consume(context_, table)) {
1071 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1072 return false;
1073 }
1074
1075 io::BigBufferInputStream input_stream(&buffer);
1076 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1077 ArchiveEntry::kAlign, writer);
1078 } break;
1079
1080 case OutputFormat::kProto: {
1081 pb::ResourceTable pb_table;
Ryan Mitchell70414f22018-03-26 11:05:31 -07001082 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001083 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1084 ArchiveEntry::kCompress, writer);
1085 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001086 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001087 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001088 }
1089
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001090 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001091 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001092 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001093 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001094 return true;
1095 }
1096
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001097 std::string out_path;
1098 std::unique_ptr<io::FileOutputStream> fout;
1099 if (options_.generate_java_class_path) {
1100 out_path = options_.generate_java_class_path.value();
1101 file::AppendPath(&out_path, file::PackageToPath(out_package));
1102 if (!file::mkdirs(out_path)) {
1103 context_->GetDiagnostics()->Error(DiagMessage()
1104 << "failed to create directory '" << out_path << "'");
1105 return false;
1106 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001107
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001108 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001109
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001110 fout = util::make_unique<io::FileOutputStream>(out_path);
1111 if (fout->HadError()) {
1112 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1113 << "': " << fout->GetError());
1114 return false;
1115 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001116 }
1117
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001118 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001119 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001120 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1121 if (fout_text->HadError()) {
1122 context_->GetDiagnostics()->Error(DiagMessage()
1123 << "failed writing to '" << out_text_symbols_path.value()
1124 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001125 return false;
1126 }
1127 }
1128
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001129 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001130 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001131 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001132 return false;
1133 }
1134
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001135 return true;
1136 }
1137
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001138 bool GenerateJavaClasses() {
1139 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1140 std::vector<std::string> packages_to_callback;
1141
1142 JavaClassGeneratorOptions template_options;
1143 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1144 template_options.javadoc_annotations = options_.javadoc_annotations;
1145
1146 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1147 template_options.use_final = false;
1148 }
1149
1150 if (context_->GetPackageType() == PackageType::kSharedLib) {
1151 template_options.use_final = false;
1152 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1153 }
1154
1155 const StringPiece actual_package = context_->GetCompilationPackage();
1156 StringPiece output_package = context_->GetCompilationPackage();
1157 if (options_.custom_java_package) {
1158 // Override the output java package to the custom one.
1159 output_package = options_.custom_java_package.value();
1160 }
1161
1162 // Generate the private symbols if required.
1163 if (options_.private_symbols) {
1164 packages_to_callback.push_back(options_.private_symbols.value());
1165
1166 // If we defined a private symbols package, we only emit Public symbols
1167 // to the original package, and private and public symbols to the private package.
1168 JavaClassGeneratorOptions options = template_options;
1169 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1170 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1171 options)) {
1172 return false;
1173 }
1174 }
1175
1176 // Generate copies of the original package R class but with different package names.
1177 // This is to support non-namespaced builds.
1178 for (const std::string& extra_package : options_.extra_java_packages) {
1179 packages_to_callback.push_back(extra_package);
1180
1181 JavaClassGeneratorOptions options = template_options;
1182 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1183 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1184 return false;
1185 }
1186 }
1187
1188 // Generate R classes for each package that was merged (static library).
1189 // Use the actual package's resources only.
1190 for (const std::string& package : table_merger_->merged_packages()) {
1191 packages_to_callback.push_back(package);
1192
1193 JavaClassGeneratorOptions options = template_options;
1194 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1195 if (!WriteJavaFile(&final_table_, package, package, options)) {
1196 return false;
1197 }
1198 }
1199
1200 // Generate the main public R class.
1201 JavaClassGeneratorOptions options = template_options;
1202
1203 // Only generate public symbols if we have a private package.
1204 if (options_.private_symbols) {
1205 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1206 }
1207
1208 if (options.rewrite_callback_options) {
1209 options.rewrite_callback_options.value().packages_to_callback =
1210 std::move(packages_to_callback);
1211 }
1212
1213 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1214 options_.generate_text_symbols_path)) {
1215 return false;
1216 }
1217
1218 return true;
1219 }
1220
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001221 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1222 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001223 return true;
1224 }
1225
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001226 std::unique_ptr<ClassDefinition> manifest_class =
1227 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001229 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001230 // Something bad happened, but we already logged it, so exit.
1231 return false;
1232 }
1233
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001234 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235 // Empty Manifest class, no need to generate it.
1236 return true;
1237 }
1238
1239 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001240 for (const std::string& annotation : options_.javadoc_annotations) {
1241 std::string proper_annotation = "@";
1242 proper_annotation += annotation;
1243 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001244 }
1245
Adam Lesinski0d81f702017-06-27 15:51:09 -07001246 const std::string package_utf8 =
1247 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001248
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001249 std::string out_path = options_.generate_java_class_path.value();
1250 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001251
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001252 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001253 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1254 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001255 return false;
1256 }
1257
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001258 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001259
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001260 io::FileOutputStream fout(out_path);
1261 if (fout.HadError()) {
1262 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1263 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001264 return false;
1265 }
1266
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001267 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1268 fout.Flush();
1269
1270 if (fout.HadError()) {
1271 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1272 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001273 return false;
1274 }
1275 return true;
1276 }
1277
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001278 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001279 if (!out) {
1280 return true;
1281 }
1282
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001283 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001284 io::FileOutputStream fout(out_path);
1285 if (fout.HadError()) {
1286 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1287 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 return false;
1289 }
1290
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001291 proguard::WriteKeepSet(keep_set, &fout);
1292 fout.Flush();
1293
1294 if (fout.HadError()) {
1295 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1296 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001297 return false;
1298 }
1299 return true;
1300 }
1301
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001302 bool MergeStaticLibrary(const std::string& input, bool override) {
1303 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001304 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001305 }
1306
Adam Lesinski8780eb62017-10-31 17:44:39 -07001307 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1308 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001309 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001310 return false;
1311 }
1312
Adam Lesinski8780eb62017-10-31 17:44:39 -07001313 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001314 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001315 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001316 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001317 return false;
1318 }
1319
1320 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001321 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001322 // Merge all resources as if they were in the compilation package. This is the old behavior
1323 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001324
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001325 // Add the package to the set of --extra-packages so we emit an R.java for each library
1326 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001327 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001328 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001329 }
1330
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001331 // Clear the package name, so as to make the resources look like they are coming from the
1332 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001333 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001334 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001335
1336 } else {
1337 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001338 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001339 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001340 }
1341
1342 if (!result) {
1343 return false;
1344 }
1345
1346 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001347 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001348 return true;
1349 }
1350
Adam Lesinski2427dce2017-11-30 15:10:28 -08001351 bool MergeExportedSymbols(const Source& source,
1352 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001353 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001354 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001355 ResourceName res_name = exported_symbol.name;
1356 if (res_name.package.empty()) {
1357 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001358 }
1359
Adam Lesinski00451162017-10-03 07:44:08 -07001360 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001361 if (mangled_name) {
1362 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001363 }
1364
1365 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001366 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001367 bool result =
1368 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1369 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001370 if (!result) {
1371 return false;
1372 }
1373 }
1374 return true;
1375 }
1376
Adam Lesinski2427dce2017-11-30 15:10:28 -08001377 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1378 if (context_->IsVerbose()) {
1379 context_->GetDiagnostics()->Note(DiagMessage()
1380 << "merging '" << compiled_file.name
1381 << "' from compiled file " << compiled_file.source);
1382 }
1383
1384 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1385 return false;
1386 }
1387 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1388 }
1389
Adam Lesinski00451162017-10-03 07:44:08 -07001390 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1391 // If override is true, conflicting resources are allowed to override each other, in order of last
1392 // seen.
1393 // An io::IFileCollection is created from the ZIP file and added to the set of
1394 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001395 bool MergeArchive(const std::string& input, bool override) {
1396 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001397 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001398 }
1399
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001400 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001401 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001402 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001403 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001404 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001405 return false;
1406 }
1407
1408 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001409 for (auto iter = collection->Iterator(); iter->HasNext();) {
1410 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001411 error = true;
1412 }
1413 }
1414
1415 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001416 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417 return !error;
1418 }
1419
Adam Lesinski00451162017-10-03 07:44:08 -07001420 // Takes a path to load and merge into the master ResourceTable. If override is true,
1421 // conflicting resources are allowed to override each other, in order of last seen.
1422 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1423 // as ZIP archive and the files within are merged individually.
1424 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001425 bool MergePath(const std::string& path, bool override) {
1426 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1427 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1428 return MergeArchive(path, override);
1429 } else if (util::EndsWith(path, ".apk")) {
1430 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001431 }
1432
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001433 io::IFile* file = file_collection_->InsertFile(path);
1434 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001435 }
1436
Adam Lesinski00451162017-10-03 07:44:08 -07001437 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1438 // If override is true, conflicting resources are allowed to override each other, in order of last
1439 // seen.
1440 // All other file types are ignored. This is because these files could be coming from a zip,
1441 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001442 bool MergeFile(io::IFile* file, bool override) {
1443 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001444
Adam Lesinski00451162017-10-03 07:44:08 -07001445 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001446 // Since AAPT compiles these file types and appends .flat to them, seeing
1447 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001448 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1449 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1450 << " file passed as argument. Must be "
1451 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001452 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001453 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1454 if (context_->IsVerbose()) {
1455 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1456 return true;
1457 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001458 }
1459
Adam Lesinski00451162017-10-03 07:44:08 -07001460 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1461 if (input_stream == nullptr) {
1462 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1463 return false;
1464 }
1465
1466 if (input_stream->HadError()) {
1467 context_->GetDiagnostics()->Error(DiagMessage(src)
1468 << "failed to open file: " << input_stream->GetError());
1469 return false;
1470 }
1471
1472 ContainerReaderEntry* entry;
1473 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001474
1475 if (reader.HadError()) {
1476 context_->GetDiagnostics()->Error(DiagMessage(src)
1477 << "failed to read file: " << reader.GetError());
1478 return false;
1479 }
1480
Adam Lesinski00451162017-10-03 07:44:08 -07001481 while ((entry = reader.Next()) != nullptr) {
1482 if (entry->Type() == ContainerEntryType::kResTable) {
1483 pb::ResourceTable pb_table;
1484 if (!entry->GetResTable(&pb_table)) {
1485 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1486 << entry->GetError());
1487 return false;
1488 }
1489
1490 ResourceTable table;
1491 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001492 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001493 context_->GetDiagnostics()->Error(DiagMessage(src)
1494 << "failed to deserialize resource table: " << error);
1495 return false;
1496 }
1497
1498 if (!table_merger_->Merge(src, &table, override)) {
1499 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1500 return false;
1501 }
1502 } else if (entry->Type() == ContainerEntryType::kResFile) {
1503 pb::internal::CompiledFile pb_compiled_file;
1504 off64_t offset;
1505 size_t len;
1506 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1507 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1508 << entry->GetError());
1509 return false;
1510 }
1511
1512 ResourceFile resource_file;
1513 std::string error;
1514 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1515 context_->GetDiagnostics()->Error(DiagMessage(src)
1516 << "failed to read compiled header: " << error);
1517 return false;
1518 }
1519
1520 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1521 return false;
1522 }
1523 }
1524 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001525 return true;
1526 }
1527
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001528 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1529 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1530 for (const std::string& assets_dir : options_.assets_dirs) {
1531 Maybe<std::vector<std::string>> files =
1532 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1533 if (!files) {
1534 return false;
1535 }
1536
1537 for (const std::string& file : files.value()) {
1538 std::string full_key = "assets/" + file;
1539 std::string full_path = assets_dir;
1540 file::AppendPath(&full_path, file);
1541
1542 auto iter = merged_assets.find(full_key);
1543 if (iter == merged_assets.end()) {
1544 merged_assets.emplace(std::move(full_key),
1545 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1546 } else if (context_->IsVerbose()) {
1547 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1548 << "asset file overrides '" << full_path << "'");
1549 }
1550 }
1551 }
1552
1553 for (auto& entry : merged_assets) {
1554 uint32_t compression_flags = ArchiveEntry::kCompress;
1555 std::string extension = file::GetExtension(entry.first).to_string();
1556 if (options_.extensions_to_not_compress.count(extension) > 0) {
1557 compression_flags = 0u;
1558 }
1559
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001560 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1561 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001562 return false;
1563 }
1564 }
1565 return true;
1566 }
1567
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001568 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1569 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001570 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1571 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001572 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001573 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1574 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001575 if (!result) {
1576 return false;
1577 }
1578
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001579 ResourceFileFlattenerOptions file_flattener_options;
1580 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001581 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1582 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001583 file_flattener_options.no_auto_version = options_.no_auto_version;
1584 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001585 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001586 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1587 file_flattener_options.update_proguard_spec =
1588 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001589 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001590
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001591 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001592
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001593 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001594 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001595 return false;
1596 }
1597
Adam Lesinski490595a2017-11-07 17:08:07 -08001598 // Hack to fix b/68820737.
1599 // We need to modify the ResourceTable's package name, but that should NOT affect
1600 // anything else being generated, which includes the Java classes.
1601 // If required, the package name is modifed before flattening, and then modified back
1602 // to its original name.
1603 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001604 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1605 // or higher] as invalid. In order to work around this limitation, we allow the use
1606 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1607 // definition of what a valid "split" package ID is to account for this.
1608 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1609 context_->GetPackageId() != kAppPackageId &&
1610 context_->GetPackageId() != kFrameworkPackageId)
1611 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1612 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001613 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1614 // The base APK is included, and this is a feature split. If the base package is
1615 // the same as this package, then we are building an old style Android Instant Apps feature
1616 // split and must apply this workaround to avoid requiring namespaces support.
1617 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1618 if (package_to_rewrite != nullptr) {
1619 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1620
1621 std::string new_package_name =
1622 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1623 app_info_.split_name.value_or_default("feature").c_str());
1624
1625 if (context_->IsVerbose()) {
1626 context_->GetDiagnostics()->Note(
1627 DiagMessage() << "rewriting resource package name for feature split to '"
1628 << new_package_name << "'");
1629 }
1630 package_to_rewrite->name = new_package_name;
1631 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001632 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001633
1634 bool success = FlattenTable(table, options_.output_format, writer);
1635
1636 if (package_to_rewrite != nullptr) {
1637 // Change the name back.
1638 package_to_rewrite->name = context_->GetCompilationPackage();
1639 if (package_to_rewrite->id) {
1640 table->included_packages_.erase(package_to_rewrite->id.value());
1641 }
1642 }
1643
1644 if (!success) {
1645 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1646 }
1647 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001648 }
1649
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001650 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001651 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001652 std::unique_ptr<xml::XmlResource> manifest_xml =
1653 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1654 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001655 return 1;
1656 }
1657
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001658 // First extract the Package name without modifying it (via --rename-manifest-package).
1659 if (Maybe<AppInfo> maybe_app_info =
1660 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001661 const AppInfo& app_info = maybe_app_info.value();
1662 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001663 }
1664
Adam Lesinskic6284372017-12-04 13:46:23 -08001665 // Now that the compilation package is set, load the dependencies. This will also extract
1666 // the Android framework's versionCode and versionName, if they exist.
1667 if (!LoadSymbolsFromIncludePaths()) {
1668 return 1;
1669 }
1670
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001671 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1672 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001673 return 1;
1674 }
1675
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001676 Maybe<AppInfo> maybe_app_info =
1677 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001678 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001679 return 1;
1680 }
1681
Adam Lesinski490595a2017-11-07 17:08:07 -08001682 app_info_ = maybe_app_info.value();
1683 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001684
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001685 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001686
1687 // Override the package ID when it is "android".
1688 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001689 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001690
1691 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001692 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001693 context_->GetDiagnostics()->Error(
1694 DiagMessage() << "package 'android' can only be built as a regular app");
1695 return 1;
1696 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001697 }
1698
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001699 TableMergerOptions table_merger_options;
1700 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001701 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001702
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001703 if (context_->IsVerbose()) {
1704 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001705 << StringPrintf("linking package '%s' using package ID %02x",
1706 context_->GetCompilationPackage().data(),
1707 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001708 }
1709
Adam Lesinski2427dce2017-11-30 15:10:28 -08001710 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1711 // in res/**/*.
1712 {
1713 XmlIdCollector collector;
1714 if (!collector.Consume(context_, manifest_xml.get())) {
1715 return false;
1716 }
1717
1718 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1719 return false;
1720 }
1721 }
1722
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001723 for (const std::string& input : input_files) {
1724 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001725 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001726 return 1;
1727 }
1728 }
1729
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001730 for (const std::string& input : options_.overlay_files) {
1731 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001732 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001733 return 1;
1734 }
1735 }
1736
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001737 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001738 return 1;
1739 }
1740
Adam Lesinskib522f042017-04-21 16:57:59 -07001741 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001742 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001743 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001744 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001745 return 1;
1746 }
1747
1748 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001749 IdAssigner id_assigner(&options_.stable_id_map);
1750 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001751 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001752 return 1;
1753 }
1754
1755 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001756 if (options_.resource_id_map_path) {
1757 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001758 for (auto& type : package->types) {
1759 for (auto& entry : type->entries) {
1760 ResourceName name(package->name, type->type, entry->name);
1761 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001762 options_.stable_id_map[std::move(name)] =
1763 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001764 }
1765 }
1766 }
1767
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001768 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001769 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001770 return 1;
1771 }
1772 }
1773 } else {
1774 // Static libs are merged with other apps, and ID collisions are bad, so
1775 // verify that
1776 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001777 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001778 return 1;
1779 }
1780 }
1781
1782 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001783 context_->SetNameManglerPolicy(
1784 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001785
1786 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001787 context_->GetExternalSymbols()->PrependSource(
1788 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001789
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001790 // Workaround for pre-O runtime that would treat negative resource IDs
1791 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1792 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1793 // are just identifiers.
1794 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1795 if (context_->IsVerbose()) {
1796 context_->GetDiagnostics()->Note(DiagMessage()
1797 << "enabling pre-O feature split ID rewriting");
1798 }
1799 context_->GetExternalSymbols()->SetDelegate(
1800 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1801 }
1802
Adam Lesinski34a16872018-02-23 16:18:10 -08001803 // Before we process anything, remove the resources whose default values don't exist.
1804 // We want to force any references to these to fail the build.
1805 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1806 context_->GetDiagnostics()->Error(DiagMessage()
1807 << "failed removing resources with no defaults");
1808 return 1;
1809 }
1810
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001811 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001812 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001813 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001814 return 1;
1815 }
1816
Adam Lesinskib522f042017-04-21 16:57:59 -07001817 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001818 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001819 context_->GetDiagnostics()->Warn(DiagMessage()
1820 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001821 }
1822 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001823 ProductFilter product_filter(options_.products);
1824 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001825 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001826 return 1;
1827 }
1828 }
1829
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001830 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001831 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001832 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001833 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001834 return 1;
1835 }
1836 }
1837
Adam Lesinskib522f042017-04-21 16:57:59 -07001838 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001839 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001840 context_->GetDiagnostics()->Note(DiagMessage()
1841 << "collapsing resource versions for minimum SDK "
1842 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001843 }
1844
1845 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001846 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001847 return 1;
1848 }
1849 }
1850
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001851 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001852 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001853 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001854 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001855 return 1;
1856 }
1857 }
1858
Adam Koskidc21dea2017-07-21 10:55:27 -07001859 proguard::KeepSet proguard_keep_set =
1860 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001861 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001862
Adam Lesinskib522f042017-04-21 16:57:59 -07001863 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001864 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001865 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001866 context_->GetDiagnostics()->Warn(DiagMessage()
1867 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001868 }
1869 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001870 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1871 // equal to the minSdk.
1872 options_.split_constraints =
1873 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001874
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001875 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001877 return 1;
1878 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001879 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001880
1881 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001882 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001883 auto split_constraints_iter = options_.split_constraints.begin();
1884 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001885 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001886 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1887 << "generating split with configurations '"
1888 << util::Joiner(split_constraints_iter->configs, ", ")
1889 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001890 }
1891
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001892 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001893 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001894 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001895 return 1;
1896 }
1897
1898 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001899 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001900 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001901
1902 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001903 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001904 context_->GetDiagnostics()->Error(DiagMessage()
1905 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001906 return 1;
1907 }
1908
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001909 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1910 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001911 return 1;
1912 }
1913
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001914 ++path_iter;
1915 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001916 }
1917 }
1918
1919 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001920 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001921 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001922 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001923 return 1;
1924 }
1925
1926 bool error = false;
1927 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001928 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001929 // (aka, which package the AndroidManifest.xml is coming from).
1930 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001931 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001932
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 XmlReferenceLinker manifest_linker;
1934 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1935 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001936 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001937 error = true;
1938 }
1939
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001941 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001942 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001943 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001944 }
1945
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001946 if (options_.generate_java_class_path) {
1947 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001948 error = true;
1949 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001950 }
1951
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001952 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001953 // PackageParser will fail if URIs are removed from
1954 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001955 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1956 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001957 error = true;
1958 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001959 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001960 } else {
1961 error = true;
1962 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001963 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001964
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001965 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001966 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001967 return 1;
1968 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001969
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001970 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1971 return 1;
1972 }
1973
1974 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001975 return 1;
1976 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001977
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001978 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001979 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001980 return 1;
1981 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001982 }
1983
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001984 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001985 return 1;
1986 }
1987
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001988 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1989 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001990 return 1;
1991 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001992 return 0;
1993 }
1994
1995 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 LinkOptions options_;
1997 LinkContext* context_;
1998 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001999
Adam Lesinski490595a2017-11-07 17:08:07 -08002000 AppInfo app_info_;
2001
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002002 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002003
2004 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002005 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002006
Adam Lesinski8780eb62017-10-31 17:44:39 -07002007 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002008 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002009 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002010
Adam Lesinski8780eb62017-10-31 17:44:39 -07002011 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2012 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2013
2014 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2015 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002016
2017 // The set of shared libraries being used, mapping their assigned package ID to package name.
2018 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002019
2020 // The package name of the base application, if it is included.
2021 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002022};
2023
Chris Warrington820d72a2017-04-27 15:27:01 +01002024int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
2025 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002026 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002027 std::vector<std::string> overlay_arg_list;
2028 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002029 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07002030 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002031 Maybe<std::string> preferred_density;
2032 Maybe<std::string> product_list;
2033 bool legacy_x_flag = false;
2034 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002035 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002036 bool shared_lib = false;
2037 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002038 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002039 Maybe<std::string> stable_id_file_path;
2040 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002041 Flags flags =
2042 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002043 .RequiredFlag("-o", "Output path.", &options.output_path)
2044 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002045 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002046 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002047 .OptionalFlagList("-A",
2048 "An assets directory to include in the APK. These are unprocessed.",
2049 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002050 .OptionalFlagList("-R",
2051 "Compilation unit to link, using `overlay` semantics.\n"
2052 "The last conflicting resource given takes precedence.",
2053 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002054 .OptionalFlag("--package-id",
2055 "Specify the package ID to use for this app. Must be greater or equal to\n"
2056 "0x7f and can't be used with --static-lib or --shared-lib.",
2057 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002058 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002059 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002060 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002061 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002062 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002063 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002064 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07002065 .OptionalSwitch("--proguard-conditional-keep-rules",
2066 "Generate conditional Proguard keep rules.",
2067 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002068 .OptionalSwitch("--no-auto-version",
2069 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002070 &options.no_auto_version)
2071 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002072 "Disables automatic versioning of vector drawables. Use this only\n"
2073 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002074 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002075 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002076 "Disables automatic versioning of transition resources. Use this only\n"
2077 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002078 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002079 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002080 "Disables automatic deduping of resources with\n"
2081 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002082 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002083 .OptionalSwitch("--enable-sparse-encoding",
2084 "Enables encoding sparse entries using a binary search tree.\n"
2085 "This decreases APK size at the cost of resource retrieval performance.",
2086 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002087 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002088 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002089 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002090 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07002091 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07002092 "Comma separated list of configurations to include. The default\n"
2093 "is all configurations.",
2094 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002095 .OptionalFlag("--preferred-density",
2096 "Selects the closest matching density and strips out all others.",
2097 &preferred_density)
2098 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002099 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002100 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002101 &options.output_to_directory)
2102 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002103 "Removes XML namespace prefix and URI information from\n"
2104 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002105 &options.no_xml_namespaces)
2106 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002107 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002108 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002109 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002110 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002111 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002112 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002113 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2114 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002115 &options.manifest_fixer_options.version_code_default)
2116 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002117 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002118 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002119 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
2120 &shared_lib)
2121 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002122 .OptionalSwitch("--proto-format",
2123 "Generates compiled resources in Protobuf format.\n"
2124 "Suitable as input to the bundle tool for generating an App Bundle.",
2125 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002126 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002127 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002128 &options.no_static_lib_packages)
2129 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002130 "Generates R.java without the final modifier. This is implied when\n"
2131 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002132 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002133 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002134 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002135 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002136 "Emit a file at the given path with a list of name to ID mappings,\n"
2137 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002138 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002139 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002140 "Package name to use when generating R.java for private symbols.\n"
2141 "If not specified, public and private symbols will use the application's\n"
2142 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002143 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002144 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002145 &options.custom_java_package)
2146 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002147 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002148 &extra_java_packages)
2149 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002150 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002151 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002152 .OptionalFlag("--output-text-symbols",
2153 "Generates a text file containing the resource symbols of the R class in\n"
2154 "the specified folder.",
2155 &options.generate_text_symbols_path)
Todd Kennedy32512992018-04-25 16:45:59 -07002156 .OptionalSwitch("--allow-reserved-package-id",
2157 "Allows the use of a reserved package ID. This should on be used for\n"
2158 "packages with a pre-O min-sdk\n",
2159 &options.allow_reserved_package_id)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002160 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002161 "Allows the addition of new resources in overlays without\n"
2162 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002163 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002164 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002165 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002166 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002167 "Changes the name of the target package for instrumentation. Most useful\n"
2168 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002169 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002170 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002171 &options.extensions_to_not_compress)
Izabela Orlowskaad9e1322017-12-19 16:22:42 +00002172 .OptionalSwitch("--warn-manifest-validation",
2173 "Treat manifest validation errors as warnings.",
2174 &options.manifest_fixer_options.warn_validation)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002175 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002176 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002177 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2178 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002179 &split_args)
Ryan Mitchelle5b38a62018-03-23 13:35:00 -07002180 .OptionalSwitch("-v", "Enables verbose logging.", &verbose)
2181 .OptionalSwitch("--debug-mode",
2182 "Inserts android:debuggable=\"true\" in to the application node of the\n"
2183 "manifest, making the application debuggable even on production devices.",
2184 &options.manifest_fixer_options.debug_mode);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002185
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002186 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002187 return 1;
2188 }
2189
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002190 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002191 std::vector<std::string> arg_list;
2192 for (const std::string& arg : flags.GetArgs()) {
2193 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002194 const std::string path = arg.substr(1, arg.size() - 1);
2195 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002196 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2197 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002198 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002199 }
2200 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002201 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002202 }
2203 }
2204
2205 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002206 for (const std::string& arg : overlay_arg_list) {
2207 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002208 const std::string path = arg.substr(1, arg.size() - 1);
2209 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002210 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2211 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002212 return 1;
2213 }
2214 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002215 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002216 }
2217 }
2218
2219 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002220 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002221 }
2222
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002223 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2224 context.GetDiagnostics()->Error(
2225 DiagMessage()
2226 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002227 return 1;
2228 }
2229
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002230 // The default build type.
2231 context.SetPackageType(PackageType::kApp);
2232 context.SetPackageId(kAppPackageId);
2233
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002234 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002235 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002236 context.SetPackageId(0x00);
2237 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002238 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002239 options.output_format = OutputFormat::kProto;
2240 } else if (proto_format) {
2241 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002242 }
2243
2244 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002245 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002246 context.GetDiagnostics()->Error(
2247 DiagMessage() << "can't specify --package-id when not building a regular app");
2248 return 1;
2249 }
2250
2251 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2252 if (!maybe_package_id_int) {
2253 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2254 << "' is not a valid integer");
2255 return 1;
2256 }
2257
2258 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002259 if (package_id_int > std::numeric_limits<uint8_t>::max()
2260 || package_id_int == kFrameworkPackageId
2261 || (!options.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002262 context.GetDiagnostics()->Error(
2263 DiagMessage() << StringPrintf(
2264 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2265 return 1;
2266 }
2267 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2268 }
2269
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002270 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002271 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002272 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002273 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002274 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002275 }
2276 }
2277
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002278 if (product_list) {
2279 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002280 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002281 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002282 }
2283 }
2284 }
2285
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002286 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002287 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002288 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2289 if (filter == nullptr) {
2290 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002291 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002292 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002293 }
2294
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002295 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002296 Maybe<uint16_t> density =
2297 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2298 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002299 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002300 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002301 options.table_splitter_options.preferred_densities.push_back(density.value());
2302 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002303
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002304 // Parse the split parameters.
2305 for (const std::string& split_arg : split_args) {
2306 options.split_paths.push_back({});
2307 options.split_constraints.push_back({});
2308 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2309 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002310 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002311 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002312 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002313
Adam Lesinskib522f042017-04-21 16:57:59 -07002314 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002315 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2316 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002317 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002318 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002319 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002320
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002321 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002322 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002323 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2324 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2325 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2326 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2327
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002328 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002329 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002330 options.no_auto_version = true;
2331 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002332 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002333 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002334
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002335 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002336 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002337}
2338
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002339} // namespace aapt