blob: 13e090d9d8430f19ff9ecc4fe6467ed2da6f8c89 [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
Ryan Mitchell833a1a62018-07-10 13:51:36 -070017#include "Link.h"
18
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019#include <sys/stat.h>
Adam Lesinskic6284372017-12-04 13:46:23 -080020#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070021
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050022#include <algorithm>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070023#include <queue>
24#include <unordered_map>
25#include <vector>
26
27#include "android-base/errors.h"
28#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080029#include "android-base/stringprintf.h"
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020030#include "androidfw/Locale.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080031#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070032
Adam Lesinski1ab598f2015-08-14 14:26:04 -070033#include "AppInfo.h"
34#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070035#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070036#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080037#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070038#include "ResourceValues.h"
39#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070040#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070041#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080042#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080043#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070045#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070046#include "format/binary/TableFlattener.h"
47#include "format/binary/XmlFlattener.h"
48#include "format/proto/ProtoDeserialize.h"
49#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070050#include "io/BigBufferStream.h"
51#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070053#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080054#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070055#include "java/JavaClassGenerator.h"
56#include "java/ManifestClassGenerator.h"
57#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070059#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080060#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080061#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080062#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070063#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070064#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080065#include "optimize/ResourceDeduper.h"
66#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067#include "process/IResourceTableConsumer.h"
68#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080069#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080070#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080072#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070073
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070074using ::aapt::io::FileInputStream;
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020075using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070076using ::android::StringPiece;
77using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070078
Adam Lesinski1ab598f2015-08-14 14:26:04 -070079namespace aapt {
80
Ryan Mitchell22dc5312020-06-01 12:17:07 -070081constexpr uint8_t kAndroidPackageId = 0x01;
82
Adam Lesinski64587af2016-02-18 18:33:06 -080083class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070084 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -080085 explicit LinkContext(IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +010086 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -070087 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070088
Adam Lesinskib522f042017-04-21 16:57:59 -070089 PackageType GetPackageType() override {
90 return package_type_;
91 }
92
93 void SetPackageType(PackageType type) {
94 package_type_ = type;
95 }
96
Adam Lesinskid0f492d2017-04-03 18:12:45 -070097 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +010098 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070099 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700100
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700101 NameMangler* GetNameMangler() override {
102 return &name_mangler_;
103 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700104
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700105 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
106 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700107 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800108
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700109 const std::string& GetCompilationPackage() override {
110 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700111 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700112
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700113 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800114 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700115 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800116
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700117 uint8_t GetPackageId() override {
118 return package_id_;
119 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700120
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700121 void SetPackageId(uint8_t id) {
122 package_id_ = id;
123 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800124
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700125 SymbolTable* GetExternalSymbols() override {
126 return &symbols_;
127 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800128
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700129 bool IsVerbose() override {
130 return verbose_;
131 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800132
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700133 void SetVerbose(bool val) {
134 verbose_ = val;
135 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800136
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700137 int GetMinSdkVersion() override {
138 return min_sdk_version_;
139 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700140
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700141 void SetMinSdkVersion(int minSdk) {
142 min_sdk_version_ = minSdk;
143 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700144
Udam Sainib228df32019-06-18 16:50:34 -0700145 const std::set<std::string>& GetSplitNameDependencies() override {
146 return split_name_dependencies_;
147 }
148
149 void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
150 split_name_dependencies_ = split_name_dependencies;
151 }
152
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700153 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700154 DISALLOW_COPY_AND_ASSIGN(LinkContext);
155
Adam Lesinskib522f042017-04-21 16:57:59 -0700156 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100157 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700158 NameMangler name_mangler_;
159 std::string compilation_package_;
160 uint8_t package_id_ = 0x0;
161 SymbolTable symbols_;
162 bool verbose_ = false;
163 int min_sdk_version_ = 0;
Udam Sainib228df32019-06-18 16:50:34 -0700164 std::set<std::string> split_name_dependencies_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700165};
166
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700167// A custom delegate that generates compatible pre-O IDs for use with feature splits.
168// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
169// is interpreted as a negative number. Some verification was wrongly assuming negative values
170// were invalid.
171//
172// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
173// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
174// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800175//
176// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700177class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
178 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800179 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700180 }
181
182 virtual ~FeatureSplitSymbolTableDelegate() = default;
183
184 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
185 const ResourceName& name,
186 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
187 std::unique_ptr<SymbolTable::Symbol> symbol =
188 DefaultSymbolTableDelegate::FindByName(name, sources);
189 if (symbol == nullptr) {
190 return {};
191 }
192
193 // Check to see if this is an 'id' with the target package.
194 if (name.type == ResourceType::kId && symbol->id) {
195 ResourceId* id = &symbol->id.value();
196 if (id->package_id() > kAppPackageId) {
197 // Rewrite the resource ID to be compatible pre-O.
198 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
199
200 // Check that this doesn't overlap another resource.
201 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
202 // The ID overlaps, so log a message (since this is a weird failure) and fail.
203 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
204 << " for pre-O feature split support");
205 return {};
206 }
207
208 if (context_->IsVerbose()) {
209 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
210 << ") -> (" << rewritten_id << ")");
211 }
212
213 *id = rewritten_id;
214 }
215 }
216 return symbol;
217 }
218
219 private:
220 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
221
222 IAaptContext* context_;
223};
224
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700225static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
226 const StringPiece& path, bool keep_raw_values, bool utf16,
227 OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800228 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700229 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700230 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
231 << (keep_raw_values ? "true" : "false")
232 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700233 }
234
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700235 switch (format) {
236 case OutputFormat::kApk: {
237 BigBuffer buffer(1024);
238 XmlFlattenerOptions options = {};
239 options.keep_raw_values = keep_raw_values;
240 options.use_utf16 = utf16;
241 XmlFlattener flattener(&buffer, options);
242 if (!flattener.Consume(context, &xml_res)) {
243 return false;
244 }
245
246 io::BigBufferInputStream input_stream(&buffer);
247 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
248 ArchiveEntry::kCompress, writer);
249 } break;
250
251 case OutputFormat::kProto: {
252 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800253 // Strip whitespace text nodes from tha AndroidManifest.xml
254 SerializeXmlOptions options;
255 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700256 SerializeXmlResourceToPb(xml_res, &pb_node);
257 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
258 writer);
259 } break;
260 }
261 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800262}
263
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700264// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700265static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800266 TRACE_CALL();
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700267 FileInputStream fin(path);
268 if (fin.HadError()) {
269 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700270 return {};
271 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700272 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800273}
274
Adam Lesinski355f2852016-02-13 20:26:45 -0800275struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700276 bool no_auto_version = false;
277 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900278 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700279 bool no_xml_namespaces = false;
280 bool keep_raw_values = false;
281 bool do_not_compress_anything = false;
282 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100283 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700284 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700285 std::unordered_set<std::string> extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +0100286 Maybe<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800287};
288
Adam Lesinskic744ae82017-05-17 19:28:38 -0700289// A sampling of public framework resource IDs.
290struct R {
291 struct attr {
292 enum : uint32_t {
293 paddingLeft = 0x010100d6u,
294 paddingRight = 0x010100d8u,
295 paddingHorizontal = 0x0101053du,
296
297 paddingTop = 0x010100d7u,
298 paddingBottom = 0x010100d9u,
299 paddingVertical = 0x0101053eu,
300
301 layout_marginLeft = 0x010100f7u,
302 layout_marginRight = 0x010100f9u,
303 layout_marginHorizontal = 0x0101053bu,
304
305 layout_marginTop = 0x010100f8u,
306 layout_marginBottom = 0x010100fau,
307 layout_marginVertical = 0x0101053cu,
308 };
309 };
310};
311
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700312template <typename T>
313uint32_t GetCompressionFlags(const StringPiece& str, T options) {
314 if (options.do_not_compress_anything) {
315 return 0;
316 }
317
318 if (options.regex_to_not_compress
319 && std::regex_search(str.to_string(), options.regex_to_not_compress.value())) {
320 return 0;
321 }
322
323 for (const std::string& extension : options.extensions_to_not_compress) {
324 if (util::EndsWith(str, extension)) {
325 return 0;
326 }
327 }
328 return ArchiveEntry::kCompress;
329}
330
Adam Lesinski355f2852016-02-13 20:26:45 -0800331class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700332 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700333 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700334 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800335
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700336 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800337
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700338 private:
339 struct FileOperation {
340 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700341
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700342 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700343 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700344
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700345 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700346 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700347
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700348 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700349 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700350
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700351 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700352 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700353 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800354
Adam Lesinskic744ae82017-05-17 19:28:38 -0700355 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
356 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800357
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700358 ResourceFileFlattenerOptions options_;
359 IAaptContext* context_;
360 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700361 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800362};
363
Adam Lesinskic744ae82017-05-17 19:28:38 -0700364ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
365 IAaptContext* context, proguard::KeepSet* keep_set)
366 : options_(options), context_(context), keep_set_(keep_set) {
367 SymbolTable* symm = context_->GetExternalSymbols();
368
369 // Build up the rules for degrading newer attributes to older ones.
370 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
371 // generated from the attribute definitions themselves (b/62028956).
372 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
373 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800374 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
375 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700376 };
377 rules_[R::attr::paddingHorizontal] =
378 util::make_unique<DegradeToManyRule>(std::move(replacements));
379 }
380
381 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
382 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800383 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
384 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700385 };
386 rules_[R::attr::paddingVertical] =
387 util::make_unique<DegradeToManyRule>(std::move(replacements));
388 }
389
390 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
391 std::vector<ReplacementAttr> replacements{
392 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800393 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700394 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800395 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700396 };
397 rules_[R::attr::layout_marginHorizontal] =
398 util::make_unique<DegradeToManyRule>(std::move(replacements));
399 }
400
401 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
402 std::vector<ReplacementAttr> replacements{
403 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800404 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700405 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800406 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700407 };
408 rules_[R::attr::layout_marginVertical] =
409 util::make_unique<DegradeToManyRule>(std::move(replacements));
410 }
411}
412
Adam Lesinskibb94f322017-07-12 07:41:55 -0700413static bool IsTransitionElement(const std::string& name) {
414 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
415 name == "changeImageTransform" || name == "changeTransform" ||
416 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
417 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
418 name == "transitionManager";
419}
420
421static bool IsVectorElement(const std::string& name) {
422 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800423 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
424 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700425}
426
Adam Lesinskic744ae82017-05-17 19:28:38 -0700427template <typename T>
428std::vector<T> make_singleton_vec(T&& val) {
429 std::vector<T> vec;
430 vec.emplace_back(std::forward<T>(val));
431 return vec;
432}
433
434std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
435 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800436 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700437 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700438 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700439
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700440 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700441 context_->GetDiagnostics()->Note(DiagMessage()
442 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700443 }
444
Adam Lesinski00451162017-10-03 07:44:08 -0700445 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
446 // that existing projects have out-of-date references which pass compilation.
447 xml::StripAndroidStudioAttributes(doc->root.get());
448
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700449 XmlReferenceLinker xml_linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100450 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700451 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700452 }
453
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700454 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700455 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700456 }
457
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700458 if (options_.no_xml_namespaces) {
459 XmlNamespaceRemover namespace_remover;
460 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700461 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800462 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700463 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800464
Adam Lesinskibb94f322017-07-12 07:41:55 -0700465 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700466 return make_singleton_vec(std::move(file_op->xml_to_flatten));
467 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700468
Adam Lesinskibb94f322017-07-12 07:41:55 -0700469 if (options_.no_version_vectors || options_.no_version_transitions) {
470 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700471 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700472 if (el && el->namespace_uri.empty()) {
473 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
474 (options_.no_version_transitions && IsTransitionElement(el->name))) {
475 return make_singleton_vec(std::move(file_op->xml_to_flatten));
476 }
477 }
478 }
479
Adam Lesinskic744ae82017-05-17 19:28:38 -0700480 const ConfigDescription& config = file_op->config;
481 ResourceEntry* entry = file_op->entry;
482
483 XmlCompatVersioner xml_compat_versioner(&rules_);
484 const util::Range<ApiVersion> api_range{config.sdkVersion,
485 FindNextApiVersionForConfig(entry, config)};
486 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800487}
488
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800489ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
490 switch (format) {
491 case OutputFormat::kApk:
492 return ResourceFile::Type::kBinaryXml;
493 case OutputFormat::kProto:
494 return ResourceFile::Type::kProtoXml;
495 }
496 LOG_ALWAYS_FATAL("unreachable");
497 return ResourceFile::Type::kUnknown;
498}
499
Ryan Mitchell70f79722018-08-13 07:37:24 -0700500static auto kDrawableVersions = std::map<std::string, ApiVersion>{
501 { "adaptive-icon" , SDK_O },
502};
503
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700504bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800505 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700506 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700507 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800508
Adam Koskidc21dea2017-07-21 10:55:27 -0700509 proguard::CollectResourceReferences(context_, table, keep_set_);
510
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700511 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700512 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
513
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700514 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700515 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700516 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700517 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800518
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700519 // Populate the queue with all files in the ResourceTable.
520 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700521 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700522 // WARNING! Do not insert or remove any resources while executing in this scope. It will
523 // corrupt the iteration order.
524
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700525 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700526 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700527 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700528 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700529
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700530 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700531 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700532 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700534 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700535 }
536
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700537 FileOperation file_op;
538 file_op.entry = entry.get();
539 file_op.dst_path = *file_ref->path;
540 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700541 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700542
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700543 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700544 (file_ref->type == ResourceFile::Type::kBinaryXml ||
545 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700547 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700548 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 << "failed to open file");
550 return false;
551 }
552
Adam Lesinski00451162017-10-03 07:44:08 -0700553 if (file_ref->type == ResourceFile::Type::kProtoXml) {
554 pb::XmlNode pb_xml_node;
555 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
556 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700557 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700558 return false;
559 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560
Adam Lesinski00451162017-10-03 07:44:08 -0700561 std::string error;
562 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
563 if (file_op.xml_to_flatten == nullptr) {
564 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700565 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700566 return false;
567 }
568 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700569 std::string error_str;
570 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700571 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700572 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
573 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700574 return false;
575 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700576 }
577
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800578 // Update the type that this file will be written as.
579 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
580
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700581 file_op.xml_to_flatten->file.config = config_value->config;
582 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700583 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700584 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700585
586 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
587 // else we end up copying the string in the std::make_pair() method,
588 // then creating a StringPiece from the copy, which would cause us
589 // to end up referencing garbage in the map.
590 const StringPiece entry_name(entry->name);
591 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
592 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700593 }
594 }
595
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700596 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700597 for (auto& map_entry : config_sorted_files) {
598 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700599 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700600
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700601 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700602 // Check minimum sdk versions supported for drawables
603 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
604 if (drawable_entry != kDrawableVersions.end()) {
605 if (drawable_entry->second > context_->GetMinSdkVersion()
606 && drawable_entry->second > config.sdkVersion) {
607 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
608 << "<" << drawable_entry->first << "> elements "
609 << "require a sdk version of at least "
610 << (int16_t) drawable_entry->second);
611 error = true;
612 continue;
613 }
614 }
615
Adam Lesinskic744ae82017-05-17 19:28:38 -0700616 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
617 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700618 if (versioned_docs.empty()) {
619 error = true;
620 continue;
621 }
622
Adam Lesinskic744ae82017-05-17 19:28:38 -0700623 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
624 std::string dst_path = file_op.dst_path;
625 if (doc->file.config != file_op.config) {
626 // Only add the new versioned configurations.
627 if (context_->IsVerbose()) {
628 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
629 << "auto-versioning resource from config '"
630 << config << "' -> '" << doc->file.config << "'");
631 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700632
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800633 const ResourceFile& file = doc->file;
634 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
635
636 std::unique_ptr<FileReference> file_ref =
637 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
638 file_ref->SetSource(doc->file.source);
639 // Update the output format of this XML file.
640 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
641 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
642 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700643 return false;
644 }
645 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700646
647 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
648 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700649 }
650 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700651 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700652 GetCompressionFlags(file_op.dst_path, options_),
653 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700654 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700655 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700656 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700657 }
658 return !error;
659}
660
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700661static bool WriteStableIdMapToPath(IDiagnostics* diag,
662 const std::unordered_map<ResourceName, ResourceId>& id_map,
663 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800664 io::FileOutputStream fout(id_map_path);
665 if (fout.HadError()) {
666 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700667 return false;
668 }
669
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800670 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700671 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700672 const ResourceName& name = entry.first;
673 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800674 printer.Print(name.to_string());
675 printer.Print(" = ");
676 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700677 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800678 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700679
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800680 if (fout.HadError()) {
681 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 return false;
683 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700684 return true;
685}
686
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700687static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
688 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700689 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700690 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700691 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700692 return false;
693 }
694
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700695 out_id_map->clear();
696 size_t line_no = 0;
697 for (StringPiece line : util::Tokenize(content, '\n')) {
698 line_no++;
699 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 if (line.empty()) {
701 continue;
702 }
703
704 auto iter = std::find(line.begin(), line.end(), '=');
705 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700706 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700707 return false;
708 }
709
710 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700711 StringPiece res_name_str =
712 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
713 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700714 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
715 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 return false;
717 }
718
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700719 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
720 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700721 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700722
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700723 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
724 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700725 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
726 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700727 return false;
728 }
729
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700730 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731 }
732 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700733}
734
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700735class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700737 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700738 : options_(options),
739 context_(context),
740 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700741 file_collection_(util::make_unique<io::FileCollection>()) {
742 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700743
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800744 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800745 using namespace android;
746
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000747 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
748 // we're looking for the first attribute resource in the system package.
749 android::ApkAssetsCookie cookie;
750 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
751 cookie = value->cookie;
752 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800753 // No Framework assets loaded. Not a failure.
754 return;
755 }
756
757 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800758 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800759 if (manifest == nullptr) {
760 // No errors.
761 return;
762 }
763
764 std::string error;
765 std::unique_ptr<xml::XmlResource> manifest_xml =
766 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
767 if (manifest_xml == nullptr) {
768 // No errors.
769 return;
770 }
771
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700772 if (!options_.manifest_fixer_options.compile_sdk_version) {
773 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
774 if (attr != nullptr) {
775 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
776 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
777 switch (prim->value.dataType) {
778 case Res_value::TYPE_INT_DEC:
779 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
780 break;
781 case Res_value::TYPE_INT_HEX:
782 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
783 break;
784 default:
785 break;
786 }
787 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
788 compile_sdk_version = *str->value;
789 } else {
790 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800791 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800792 }
793 }
794
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700795 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
796 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
797 if (attr != nullptr) {
798 Maybe<std::string>& compile_sdk_version_codename =
799 options_.manifest_fixer_options.compile_sdk_version_codename;
800 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
801 compile_sdk_version_codename = *str->value;
802 } else {
803 compile_sdk_version_codename = attr->value;
804 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800805 }
806 }
807 }
808
Adam Lesinski8780eb62017-10-31 17:44:39 -0700809 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800810 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700811 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800812 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700813 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700814 for (const std::string& path : options_.include_paths) {
815 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700816 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700817 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700818
Adam Lesinski8780eb62017-10-31 17:44:39 -0700819 std::string error;
820 auto zip_collection = io::ZipFileCollection::Create(path, &error);
821 if (zip_collection == nullptr) {
822 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
823 return false;
824 }
825
826 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
827 // Load this as a static library include.
828 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
829 Source(path), std::move(zip_collection), context_->GetDiagnostics());
830 if (static_apk == nullptr) {
831 return false;
832 }
833
Adam Lesinskib522f042017-04-21 16:57:59 -0700834 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800835 // Can't include static libraries when not building a static library (they have no IDs
836 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700837 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800838 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700839 return false;
840 }
841
Adam Lesinski8780eb62017-10-31 17:44:39 -0700842 ResourceTable* table = static_apk->GetResourceTable();
843
844 // If we are using --no-static-lib-packages, we need to rename the package of this table to
845 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700846 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800847 // Since package names can differ, and multiple packages can exist in a ResourceTable,
848 // we place the requirement that all static libraries are built with the package
849 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700850 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700851 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800852 } else {
853 context_->GetDiagnostics()->Error(DiagMessage(path)
854 << "no package with ID 0x7f found in static library");
855 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700856 }
857 }
858
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700859 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700860 util::make_unique<ResourceTableSymbolSource>(table));
861 static_library_includes_.push_back(std::move(static_apk));
862 } else {
863 if (!asset_source->AddAssetPath(path)) {
864 context_->GetDiagnostics()->Error(DiagMessage()
865 << "failed to load include path " << path);
866 return false;
867 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700868 }
869 }
870
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800871 // Capture the shared libraries so that the final resource table can be properly flattened
872 // with support for shared libraries.
873 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700874 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800875 // Capture the included base feature package.
876 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800877 } else if (entry.first == kFrameworkPackageId) {
878 // Try to embed which version of the framework we're compiling against.
879 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
880 // when linking our synthesized 'android:compileSdkVersion' attribute.
881 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
882 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
883 if (symbol != nullptr && symbol->is_public) {
884 // The symbol is present and public, extract the android:versionName and
885 // android:versionCode from the framework AndroidManifest.xml.
886 ExtractCompileSdkVersions(asset_source->GetAssetManager());
887 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700888 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700889 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800890 }
891 }
892
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700893 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700894 return true;
895 }
896
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800897 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800898 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700899 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800900 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
901 if (manifest_el == nullptr) {
902 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700903 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800904
905 AppInfo app_info;
906
907 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
908 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
909 return {};
910 }
911
912 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
913 if (!package_attr) {
914 diag->Error(DiagMessage(xml_res->file.source)
915 << "<manifest> must have a 'package' attribute");
916 return {};
917 }
918 app_info.package = package_attr->value;
919
920 if (xml::Attribute* version_code_attr =
921 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
922 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
923 if (!maybe_code) {
924 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
925 << "invalid android:versionCode '" << version_code_attr->value << "'");
926 return {};
927 }
928 app_info.version_code = maybe_code.value();
929 }
930
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700931 if (xml::Attribute* version_code_major_attr =
932 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
933 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
934 if (!maybe_code) {
935 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
936 << "invalid android:versionCodeMajor '"
937 << version_code_major_attr->value << "'");
938 return {};
939 }
940 app_info.version_code_major = maybe_code.value();
941 }
942
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800943 if (xml::Attribute* revision_code_attr =
944 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
945 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
946 if (!maybe_code) {
947 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
948 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
949 return {};
950 }
951 app_info.revision_code = maybe_code.value();
952 }
953
954 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
955 if (!split_name_attr->value.empty()) {
956 app_info.split_name = split_name_attr->value;
957 }
958 }
959
960 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
961 if (xml::Attribute* min_sdk =
962 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700963 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800964 }
965 }
Udam Sainib228df32019-06-18 16:50:34 -0700966
967 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
968 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
969 if (const xml::Attribute* split_name =
970 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
971 if (!split_name->value.empty()) {
972 app_info.split_name_dependencies.insert(split_name->value);
973 }
974 }
975 }
976 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800977 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700978 }
979
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700980 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
981 // Postcondition: ResourceTable has only one package left. All others are
982 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700983 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700984 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700985 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
986 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700987 };
988
989 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700990 for (const auto& package : final_table_.packages) {
991 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700992 // We have a package that is not related to the one we're building!
993 for (const auto& type : package->types) {
994 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700995 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700997 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700998 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700999 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001000 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1001 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1002 << "generated id '" << res_name
1003 << "' for external package '" << package->name
1004 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001005 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001006 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1007 << "defined resource '" << res_name
1008 << "' for external package '" << package->name
1009 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001010 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001011 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001012 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013 }
1014 }
1015 }
1016 }
1017
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001018 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1019 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001020 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001021 return !error;
1022 }
1023
1024 /**
1025 * Returns true if no IDs have been set, false otherwise.
1026 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001027 bool VerifyNoIdsSet() {
1028 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001029 for (const auto& type : package->types) {
1030 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001031 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1032 << StringPrintf("%02x", type->id.value())
1033 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001034 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001035 }
1036
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001037 for (const auto& entry : type->entries) {
1038 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001039 ResourceNameRef res_name(package->name, type->type, entry->name);
1040 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001041 DiagMessage() << "entry " << res_name << " has ID "
1042 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001043 return false;
1044 }
1045 }
1046 }
1047 }
1048 return true;
1049 }
1050
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001051 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1052 if (options_.output_to_directory) {
1053 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001054 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001055 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001056 }
1057 }
1058
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001059 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001060 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001061 switch (format) {
1062 case OutputFormat::kApk: {
1063 BigBuffer buffer(1024);
1064 TableFlattener flattener(options_.table_flattener_options, &buffer);
1065 if (!flattener.Consume(context_, table)) {
1066 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1067 return false;
1068 }
1069
1070 io::BigBufferInputStream input_stream(&buffer);
1071 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1072 ArchiveEntry::kAlign, writer);
1073 } break;
1074
1075 case OutputFormat::kProto: {
1076 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001077 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1078 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001079 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1080 ArchiveEntry::kCompress, writer);
1081 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001082 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001083 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001084 }
1085
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001086 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001087 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001088 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001089 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001090 return true;
1091 }
1092
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001093 std::string out_path;
1094 std::unique_ptr<io::FileOutputStream> fout;
1095 if (options_.generate_java_class_path) {
1096 out_path = options_.generate_java_class_path.value();
1097 file::AppendPath(&out_path, file::PackageToPath(out_package));
1098 if (!file::mkdirs(out_path)) {
1099 context_->GetDiagnostics()->Error(DiagMessage()
1100 << "failed to create directory '" << out_path << "'");
1101 return false;
1102 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001103
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001104 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001105
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001106 fout = util::make_unique<io::FileOutputStream>(out_path);
1107 if (fout->HadError()) {
1108 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1109 << "': " << fout->GetError());
1110 return false;
1111 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001112 }
1113
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001114 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001115 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001116 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1117 if (fout_text->HadError()) {
1118 context_->GetDiagnostics()->Error(DiagMessage()
1119 << "failed writing to '" << out_text_symbols_path.value()
1120 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001121 return false;
1122 }
1123 }
1124
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001125 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001126 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001127 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001128 return false;
1129 }
1130
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001131 return true;
1132 }
1133
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001134 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001135 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001136 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1137 std::vector<std::string> packages_to_callback;
1138
1139 JavaClassGeneratorOptions template_options;
1140 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1141 template_options.javadoc_annotations = options_.javadoc_annotations;
1142
1143 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1144 template_options.use_final = false;
1145 }
1146
1147 if (context_->GetPackageType() == PackageType::kSharedLib) {
1148 template_options.use_final = false;
1149 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1150 }
1151
1152 const StringPiece actual_package = context_->GetCompilationPackage();
1153 StringPiece output_package = context_->GetCompilationPackage();
1154 if (options_.custom_java_package) {
1155 // Override the output java package to the custom one.
1156 output_package = options_.custom_java_package.value();
1157 }
1158
1159 // Generate the private symbols if required.
1160 if (options_.private_symbols) {
1161 packages_to_callback.push_back(options_.private_symbols.value());
1162
1163 // If we defined a private symbols package, we only emit Public symbols
1164 // to the original package, and private and public symbols to the private package.
1165 JavaClassGeneratorOptions options = template_options;
1166 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1167 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1168 options)) {
1169 return false;
1170 }
1171 }
1172
1173 // Generate copies of the original package R class but with different package names.
1174 // This is to support non-namespaced builds.
1175 for (const std::string& extra_package : options_.extra_java_packages) {
1176 packages_to_callback.push_back(extra_package);
1177
1178 JavaClassGeneratorOptions options = template_options;
1179 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1180 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1181 return false;
1182 }
1183 }
1184
1185 // Generate R classes for each package that was merged (static library).
1186 // Use the actual package's resources only.
1187 for (const std::string& package : table_merger_->merged_packages()) {
1188 packages_to_callback.push_back(package);
1189
1190 JavaClassGeneratorOptions options = template_options;
1191 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1192 if (!WriteJavaFile(&final_table_, package, package, options)) {
1193 return false;
1194 }
1195 }
1196
1197 // Generate the main public R class.
1198 JavaClassGeneratorOptions options = template_options;
1199
1200 // Only generate public symbols if we have a private package.
1201 if (options_.private_symbols) {
1202 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1203 }
1204
1205 if (options.rewrite_callback_options) {
1206 options.rewrite_callback_options.value().packages_to_callback =
1207 std::move(packages_to_callback);
1208 }
1209
1210 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1211 options_.generate_text_symbols_path)) {
1212 return false;
1213 }
1214
1215 return true;
1216 }
1217
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001218 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001219 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001220 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221 return true;
1222 }
1223
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001224 std::unique_ptr<ClassDefinition> manifest_class =
1225 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001226
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 // Something bad happened, but we already logged it, so exit.
1229 return false;
1230 }
1231
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001232 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001233 // Empty Manifest class, no need to generate it.
1234 return true;
1235 }
1236
1237 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001238 for (const std::string& annotation : options_.javadoc_annotations) {
1239 std::string proper_annotation = "@";
1240 proper_annotation += annotation;
1241 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001242 }
1243
Adam Lesinski0d81f702017-06-27 15:51:09 -07001244 const std::string package_utf8 =
1245 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001246
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001247 std::string out_path = options_.generate_java_class_path.value();
1248 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001249
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001250 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001251 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1252 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253 return false;
1254 }
1255
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001256 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001257
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001258 io::FileOutputStream fout(out_path);
1259 if (fout.HadError()) {
1260 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1261 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001262 return false;
1263 }
1264
Makoto Onukide6e6f22020-06-22 10:17:02 -07001265 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1266 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001267 fout.Flush();
1268
1269 if (fout.HadError()) {
1270 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1271 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001272 return false;
1273 }
1274 return true;
1275 }
1276
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001277 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001278 TRACE_CALL();
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
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001291 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1292 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001293 fout.Flush();
1294
1295 if (fout.HadError()) {
1296 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1297 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001298 return false;
1299 }
1300 return true;
1301 }
1302
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001303 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001304 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001305 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001306 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001307 }
1308
Adam Lesinski8780eb62017-10-31 17:44:39 -07001309 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1310 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001311 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001312 return false;
1313 }
1314
Adam Lesinski8780eb62017-10-31 17:44:39 -07001315 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001316 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001317 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001318 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001319 return false;
1320 }
1321
1322 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001323 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001324 // Merge all resources as if they were in the compilation package. This is the old behavior
1325 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001326
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001327 // Add the package to the set of --extra-packages so we emit an R.java for each library
1328 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001329 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001330 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001331 }
1332
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001333 // Clear the package name, so as to make the resources look like they are coming from the
1334 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001335 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001336 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001337
1338 } else {
1339 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001340 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001341 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001342 }
1343
1344 if (!result) {
1345 return false;
1346 }
1347
1348 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001349 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001350 return true;
1351 }
1352
Adam Lesinski2427dce2017-11-30 15:10:28 -08001353 bool MergeExportedSymbols(const Source& source,
1354 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001355 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001356 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001357 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001358 ResourceName res_name = exported_symbol.name;
1359 if (res_name.package.empty()) {
1360 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001361 }
1362
Adam Lesinski00451162017-10-03 07:44:08 -07001363 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001364 if (mangled_name) {
1365 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001366 }
1367
1368 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001369 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001370 bool result =
1371 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1372 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001373 if (!result) {
1374 return false;
1375 }
1376 }
1377 return true;
1378 }
1379
Adam Lesinski2427dce2017-11-30 15:10:28 -08001380 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001381 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001382 if (context_->IsVerbose()) {
1383 context_->GetDiagnostics()->Note(DiagMessage()
1384 << "merging '" << compiled_file.name
1385 << "' from compiled file " << compiled_file.source);
1386 }
1387
1388 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1389 return false;
1390 }
1391 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1392 }
1393
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001394 // Takes a path to load as a ZIP file and merges the files within into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001395 // If override is true, conflicting resources are allowed to override each other, in order of last
1396 // seen.
1397 // An io::IFileCollection is created from the ZIP file and added to the set of
1398 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001399 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001400 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001401 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001402 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001403 }
1404
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001405 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001406 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001407 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001408 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001409 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001410 return false;
1411 }
1412
1413 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001414 for (auto iter = collection->Iterator(); iter->HasNext();) {
1415 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001416 error = true;
1417 }
1418 }
1419
1420 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001421 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001422 return !error;
1423 }
1424
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001425 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001426 // conflicting resources are allowed to override each other, in order of last seen.
1427 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1428 // as ZIP archive and the files within are merged individually.
1429 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001430 bool MergePath(const std::string& path, bool override) {
1431 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1432 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1433 return MergeArchive(path, override);
1434 } else if (util::EndsWith(path, ".apk")) {
1435 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001436 }
1437
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001438 io::IFile* file = file_collection_->InsertFile(path);
1439 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001440 }
1441
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001442 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001443 // If override is true, conflicting resources are allowed to override each other, in order of last
1444 // seen.
1445 // All other file types are ignored. This is because these files could be coming from a zip,
1446 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001447 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001448 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001449 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001450
Adam Lesinski00451162017-10-03 07:44:08 -07001451 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001452 // Since AAPT compiles these file types and appends .flat to them, seeing
1453 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001454 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1455 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1456 << " file passed as argument. Must be "
1457 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001458 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001459 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1460 if (context_->IsVerbose()) {
1461 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1462 return true;
1463 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001464 }
1465
Adam Lesinski00451162017-10-03 07:44:08 -07001466 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1467 if (input_stream == nullptr) {
1468 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1469 return false;
1470 }
1471
1472 if (input_stream->HadError()) {
1473 context_->GetDiagnostics()->Error(DiagMessage(src)
1474 << "failed to open file: " << input_stream->GetError());
1475 return false;
1476 }
1477
1478 ContainerReaderEntry* entry;
1479 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001480
1481 if (reader.HadError()) {
1482 context_->GetDiagnostics()->Error(DiagMessage(src)
1483 << "failed to read file: " << reader.GetError());
1484 return false;
1485 }
1486
Adam Lesinski00451162017-10-03 07:44:08 -07001487 while ((entry = reader.Next()) != nullptr) {
1488 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001489 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001490 pb::ResourceTable pb_table;
1491 if (!entry->GetResTable(&pb_table)) {
1492 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1493 << entry->GetError());
1494 return false;
1495 }
1496
1497 ResourceTable table;
1498 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001499 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001500 context_->GetDiagnostics()->Error(DiagMessage(src)
1501 << "failed to deserialize resource table: " << error);
1502 return false;
1503 }
1504
1505 if (!table_merger_->Merge(src, &table, override)) {
1506 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1507 return false;
1508 }
1509 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001510 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001511 pb::internal::CompiledFile pb_compiled_file;
1512 off64_t offset;
1513 size_t len;
1514 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1515 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1516 << entry->GetError());
1517 return false;
1518 }
1519
1520 ResourceFile resource_file;
1521 std::string error;
1522 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1523 context_->GetDiagnostics()->Error(DiagMessage(src)
1524 << "failed to read compiled header: " << error);
1525 return false;
1526 }
1527
1528 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1529 return false;
1530 }
1531 }
1532 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001533 return true;
1534 }
1535
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001536 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1537 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1538 for (const std::string& assets_dir : options_.assets_dirs) {
1539 Maybe<std::vector<std::string>> files =
1540 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1541 if (!files) {
1542 return false;
1543 }
1544
1545 for (const std::string& file : files.value()) {
1546 std::string full_key = "assets/" + file;
1547 std::string full_path = assets_dir;
1548 file::AppendPath(&full_path, file);
1549
1550 auto iter = merged_assets.find(full_key);
1551 if (iter == merged_assets.end()) {
1552 merged_assets.emplace(std::move(full_key),
1553 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1554 } else if (context_->IsVerbose()) {
1555 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1556 << "asset file overrides '" << full_path << "'");
1557 }
1558 }
1559 }
1560
1561 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001562 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001563 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1564 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001565 return false;
1566 }
1567 }
1568 return true;
1569 }
1570
Rhed Jao2c434422020-11-12 10:48:03 +08001571 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1572 Reference* reference) {
1573 if (!reference || !reference->name) {
1574 return nullptr;
1575 }
1576 auto name_ref = ResourceNameRef(reference->name.value());
1577 if (name_ref.package.empty()) {
1578 name_ref.package = context->GetCompilationPackage();
1579 }
1580 const auto search_result = table->FindResource(name_ref);
1581 if (!search_result) {
1582 return nullptr;
1583 }
1584 return search_result.value().entry;
1585 }
1586
Ryan Mitchelldba64562019-06-07 17:07:37 -07001587 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001588 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001589 if (!application) {
1590 return;
1591 }
1592
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001593 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1594 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001595 if (!icon || !round_icon) {
1596 return;
1597 }
1598
1599 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001600 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001601 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1602 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001603 return;
1604 }
1605
1606 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001607 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001608 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1609 ? config_value->config.sdkVersion : icon_max_sdk;
1610 }
1611 if (icon_max_sdk < SDK_O) {
1612 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1613 return;
1614 }
1615
1616 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001617 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001618 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1619 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001620 return;
1621 }
1622
1623 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001624 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001625 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1626 ? config_value->config.sdkVersion : round_icon_max_sdk;
1627 }
1628 if (round_icon_max_sdk >= SDK_O) {
1629 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1630 // not generate an alias to the icon drawable.
1631 return;
1632 }
1633
1634 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001635 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001636 if (config_value->config.sdkVersion < SDK_O) {
1637 continue;
1638 }
1639
1640 context_->GetDiagnostics()->Note(DiagMessage() << "generating "
1641 << round_icon_reference->name.value()
1642 << " with config \"" << config_value->config
1643 << "\" for round icon compatibility");
1644
1645 auto value = icon_reference->Clone(&table->string_pool);
Rhed Jao2c434422020-11-12 10:48:03 +08001646 auto round_config_value =
1647 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001648 round_config_value->value.reset(value);
1649 }
1650 }
1651
Rhed Jao2c434422020-11-12 10:48:03 +08001652 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1653 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1654 if (manifest_el == nullptr) {
1655 return true;
1656 }
1657 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1658 return true;
1659 }
1660 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1661 if (!attr) {
1662 return true;
1663 }
1664 const auto validate = [&](const std::string& shared_user_id) -> bool {
1665 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1666 return true;
1667 }
1668 DiagMessage error_msg(manifest_el->line_number);
1669 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1670 << shared_user_id << "'";
1671 if (options_.manifest_fixer_options.warn_validation) {
1672 // Treat the error only as a warning.
1673 context_->GetDiagnostics()->Warn(error_msg);
1674 return true;
1675 }
1676 context_->GetDiagnostics()->Error(error_msg);
1677 return false;
1678 };
1679 // If attr->compiled_value is not null, check if it is a ref
1680 if (attr->compiled_value) {
1681 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1682 if (ref == nullptr) {
1683 return true;
1684 }
1685 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1686 if (!shared_user_id_entry) {
1687 return true;
1688 }
1689 for (const auto& value : shared_user_id_entry->values) {
1690 const auto str_value = ValueCast<String>(value->value.get());
1691 if (str_value != nullptr && !validate(*str_value->value)) {
1692 return false;
1693 }
1694 }
1695 return true;
1696 }
1697
1698 // Fallback to checking the raw value
1699 return validate(attr->value);
1700 }
1701
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001702 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1703 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001704 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1705 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001706 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001707 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1708 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001709 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001710 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001711 if (!result) {
1712 return false;
1713 }
1714
Ryan Mitchelldba64562019-06-07 17:07:37 -07001715 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1716 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1717 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1718 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1719 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1720 // See (b/34829129)
1721 AliasAdaptiveIcon(manifest, table);
1722
Rhed Jao2c434422020-11-12 10:48:03 +08001723 // Verify the shared user id here to handle the case of reference value.
1724 if (!VerifySharedUserId(manifest, table)) {
1725 return false;
1726 }
1727
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001728 ResourceFileFlattenerOptions file_flattener_options;
1729 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001730 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1731 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001732 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001733 file_flattener_options.no_auto_version = options_.no_auto_version;
1734 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001735 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001736 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1737 file_flattener_options.update_proguard_spec =
1738 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001739 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001740 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001741
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001742 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001743 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001744 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001745 return false;
1746 }
1747
Adam Lesinski490595a2017-11-07 17:08:07 -08001748 // Hack to fix b/68820737.
1749 // We need to modify the ResourceTable's package name, but that should NOT affect
1750 // anything else being generated, which includes the Java classes.
1751 // If required, the package name is modifed before flattening, and then modified back
1752 // to its original name.
1753 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001754 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1755 // or higher] as invalid. In order to work around this limitation, we allow the use
1756 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1757 // definition of what a valid "split" package ID is to account for this.
1758 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1759 context_->GetPackageId() != kAppPackageId &&
1760 context_->GetPackageId() != kFrameworkPackageId)
1761 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1762 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001763 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1764 // The base APK is included, and this is a feature split. If the base package is
1765 // the same as this package, then we are building an old style Android Instant Apps feature
1766 // split and must apply this workaround to avoid requiring namespaces support.
1767 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1768 if (package_to_rewrite != nullptr) {
1769 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1770
1771 std::string new_package_name =
1772 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1773 app_info_.split_name.value_or_default("feature").c_str());
1774
1775 if (context_->IsVerbose()) {
1776 context_->GetDiagnostics()->Note(
1777 DiagMessage() << "rewriting resource package name for feature split to '"
1778 << new_package_name << "'");
1779 }
1780 package_to_rewrite->name = new_package_name;
1781 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001782 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001783
1784 bool success = FlattenTable(table, options_.output_format, writer);
1785
1786 if (package_to_rewrite != nullptr) {
1787 // Change the name back.
1788 package_to_rewrite->name = context_->GetCompilationPackage();
1789 if (package_to_rewrite->id) {
1790 table->included_packages_.erase(package_to_rewrite->id.value());
1791 }
1792 }
1793
1794 if (!success) {
1795 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1796 }
1797 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001798 }
1799
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001800 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001801 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001802 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001803 std::unique_ptr<xml::XmlResource> manifest_xml =
1804 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1805 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001806 return 1;
1807 }
1808
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001809 // First extract the Package name without modifying it (via --rename-manifest-package).
1810 if (Maybe<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001811 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001812 const AppInfo& app_info = maybe_app_info.value();
1813 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001814 }
1815
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001816 // Determine the package name under which to merge resources.
1817 if (options_.rename_resources_package) {
1818 if (!options_.custom_java_package) {
1819 // Generate the R.java under the original package name instead of the package name specified
1820 // through --rename-resources-package.
1821 options_.custom_java_package = context_->GetCompilationPackage();
1822 }
1823 context_->SetCompilationPackage(options_.rename_resources_package.value());
1824 }
1825
Adam Lesinskic6284372017-12-04 13:46:23 -08001826 // Now that the compilation package is set, load the dependencies. This will also extract
1827 // the Android framework's versionCode and versionName, if they exist.
1828 if (!LoadSymbolsFromIncludePaths()) {
1829 return 1;
1830 }
1831
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001832 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1833 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001834 return 1;
1835 }
1836
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001837 Maybe<AppInfo> maybe_app_info =
1838 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001839 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001840 return 1;
1841 }
1842
Adam Lesinski490595a2017-11-07 17:08:07 -08001843 app_info_ = maybe_app_info.value();
1844 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001846 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001847 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001848
1849 // Override the package ID when it is "android".
1850 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001851 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001852
1853 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001854 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001855 context_->GetDiagnostics()->Error(
1856 DiagMessage() << "package 'android' can only be built as a regular app");
1857 return 1;
1858 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001859 }
1860
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001861 TableMergerOptions table_merger_options;
1862 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07001863 table_merger_options.override_styles_instead_of_overlaying =
1864 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001865 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001866 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001867
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001868 if (context_->IsVerbose()) {
1869 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001870 << StringPrintf("linking package '%s' using package ID %02x",
1871 context_->GetCompilationPackage().data(),
1872 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001873 }
1874
Adam Lesinski2427dce2017-11-30 15:10:28 -08001875 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1876 // in res/**/*.
1877 {
1878 XmlIdCollector collector;
1879 if (!collector.Consume(context_, manifest_xml.get())) {
1880 return false;
1881 }
1882
1883 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1884 return false;
1885 }
1886 }
1887
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001888 for (const std::string& input : input_files) {
1889 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001890 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001891 return 1;
1892 }
1893 }
1894
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001895 for (const std::string& input : options_.overlay_files) {
1896 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001897 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001898 return 1;
1899 }
1900 }
1901
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001902 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001903 return 1;
1904 }
1905
Adam Lesinskib522f042017-04-21 16:57:59 -07001906 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001907 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001908 if (context_->GetPackageId() == kAndroidPackageId &&
1909 !mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001910 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001911 return 1;
1912 }
1913
1914 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001915 IdAssigner id_assigner(&options_.stable_id_map);
1916 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001917 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001918 return 1;
1919 }
1920
1921 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001922 if (options_.resource_id_map_path) {
1923 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001924 for (auto& type : package->types) {
1925 for (auto& entry : type->entries) {
1926 ResourceName name(package->name, type->type, entry->name);
1927 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001928 options_.stable_id_map[std::move(name)] =
1929 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001930 }
1931 }
1932 }
1933
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001934 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001935 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001936 return 1;
1937 }
1938 }
1939 } else {
1940 // Static libs are merged with other apps, and ID collisions are bad, so
1941 // verify that
1942 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001943 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001944 return 1;
1945 }
1946 }
1947
1948 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001949 context_->SetNameManglerPolicy(
1950 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001951
1952 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001953 context_->GetExternalSymbols()->PrependSource(
1954 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001955
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001956 // Workaround for pre-O runtime that would treat negative resource IDs
1957 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1958 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1959 // are just identifiers.
1960 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1961 if (context_->IsVerbose()) {
1962 context_->GetDiagnostics()->Note(DiagMessage()
1963 << "enabling pre-O feature split ID rewriting");
1964 }
1965 context_->GetExternalSymbols()->SetDelegate(
1966 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1967 }
1968
Adam Lesinski34a16872018-02-23 16:18:10 -08001969 // Before we process anything, remove the resources whose default values don't exist.
1970 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02001971 if (!options_.no_resource_removal) {
1972 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1973 context_->GetDiagnostics()->Error(DiagMessage()
1974 << "failed removing resources with no defaults");
1975 return 1;
1976 }
Adam Lesinski34a16872018-02-23 16:18:10 -08001977 }
1978
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001979 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001980 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001981 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001982 return 1;
1983 }
1984
Adam Lesinskib522f042017-04-21 16:57:59 -07001985 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001986 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001987 context_->GetDiagnostics()->Warn(DiagMessage()
1988 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001989 }
1990 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001991 ProductFilter product_filter(options_.products);
1992 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001993 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001994 return 1;
1995 }
1996 }
1997
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001998 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001999 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002000 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002001 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002002 return 1;
2003 }
2004 }
2005
Adam Lesinskib522f042017-04-21 16:57:59 -07002006 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002007 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002008 context_->GetDiagnostics()->Note(DiagMessage()
2009 << "collapsing resource versions for minimum SDK "
2010 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011 }
2012
2013 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002014 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002015 return 1;
2016 }
2017 }
2018
Winson3c918b82019-01-25 14:25:37 -08002019 if (!options_.exclude_configs_.empty()) {
2020 std::vector<ConfigDescription> excluded_configs;
2021
2022 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002023 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002024 ConfigDescription config_description;
2025
2026 if (!ConfigDescription::Parse(config_string, &config_description)) {
2027 context_->GetDiagnostics()->Error(DiagMessage()
2028 << "failed to parse --excluded-configs "
2029 << config_string);
2030 return 1;
2031 }
2032
2033 excluded_configs.push_back(config_description);
2034 }
2035
2036 ResourceExcluder excluder(excluded_configs);
2037 if (!excluder.Consume(context_, &final_table_)) {
2038 context_->GetDiagnostics()->Error(DiagMessage() << "failed excluding configurations");
2039 return 1;
2040 }
2041 }
2042
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002043 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002044 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002045 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002046 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002047 return 1;
2048 }
2049 }
2050
Adam Koskidc21dea2017-07-21 10:55:27 -07002051 proguard::KeepSet proguard_keep_set =
2052 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002053 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002054
Adam Lesinskib522f042017-04-21 16:57:59 -07002055 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002056 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002057 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002058 context_->GetDiagnostics()->Warn(DiagMessage()
2059 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002060 }
2061 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002062 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2063 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002064 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002065 options_.split_constraints =
2066 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002067
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002068 if (origConstraintSize != options_.split_constraints.size()) {
2069 context_->GetDiagnostics()->Warn(DiagMessage()
2070 << "requested to split resources prior to min sdk of "
2071 << context_->GetMinSdkVersion());
2072 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002073 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002074 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002075 return 1;
2076 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002077 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002078
2079 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002080 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002081 auto split_constraints_iter = options_.split_constraints.begin();
2082 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002083 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002084 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
2085 << "generating split with configurations '"
2086 << util::Joiner(split_constraints_iter->configs, ", ")
2087 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002088 }
2089
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002090 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002091 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002092 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002093 return 1;
2094 }
2095
2096 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002097 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002098 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002099
2100 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002101 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002102 context_->GetDiagnostics()->Error(DiagMessage()
2103 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002104 return 1;
2105 }
2106
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002107 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2108 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002109 return 1;
2110 }
2111
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002112 ++path_iter;
2113 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002114 }
2115 }
2116
2117 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002118 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002119 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002120 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002121 return 1;
2122 }
2123
2124 bool error = false;
2125 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002126 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002127 // (aka, which package the AndroidManifest.xml is coming from).
2128 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002129 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002130
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002131 XmlReferenceLinker manifest_linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01002132 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002133 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002134 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002135 error = true;
2136 }
2137
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002138 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002139 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002140 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002141 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002142 }
2143
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002144 if (options_.generate_java_class_path) {
2145 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002146 error = true;
2147 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002148 }
2149
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002150 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002151 // PackageParser will fail if URIs are removed from
2152 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002153 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2154 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002155 error = true;
2156 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002157 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002158 } else {
2159 error = true;
2160 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002161 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002162
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002163 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002164 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002165 return 1;
2166 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002167
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002168 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2169 return 1;
2170 }
2171
2172 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002173 return 1;
2174 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002175
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002176 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002177 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002178 return 1;
2179 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002180 }
2181
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002182 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002183 return 1;
2184 }
2185
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002186 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2187 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002188 return 1;
2189 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002190 return 0;
2191 }
2192
2193 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002194 LinkOptions options_;
2195 LinkContext* context_;
2196 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002197
Adam Lesinski490595a2017-11-07 17:08:07 -08002198 AppInfo app_info_;
2199
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002200 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002201
2202 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002203 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002204
Adam Lesinski8780eb62017-10-31 17:44:39 -07002205 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002206 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002207 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002208
Adam Lesinski8780eb62017-10-31 17:44:39 -07002209 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2210 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2211
2212 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2213 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002214
2215 // The set of shared libraries being used, mapping their assigned package ID to package name.
2216 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002217
2218 // The package name of the base application, if it is included.
2219 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002220};
2221
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002222int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002223 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002224 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002225
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002226 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002227 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002228 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002229 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002230 const std::string path = arg.substr(1, arg.size() - 1);
2231 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002232 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2233 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002234 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002235 }
2236 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002237 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002238 }
2239 }
2240
2241 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002242 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002243 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002244 const std::string path = arg.substr(1, arg.size() - 1);
2245 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002246 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002247 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002248 return 1;
2249 }
2250 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002251 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002252 }
2253 }
2254
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002255 if (verbose_) {
2256 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002257 }
2258
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002259 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002260 context.GetDiagnostics()->Error(
2261 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002262 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002263 return 1;
2264 }
2265
Ryan Mitchell5855de72021-02-24 14:39:13 -08002266 if (shared_lib_ && options_.private_symbols) {
2267 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2268 // reference the private attribute within the styleable array will cause a link error because
2269 // the private attribute will not be emitted in the public R.java.
2270 context.GetDiagnostics()->Error(DiagMessage()
2271 << "--shared-lib cannot currently be used in combination with"
2272 << " --private-symbols");
2273 return 1;
2274 }
2275
Izabela Orlowska84febea2019-06-03 18:34:12 +01002276 if (options_.merge_only && !static_lib_) {
2277 context.GetDiagnostics()->Error(
2278 DiagMessage() << "the --merge-only flag can be only used when building a static library");
2279 return 1;
2280 }
2281
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002282 // The default build type.
2283 context.SetPackageType(PackageType::kApp);
2284 context.SetPackageId(kAppPackageId);
2285
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002286 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002287 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002288 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002289 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002290 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002291 options_.output_format = OutputFormat::kProto;
2292 } else if (proto_format_) {
2293 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002294 }
2295
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002296 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002297 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002298 context.GetDiagnostics()->Error(
2299 DiagMessage() << "can't specify --package-id when not building a regular app");
2300 return 1;
2301 }
2302
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002303 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002304 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002305 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002306 << "' is not a valid integer");
2307 return 1;
2308 }
2309
2310 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002311 if (package_id_int > std::numeric_limits<uint8_t>::max()
2312 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002313 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002314 context.GetDiagnostics()->Error(
2315 DiagMessage() << StringPrintf(
2316 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2317 return 1;
2318 }
2319 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2320 }
2321
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002322 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002323 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002324 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002325 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002326 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002327 }
2328 }
2329
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002330 if (product_list_) {
2331 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002332 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002333 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002334 }
2335 }
2336 }
2337
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002338 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002339 if (!configs_.empty()) {
2340 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002341 if (filter == nullptr) {
2342 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002343 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002344 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002345 }
2346
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002347 if (preferred_density_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002348 Maybe<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002349 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002350 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002351 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002352 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002353 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002354 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002355
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002356 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002357 for (const std::string& split_arg : split_args_) {
2358 options_.split_paths.push_back({});
2359 options_.split_constraints.push_back({});
2360 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2361 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002362 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002363 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002364 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002365
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002366 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2367 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2368 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002369 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002370 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002371 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002372
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002373 if (no_compress_regex) {
2374 std::string regex = no_compress_regex.value();
2375 if (util::StartsWith(regex, "@")) {
2376 const std::string path = regex.substr(1, regex.size() -1);
2377 std::string error;
2378 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
2379 context.GetDiagnostics()->Error(DiagMessage(path) << error);
2380 return 1;
2381 }
2382 } else {
2383 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2384 }
2385 }
2386
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002387 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002388 options_.extensions_to_not_compress.insert({
2389 // Image extensions
2390 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2391 // Audio extensions
2392 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2393 ".xmf", ".amr", ".awb",
2394 // Audio/video extensions
2395 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2396 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002397
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002398 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002399 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002400 options_.no_auto_version = true;
2401 options_.no_version_vectors = true;
2402 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002403 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002404
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002405 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002406 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002407}
2408
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002409} // namespace aapt