blob: 790f2b34c58b27ad04efb6c54632c9dae951e19e [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"
Ryan Mitchell9634efb2021-03-19 14:53:17 -070028#include "android-base/expected.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070029#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080030#include "android-base/stringprintf.h"
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020031#include "androidfw/Locale.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080032#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070033
Adam Lesinski1ab598f2015-08-14 14:26:04 -070034#include "AppInfo.h"
35#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070036#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070037#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080038#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070039#include "ResourceValues.h"
40#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070041#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070042#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080043#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080044#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070045#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070046#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070047#include "format/binary/TableFlattener.h"
48#include "format/binary/XmlFlattener.h"
49#include "format/proto/ProtoDeserialize.h"
50#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070051#include "io/BigBufferStream.h"
52#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080053#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070054#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080055#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070056#include "java/JavaClassGenerator.h"
57#include "java/ManifestClassGenerator.h"
58#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070060#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080061#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080062#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080063#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070065#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080066#include "optimize/ResourceDeduper.h"
67#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070068#include "process/IResourceTableConsumer.h"
69#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080070#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080071#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080073#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070074
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070075using ::aapt::io::FileInputStream;
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020076using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070077using ::android::StringPiece;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070078using ::android::base::expected;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070079using ::android::base::StringPrintf;
Ryan Mitchell9634efb2021-03-19 14:53:17 -070080using ::android::base::unexpected;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070081
Adam Lesinski1ab598f2015-08-14 14:26:04 -070082namespace aapt {
83
Ryan Mitchell9634efb2021-03-19 14:53:17 -070084namespace {
85
86expected<ResourceTablePackage*, const char*> GetStaticLibraryPackage(ResourceTable* table) {
87 // Resource tables built by aapt2 always contain one package. This is a post condition of
88 // VerifyNoExternalPackages.
89 if (table->packages.size() != 1u) {
90 return unexpected("static library contains more than one package");
91 }
92 return table->packages.back().get();
93}
94
95} // namespace
96
Ryan Mitchell22dc5312020-06-01 12:17:07 -070097constexpr uint8_t kAndroidPackageId = 0x01;
98
Adam Lesinski64587af2016-02-18 18:33:06 -080099class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700100 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800101 explicit LinkContext(IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +0100102 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700103 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700104
Adam Lesinskib522f042017-04-21 16:57:59 -0700105 PackageType GetPackageType() override {
106 return package_type_;
107 }
108
109 void SetPackageType(PackageType type) {
110 package_type_ = type;
111 }
112
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700113 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100114 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700115 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700116
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700117 NameMangler* GetNameMangler() override {
118 return &name_mangler_;
119 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700120
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700121 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
122 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700123 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800124
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700125 const std::string& GetCompilationPackage() override {
126 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700127 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700128
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700129 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800130 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700131 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800132
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700133 uint8_t GetPackageId() override {
134 return package_id_;
135 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700136
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700137 void SetPackageId(uint8_t id) {
138 package_id_ = id;
139 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800140
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700141 SymbolTable* GetExternalSymbols() override {
142 return &symbols_;
143 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800144
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700145 bool IsVerbose() override {
146 return verbose_;
147 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800148
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700149 void SetVerbose(bool val) {
150 verbose_ = val;
151 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800152
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700153 int GetMinSdkVersion() override {
154 return min_sdk_version_;
155 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700156
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700157 void SetMinSdkVersion(int minSdk) {
158 min_sdk_version_ = minSdk;
159 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700160
Udam Sainib228df32019-06-18 16:50:34 -0700161 const std::set<std::string>& GetSplitNameDependencies() override {
162 return split_name_dependencies_;
163 }
164
165 void SetSplitNameDependencies(const std::set<std::string>& split_name_dependencies) {
166 split_name_dependencies_ = split_name_dependencies;
167 }
168
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700169 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700170 DISALLOW_COPY_AND_ASSIGN(LinkContext);
171
Adam Lesinskib522f042017-04-21 16:57:59 -0700172 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100173 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700174 NameMangler name_mangler_;
175 std::string compilation_package_;
176 uint8_t package_id_ = 0x0;
177 SymbolTable symbols_;
178 bool verbose_ = false;
179 int min_sdk_version_ = 0;
Udam Sainib228df32019-06-18 16:50:34 -0700180 std::set<std::string> split_name_dependencies_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700181};
182
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700183// A custom delegate that generates compatible pre-O IDs for use with feature splits.
184// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
185// is interpreted as a negative number. Some verification was wrongly assuming negative values
186// were invalid.
187//
188// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
189// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
190// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800191//
192// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700193class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
194 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800195 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700196 }
197
198 virtual ~FeatureSplitSymbolTableDelegate() = default;
199
200 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
201 const ResourceName& name,
202 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
203 std::unique_ptr<SymbolTable::Symbol> symbol =
204 DefaultSymbolTableDelegate::FindByName(name, sources);
205 if (symbol == nullptr) {
206 return {};
207 }
208
209 // Check to see if this is an 'id' with the target package.
Iurii Makhnocff10ce2022-02-15 19:33:50 +0000210 if (name.type.type == ResourceType::kId && symbol->id) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700211 ResourceId* id = &symbol->id.value();
212 if (id->package_id() > kAppPackageId) {
213 // Rewrite the resource ID to be compatible pre-O.
214 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
215
216 // Check that this doesn't overlap another resource.
217 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
218 // The ID overlaps, so log a message (since this is a weird failure) and fail.
219 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
220 << " for pre-O feature split support");
221 return {};
222 }
223
224 if (context_->IsVerbose()) {
225 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
226 << ") -> (" << rewritten_id << ")");
227 }
228
229 *id = rewritten_id;
230 }
231 }
232 return symbol;
233 }
234
235 private:
236 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
237
238 IAaptContext* context_;
239};
240
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700241static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
242 const StringPiece& path, bool keep_raw_values, bool utf16,
243 OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800244 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700245 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700246 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
247 << (keep_raw_values ? "true" : "false")
248 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700249 }
250
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700251 switch (format) {
252 case OutputFormat::kApk: {
253 BigBuffer buffer(1024);
254 XmlFlattenerOptions options = {};
255 options.keep_raw_values = keep_raw_values;
256 options.use_utf16 = utf16;
257 XmlFlattener flattener(&buffer, options);
258 if (!flattener.Consume(context, &xml_res)) {
259 return false;
260 }
261
262 io::BigBufferInputStream input_stream(&buffer);
263 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
264 ArchiveEntry::kCompress, writer);
265 } break;
266
267 case OutputFormat::kProto: {
268 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800269 // Strip whitespace text nodes from tha AndroidManifest.xml
270 SerializeXmlOptions options;
271 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700272 SerializeXmlResourceToPb(xml_res, &pb_node);
273 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
274 writer);
275 } break;
276 }
277 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800278}
279
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700280// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700281static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800282 TRACE_CALL();
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700283 FileInputStream fin(path);
284 if (fin.HadError()) {
285 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700286 return {};
287 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700288 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800289}
290
Adam Lesinski355f2852016-02-13 20:26:45 -0800291struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700292 bool no_auto_version = false;
293 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900294 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700295 bool no_xml_namespaces = false;
296 bool keep_raw_values = false;
297 bool do_not_compress_anything = false;
298 bool update_proguard_spec = false;
Izabela Orlowska84febea2019-06-03 18:34:12 +0100299 bool do_not_fail_on_missing_resources = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700300 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700301 std::unordered_set<std::string> extensions_to_not_compress;
Ryan Mitchell4382e442021-07-14 12:53:01 -0700302 std::optional<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800303};
304
Adam Lesinskic744ae82017-05-17 19:28:38 -0700305// A sampling of public framework resource IDs.
306struct R {
307 struct attr {
308 enum : uint32_t {
309 paddingLeft = 0x010100d6u,
310 paddingRight = 0x010100d8u,
311 paddingHorizontal = 0x0101053du,
312
313 paddingTop = 0x010100d7u,
314 paddingBottom = 0x010100d9u,
315 paddingVertical = 0x0101053eu,
316
317 layout_marginLeft = 0x010100f7u,
318 layout_marginRight = 0x010100f9u,
319 layout_marginHorizontal = 0x0101053bu,
320
321 layout_marginTop = 0x010100f8u,
322 layout_marginBottom = 0x010100fau,
323 layout_marginVertical = 0x0101053cu,
324 };
325 };
326};
327
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700328template <typename T>
329uint32_t GetCompressionFlags(const StringPiece& str, T options) {
330 if (options.do_not_compress_anything) {
331 return 0;
332 }
333
334 if (options.regex_to_not_compress
335 && std::regex_search(str.to_string(), options.regex_to_not_compress.value())) {
336 return 0;
337 }
338
339 for (const std::string& extension : options.extensions_to_not_compress) {
340 if (util::EndsWith(str, extension)) {
341 return 0;
342 }
343 }
344 return ArchiveEntry::kCompress;
345}
346
Adam Lesinski355f2852016-02-13 20:26:45 -0800347class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700348 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700349 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700350 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800351
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700352 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800353
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700354 private:
355 struct FileOperation {
356 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700357
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700358 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700359 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700360
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700361 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700362 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700363
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700365 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700366
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700368 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700369 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800370
Adam Lesinskic744ae82017-05-17 19:28:38 -0700371 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
372 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800373
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700374 ResourceFileFlattenerOptions options_;
375 IAaptContext* context_;
376 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700377 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800378};
379
Adam Lesinskic744ae82017-05-17 19:28:38 -0700380ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
381 IAaptContext* context, proguard::KeepSet* keep_set)
382 : options_(options), context_(context), keep_set_(keep_set) {
383 SymbolTable* symm = context_->GetExternalSymbols();
384
385 // Build up the rules for degrading newer attributes to older ones.
386 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
387 // generated from the attribute definitions themselves (b/62028956).
388 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
389 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800390 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
391 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700392 };
393 rules_[R::attr::paddingHorizontal] =
394 util::make_unique<DegradeToManyRule>(std::move(replacements));
395 }
396
397 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
398 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800399 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
400 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700401 };
402 rules_[R::attr::paddingVertical] =
403 util::make_unique<DegradeToManyRule>(std::move(replacements));
404 }
405
406 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
407 std::vector<ReplacementAttr> replacements{
408 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800409 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700410 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800411 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700412 };
413 rules_[R::attr::layout_marginHorizontal] =
414 util::make_unique<DegradeToManyRule>(std::move(replacements));
415 }
416
417 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
418 std::vector<ReplacementAttr> replacements{
419 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800420 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700421 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800422 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700423 };
424 rules_[R::attr::layout_marginVertical] =
425 util::make_unique<DegradeToManyRule>(std::move(replacements));
426 }
427}
428
Adam Lesinskibb94f322017-07-12 07:41:55 -0700429static bool IsTransitionElement(const std::string& name) {
430 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
431 name == "changeImageTransform" || name == "changeTransform" ||
432 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
433 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
434 name == "transitionManager";
435}
436
437static bool IsVectorElement(const std::string& name) {
438 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800439 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
440 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700441}
442
Adam Lesinskic744ae82017-05-17 19:28:38 -0700443template <typename T>
444std::vector<T> make_singleton_vec(T&& val) {
445 std::vector<T> vec;
446 vec.emplace_back(std::forward<T>(val));
447 return vec;
448}
449
450std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
451 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800452 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700453 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700454 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700455
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700456 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700457 context_->GetDiagnostics()->Note(DiagMessage()
458 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700459 }
460
Adam Lesinski00451162017-10-03 07:44:08 -0700461 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
462 // that existing projects have out-of-date references which pass compilation.
463 xml::StripAndroidStudioAttributes(doc->root.get());
464
Ryan Mitchell326e35ff2021-04-12 07:50:42 -0700465 XmlReferenceLinker xml_linker(table);
Izabela Orlowska84febea2019-06-03 18:34:12 +0100466 if (!options_.do_not_fail_on_missing_resources && !xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700467 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700468 }
469
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700470 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700471 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700472 }
473
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700474 if (options_.no_xml_namespaces) {
475 XmlNamespaceRemover namespace_remover;
476 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700477 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800478 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700479 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800480
Adam Lesinskibb94f322017-07-12 07:41:55 -0700481 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700482 return make_singleton_vec(std::move(file_op->xml_to_flatten));
483 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700484
Adam Lesinskibb94f322017-07-12 07:41:55 -0700485 if (options_.no_version_vectors || options_.no_version_transitions) {
486 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700487 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700488 if (el && el->namespace_uri.empty()) {
489 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
490 (options_.no_version_transitions && IsTransitionElement(el->name))) {
491 return make_singleton_vec(std::move(file_op->xml_to_flatten));
492 }
493 }
494 }
495
Adam Lesinskic744ae82017-05-17 19:28:38 -0700496 const ConfigDescription& config = file_op->config;
497 ResourceEntry* entry = file_op->entry;
498
499 XmlCompatVersioner xml_compat_versioner(&rules_);
500 const util::Range<ApiVersion> api_range{config.sdkVersion,
501 FindNextApiVersionForConfig(entry, config)};
502 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800503}
504
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800505ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
506 switch (format) {
507 case OutputFormat::kApk:
508 return ResourceFile::Type::kBinaryXml;
509 case OutputFormat::kProto:
510 return ResourceFile::Type::kProtoXml;
511 }
512 LOG_ALWAYS_FATAL("unreachable");
513 return ResourceFile::Type::kUnknown;
514}
515
Ryan Mitchell70f79722018-08-13 07:37:24 -0700516static auto kDrawableVersions = std::map<std::string, ApiVersion>{
517 { "adaptive-icon" , SDK_O },
518};
519
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700520bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800521 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700522 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700523 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800524
Adam Koskidc21dea2017-07-21 10:55:27 -0700525 proguard::CollectResourceReferences(context_, table, keep_set_);
526
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700527 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700528 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
529
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700530 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700531 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700532 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700533 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800534
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700535 // Populate the queue with all files in the ResourceTable.
536 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700537 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700538 // WARNING! Do not insert or remove any resources while executing in this scope. It will
539 // corrupt the iteration order.
540
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700541 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700542 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700543 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700545
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700546 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700547 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700548 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700550 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 }
552
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700553 FileOperation file_op;
554 file_op.entry = entry.get();
555 file_op.dst_path = *file_ref->path;
556 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700557 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700558
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700559 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700560 (file_ref->type == ResourceFile::Type::kBinaryXml ||
561 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700562 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700563 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700564 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565 << "failed to open file");
566 return false;
567 }
568
Adam Lesinski00451162017-10-03 07:44:08 -0700569 if (file_ref->type == ResourceFile::Type::kProtoXml) {
570 pb::XmlNode pb_xml_node;
571 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
572 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700573 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700574 return false;
575 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700576
Adam Lesinski00451162017-10-03 07:44:08 -0700577 std::string error;
578 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
579 if (file_op.xml_to_flatten == nullptr) {
580 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700581 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700582 return false;
583 }
584 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700585 std::string error_str;
586 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700587 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700588 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
589 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700590 return false;
591 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700592 }
593
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800594 // Update the type that this file will be written as.
595 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
596
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700597 file_op.xml_to_flatten->file.config = config_value->config;
598 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700599 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700600 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700601
602 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
603 // else we end up copying the string in the std::make_pair() method,
604 // then creating a StringPiece from the copy, which would cause us
605 // to end up referencing garbage in the map.
606 const StringPiece entry_name(entry->name);
607 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
608 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700609 }
610 }
611
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700612 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700613 for (auto& map_entry : config_sorted_files) {
614 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700615 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700617 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700618 // Check minimum sdk versions supported for drawables
619 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
620 if (drawable_entry != kDrawableVersions.end()) {
621 if (drawable_entry->second > context_->GetMinSdkVersion()
622 && drawable_entry->second > config.sdkVersion) {
623 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
624 << "<" << drawable_entry->first << "> elements "
625 << "require a sdk version of at least "
626 << (int16_t) drawable_entry->second);
627 error = true;
628 continue;
629 }
630 }
631
Adam Lesinskic744ae82017-05-17 19:28:38 -0700632 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
633 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700634 if (versioned_docs.empty()) {
635 error = true;
636 continue;
637 }
638
Adam Lesinskic744ae82017-05-17 19:28:38 -0700639 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
640 std::string dst_path = file_op.dst_path;
641 if (doc->file.config != file_op.config) {
642 // Only add the new versioned configurations.
643 if (context_->IsVerbose()) {
644 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
645 << "auto-versioning resource from config '"
646 << config << "' -> '" << doc->file.config << "'");
647 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800649 const ResourceFile& file = doc->file;
650 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
651
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700652 auto file_ref =
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800653 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
654 file_ref->SetSource(doc->file.source);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700655
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800656 // Update the output format of this XML file.
657 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700658 bool result = table->AddResource(NewResourceBuilder(file.name)
659 .SetValue(std::move(file_ref), file.config)
660 .SetAllowMangled(true)
661 .Build(),
662 context_->GetDiagnostics());
663 if (!result) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700664 return false;
665 }
666 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700667
668 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
669 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700670 }
671 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700672 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
Ryan Mitchell81dfca02019-06-07 10:20:27 -0700673 GetCompressionFlags(file_op.dst_path, options_),
674 archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700675 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700677 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700678 }
679 return !error;
680}
681
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700682static bool WriteStableIdMapToPath(IDiagnostics* diag,
683 const std::unordered_map<ResourceName, ResourceId>& id_map,
684 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800685 io::FileOutputStream fout(id_map_path);
686 if (fout.HadError()) {
687 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700688 return false;
689 }
690
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800691 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700692 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 const ResourceName& name = entry.first;
694 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800695 printer.Print(name.to_string());
696 printer.Print(" = ");
697 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800699 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800701 if (fout.HadError()) {
702 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 return false;
704 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705 return true;
706}
707
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700708static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
709 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700710 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700711 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700712 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713 return false;
714 }
715
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700716 out_id_map->clear();
717 size_t line_no = 0;
718 for (StringPiece line : util::Tokenize(content, '\n')) {
719 line_no++;
720 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700721 if (line.empty()) {
722 continue;
723 }
724
725 auto iter = std::find(line.begin(), line.end(), '=');
726 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700727 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700728 return false;
729 }
730
731 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700732 StringPiece res_name_str =
733 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
734 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700735 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
736 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700737 return false;
738 }
739
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700740 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
741 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700742 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743
Ryan Mitchell4382e442021-07-14 12:53:01 -0700744 std::optional<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700745 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700746 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
747 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700748 return false;
749 }
750
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700751 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700752 }
753 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700754}
755
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700756class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700757 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700758 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700759 : options_(options),
760 context_(context),
761 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700762 file_collection_(util::make_unique<io::FileCollection>()) {
763 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700764
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800765 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800766 using namespace android;
767
Ryan Mitchelldb21f09a2020-11-16 23:08:18 +0000768 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
769 // we're looking for the first attribute resource in the system package.
770 android::ApkAssetsCookie cookie;
771 if (auto value = assets->GetResource(0x01010000, true /** may_be_bag */); value.has_value()) {
772 cookie = value->cookie;
773 } else {
Adam Lesinskic6284372017-12-04 13:46:23 -0800774 // No Framework assets loaded. Not a failure.
775 return;
776 }
777
778 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800779 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800780 if (manifest == nullptr) {
781 // No errors.
782 return;
783 }
784
785 std::string error;
786 std::unique_ptr<xml::XmlResource> manifest_xml =
787 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
788 if (manifest_xml == nullptr) {
789 // No errors.
790 return;
791 }
792
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700793 if (!options_.manifest_fixer_options.compile_sdk_version) {
794 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
795 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700796 auto& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700797 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
798 switch (prim->value.dataType) {
799 case Res_value::TYPE_INT_DEC:
800 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
801 break;
802 case Res_value::TYPE_INT_HEX:
803 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
804 break;
805 default:
806 break;
807 }
808 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
809 compile_sdk_version = *str->value;
810 } else {
811 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800812 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800813 }
814 }
815
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700816 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
817 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
818 if (attr != nullptr) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700819 std::optional<std::string>& compile_sdk_version_codename =
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700820 options_.manifest_fixer_options.compile_sdk_version_codename;
821 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
822 compile_sdk_version_codename = *str->value;
823 } else {
824 compile_sdk_version_codename = attr->value;
825 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800826 }
827 }
828 }
829
Adam Lesinski8780eb62017-10-31 17:44:39 -0700830 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800831 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700832 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800833 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700834 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700835 for (const std::string& path : options_.include_paths) {
836 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700837 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700838 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700839
Adam Lesinski8780eb62017-10-31 17:44:39 -0700840 std::string error;
841 auto zip_collection = io::ZipFileCollection::Create(path, &error);
842 if (zip_collection == nullptr) {
843 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
844 return false;
845 }
846
847 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
848 // Load this as a static library include.
849 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
850 Source(path), std::move(zip_collection), context_->GetDiagnostics());
851 if (static_apk == nullptr) {
852 return false;
853 }
854
Adam Lesinskib522f042017-04-21 16:57:59 -0700855 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800856 // Can't include static libraries when not building a static library (they have no IDs
857 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700858 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800859 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700860 return false;
861 }
862
Adam Lesinski8780eb62017-10-31 17:44:39 -0700863 ResourceTable* table = static_apk->GetResourceTable();
864
865 // If we are using --no-static-lib-packages, we need to rename the package of this table to
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700866 // our compilation package so the symbol package name does not get mangled into the entry
867 // name.
868 if (options_.no_static_lib_packages && !table->packages.empty()) {
869 auto lib_package_result = GetStaticLibraryPackage(table);
870 if (!lib_package_result.has_value()) {
871 context_->GetDiagnostics()->Error(DiagMessage(path) << lib_package_result.error());
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800872 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700873 }
Ryan Mitchell9634efb2021-03-19 14:53:17 -0700874 lib_package_result.value()->name = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700875 }
876
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700877 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700878 util::make_unique<ResourceTableSymbolSource>(table));
879 static_library_includes_.push_back(std::move(static_apk));
880 } else {
881 if (!asset_source->AddAssetPath(path)) {
882 context_->GetDiagnostics()->Error(DiagMessage()
883 << "failed to load include path " << path);
884 return false;
885 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700886 }
887 }
888
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800889 // Capture the shared libraries so that the final resource table can be properly flattened
890 // with support for shared libraries.
891 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700892 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800893 // Capture the included base feature package.
894 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800895 } else if (entry.first == kFrameworkPackageId) {
896 // Try to embed which version of the framework we're compiling against.
897 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
898 // when linking our synthesized 'android:compileSdkVersion' attribute.
899 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
900 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
901 if (symbol != nullptr && symbol->is_public) {
902 // The symbol is present and public, extract the android:versionName and
903 // android:versionCode from the framework AndroidManifest.xml.
904 ExtractCompileSdkVersions(asset_source->GetAssetManager());
905 }
Ryan Mitchellee4a5642019-10-16 08:32:55 -0700906 } else if (asset_source->IsPackageDynamic(entry.first, entry.second)) {
Todd Kennedy32512992018-04-25 16:45:59 -0700907 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800908 }
909 }
910
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700911 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700912 return true;
913 }
914
Ryan Mitchell4382e442021-07-14 12:53:01 -0700915 std::optional<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800916 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700917 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800918 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
919 if (manifest_el == nullptr) {
920 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700921 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800922
923 AppInfo app_info;
924
925 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
926 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
927 return {};
928 }
929
930 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
931 if (!package_attr) {
932 diag->Error(DiagMessage(xml_res->file.source)
933 << "<manifest> must have a 'package' attribute");
934 return {};
935 }
936 app_info.package = package_attr->value;
937
938 if (xml::Attribute* version_code_attr =
939 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700940 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800941 if (!maybe_code) {
942 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
943 << "invalid android:versionCode '" << version_code_attr->value << "'");
944 return {};
945 }
946 app_info.version_code = maybe_code.value();
947 }
948
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700949 if (xml::Attribute* version_code_major_attr =
950 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700951 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700952 if (!maybe_code) {
953 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
954 << "invalid android:versionCodeMajor '"
955 << version_code_major_attr->value << "'");
956 return {};
957 }
958 app_info.version_code_major = maybe_code.value();
959 }
960
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800961 if (xml::Attribute* revision_code_attr =
962 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
Ryan Mitchell4382e442021-07-14 12:53:01 -0700963 std::optional<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800964 if (!maybe_code) {
965 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
966 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
967 return {};
968 }
969 app_info.revision_code = maybe_code.value();
970 }
971
972 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
973 if (!split_name_attr->value.empty()) {
974 app_info.split_name = split_name_attr->value;
975 }
976 }
977
978 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
979 if (xml::Attribute* min_sdk =
980 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700981 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800982 }
983 }
Udam Sainib228df32019-06-18 16:50:34 -0700984
985 for (const xml::Element* child_el : manifest_el->GetChildElements()) {
986 if (child_el->namespace_uri.empty() && child_el->name == "uses-split") {
987 if (const xml::Attribute* split_name =
988 child_el->FindAttribute(xml::kSchemaAndroid, "name")) {
989 if (!split_name->value.empty()) {
990 app_info.split_name_dependencies.insert(split_name->value);
991 }
992 }
993 }
994 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800995 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996 }
997
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700998 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
999 // Postcondition: ResourceTable has only one package left. All others are
1000 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001001 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001002 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001003 return context_->GetCompilationPackage() != pkg->name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 };
1005
1006 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001007 for (const auto& package : final_table_.packages) {
1008 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001009 // We have a package that is not related to the one we're building!
1010 for (const auto& type : package->types) {
1011 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001012 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001014 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001015 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001016 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001017 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1018 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1019 << "generated id '" << res_name
1020 << "' for external package '" << package->name
1021 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001022 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001023 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1024 << "defined resource '" << res_name
1025 << "' for external package '" << package->name
1026 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001027 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001028 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001029 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001030 }
1031 }
1032 }
1033 }
1034
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001035 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1036 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001037 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001038 return !error;
1039 }
1040
1041 /**
1042 * Returns true if no IDs have been set, false otherwise.
1043 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001044 bool VerifyNoIdsSet() {
1045 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001046 for (const auto& type : package->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001047 for (const auto& entry : type->entries) {
1048 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001049 ResourceNameRef res_name(package->name, type->type, entry->name);
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001050 context_->GetDiagnostics()->Error(DiagMessage() << "resource " << res_name << " has ID "
1051 << entry->id.value() << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001052 return false;
1053 }
1054 }
1055 }
1056 }
1057 return true;
1058 }
1059
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001060 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1061 if (options_.output_to_directory) {
1062 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001063 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001064 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001065 }
1066 }
1067
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001068 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001069 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001070 switch (format) {
1071 case OutputFormat::kApk: {
1072 BigBuffer buffer(1024);
1073 TableFlattener flattener(options_.table_flattener_options, &buffer);
1074 if (!flattener.Consume(context_, table)) {
1075 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1076 return false;
1077 }
1078
1079 io::BigBufferInputStream input_stream(&buffer);
1080 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1081 ArchiveEntry::kAlign, writer);
1082 } break;
1083
1084 case OutputFormat::kProto: {
1085 pb::ResourceTable pb_table;
Ryan Mitchellef9e6882019-06-24 11:53:33 -07001086 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics(),
1087 options_.proto_table_flattener_options);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001088 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1089 ArchiveEntry::kCompress, writer);
1090 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001091 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001092 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001093 }
1094
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001095 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001096 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Ryan Mitchell4382e442021-07-14 12:53:01 -07001097 const std::optional<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001098 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001099 return true;
1100 }
1101
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001102 std::string out_path;
1103 std::unique_ptr<io::FileOutputStream> fout;
1104 if (options_.generate_java_class_path) {
1105 out_path = options_.generate_java_class_path.value();
1106 file::AppendPath(&out_path, file::PackageToPath(out_package));
1107 if (!file::mkdirs(out_path)) {
1108 context_->GetDiagnostics()->Error(DiagMessage()
1109 << "failed to create directory '" << out_path << "'");
1110 return false;
1111 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001112
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001113 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001114
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001115 fout = util::make_unique<io::FileOutputStream>(out_path);
1116 if (fout->HadError()) {
1117 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1118 << "': " << fout->GetError());
1119 return false;
1120 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001121 }
1122
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001123 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001124 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001125 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1126 if (fout_text->HadError()) {
1127 context_->GetDiagnostics()->Error(DiagMessage()
1128 << "failed writing to '" << out_text_symbols_path.value()
1129 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001130 return false;
1131 }
1132 }
1133
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001134 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001135 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001136 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001137 return false;
1138 }
1139
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 return true;
1141 }
1142
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001143 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001144 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001145 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1146 std::vector<std::string> packages_to_callback;
1147
1148 JavaClassGeneratorOptions template_options;
1149 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1150 template_options.javadoc_annotations = options_.javadoc_annotations;
1151
1152 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1153 template_options.use_final = false;
1154 }
1155
1156 if (context_->GetPackageType() == PackageType::kSharedLib) {
1157 template_options.use_final = false;
1158 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1159 }
1160
1161 const StringPiece actual_package = context_->GetCompilationPackage();
1162 StringPiece output_package = context_->GetCompilationPackage();
1163 if (options_.custom_java_package) {
1164 // Override the output java package to the custom one.
1165 output_package = options_.custom_java_package.value();
1166 }
1167
1168 // Generate the private symbols if required.
1169 if (options_.private_symbols) {
1170 packages_to_callback.push_back(options_.private_symbols.value());
1171
1172 // If we defined a private symbols package, we only emit Public symbols
1173 // to the original package, and private and public symbols to the private package.
1174 JavaClassGeneratorOptions options = template_options;
1175 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1176 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1177 options)) {
1178 return false;
1179 }
1180 }
1181
1182 // Generate copies of the original package R class but with different package names.
1183 // This is to support non-namespaced builds.
1184 for (const std::string& extra_package : options_.extra_java_packages) {
1185 packages_to_callback.push_back(extra_package);
1186
1187 JavaClassGeneratorOptions options = template_options;
1188 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1189 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1190 return false;
1191 }
1192 }
1193
1194 // Generate R classes for each package that was merged (static library).
1195 // Use the actual package's resources only.
1196 for (const std::string& package : table_merger_->merged_packages()) {
1197 packages_to_callback.push_back(package);
1198
1199 JavaClassGeneratorOptions options = template_options;
1200 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1201 if (!WriteJavaFile(&final_table_, package, package, options)) {
1202 return false;
1203 }
1204 }
1205
1206 // Generate the main public R class.
1207 JavaClassGeneratorOptions options = template_options;
1208
1209 // Only generate public symbols if we have a private package.
1210 if (options_.private_symbols) {
1211 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1212 }
1213
1214 if (options.rewrite_callback_options) {
1215 options.rewrite_callback_options.value().packages_to_callback =
1216 std::move(packages_to_callback);
1217 }
1218
1219 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1220 options_.generate_text_symbols_path)) {
1221 return false;
1222 }
1223
1224 return true;
1225 }
1226
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001228 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001229 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001230 return true;
1231 }
1232
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001233 std::unique_ptr<ClassDefinition> manifest_class =
1234 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001236 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001237 // Something bad happened, but we already logged it, so exit.
1238 return false;
1239 }
1240
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001241 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001242 // Empty Manifest class, no need to generate it.
1243 return true;
1244 }
1245
1246 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001247 for (const std::string& annotation : options_.javadoc_annotations) {
1248 std::string proper_annotation = "@";
1249 proper_annotation += annotation;
1250 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001251 }
1252
Adam Lesinski0d81f702017-06-27 15:51:09 -07001253 const std::string package_utf8 =
Ryan Mitchell4382e442021-07-14 12:53:01 -07001254 options_.custom_java_package.value_or(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001255
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001256 std::string out_path = options_.generate_java_class_path.value();
1257 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001258
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001259 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001260 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1261 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001262 return false;
1263 }
1264
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001265 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001266
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001267 io::FileOutputStream fout(out_path);
1268 if (fout.HadError()) {
1269 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1270 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001271 return false;
1272 }
1273
Makoto Onukide6e6f22020-06-22 10:17:02 -07001274 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true,
1275 false /* strip_api_annotations */, &fout);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001276 fout.Flush();
1277
1278 if (fout.HadError()) {
1279 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1280 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 return false;
1282 }
1283 return true;
1284 }
1285
Ryan Mitchell4382e442021-07-14 12:53:01 -07001286 bool WriteProguardFile(const std::optional<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001287 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 if (!out) {
1289 return true;
1290 }
1291
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001292 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001293 io::FileOutputStream fout(out_path);
1294 if (fout.HadError()) {
1295 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1296 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001297 return false;
1298 }
1299
Jean-Luc Coelho181cbfd2019-11-27 12:37:48 -08001300 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules,
1301 options_.no_proguard_location_reference);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001302 fout.Flush();
1303
1304 if (fout.HadError()) {
1305 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1306 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001307 return false;
1308 }
1309 return true;
1310 }
1311
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001312 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001313 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001314 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001315 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001316 }
1317
Adam Lesinski8780eb62017-10-31 17:44:39 -07001318 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1319 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001320 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001321 return false;
1322 }
1323
Adam Lesinski8780eb62017-10-31 17:44:39 -07001324 ResourceTable* table = apk->GetResourceTable();
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001325 if (table->packages.empty()) {
1326 return true;
1327 }
1328
1329 auto lib_package_result = GetStaticLibraryPackage(table);
1330 if (!lib_package_result.has_value()) {
1331 context_->GetDiagnostics()->Error(DiagMessage(input) << lib_package_result.error());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001332 return false;
1333 }
1334
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001335 ResourceTablePackage* pkg = lib_package_result.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001336 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001337 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001338 // Merge all resources as if they were in the compilation package. This is the old behavior
1339 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001340
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001341 // Add the package to the set of --extra-packages so we emit an R.java for each library
1342 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001343 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001344 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001345 }
1346
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001347 // Clear the package name, so as to make the resources look like they are coming from the
1348 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001349 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001350 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001351
1352 } else {
1353 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001354 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001355 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001356 }
1357
1358 if (!result) {
1359 return false;
1360 }
1361
1362 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001363 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001364 return true;
1365 }
1366
Adam Lesinski2427dce2017-11-30 15:10:28 -08001367 bool MergeExportedSymbols(const Source& source,
1368 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001369 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001370 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001371 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001372 ResourceName res_name = exported_symbol.name;
1373 if (res_name.package.empty()) {
1374 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001375 }
1376
Ryan Mitchell4382e442021-07-14 12:53:01 -07001377 std::optional<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001378 if (mangled_name) {
1379 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001380 }
1381
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001382 auto id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001383 id->SetSource(source.WithLine(exported_symbol.line));
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001384 bool result = final_table_.AddResource(
1385 NewResourceBuilder(res_name).SetValue(std::move(id)).SetAllowMangled(true).Build(),
1386 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001387 if (!result) {
1388 return false;
1389 }
1390 }
1391 return true;
1392 }
1393
Adam Lesinski2427dce2017-11-30 15:10:28 -08001394 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001395 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001396 if (context_->IsVerbose()) {
1397 context_->GetDiagnostics()->Note(DiagMessage()
1398 << "merging '" << compiled_file.name
1399 << "' from compiled file " << compiled_file.source);
1400 }
1401
1402 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1403 return false;
1404 }
1405 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1406 }
1407
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001408 // 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 -07001409 // If override is true, conflicting resources are allowed to override each other, in order of last
1410 // seen.
1411 // An io::IFileCollection is created from the ZIP file and added to the set of
1412 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001413 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001414 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001415 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001416 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417 }
1418
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001419 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001420 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001421 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001422 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001423 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001424 return false;
1425 }
1426
1427 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001428 for (auto iter = collection->Iterator(); iter->HasNext();) {
1429 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001430 error = true;
1431 }
1432 }
1433
1434 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001435 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001436 return !error;
1437 }
1438
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001439 // Takes a path to load and merge into the main ResourceTable. If override is true,
Adam Lesinski00451162017-10-03 07:44:08 -07001440 // conflicting resources are allowed to override each other, in order of last seen.
1441 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1442 // as ZIP archive and the files within are merged individually.
1443 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001444 bool MergePath(const std::string& path, bool override) {
1445 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1446 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1447 return MergeArchive(path, override);
1448 } else if (util::EndsWith(path, ".apk")) {
1449 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001450 }
1451
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001452 io::IFile* file = file_collection_->InsertFile(path);
1453 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001454 }
1455
Ryan Mitchell4ea90752020-07-31 08:21:43 -07001456 // Takes an AAPT Container file (.apc/.flat) to load and merge into the main ResourceTable.
Adam Lesinski00451162017-10-03 07:44:08 -07001457 // If override is true, conflicting resources are allowed to override each other, in order of last
1458 // seen.
1459 // All other file types are ignored. This is because these files could be coming from a zip,
1460 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001461 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001462 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001463 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001464
Adam Lesinski00451162017-10-03 07:44:08 -07001465 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001466 // Since AAPT compiles these file types and appends .flat to them, seeing
1467 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001468 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1469 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1470 << " file passed as argument. Must be "
1471 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001472 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001473 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1474 if (context_->IsVerbose()) {
1475 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1476 return true;
1477 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001478 }
1479
Adam Lesinski00451162017-10-03 07:44:08 -07001480 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1481 if (input_stream == nullptr) {
1482 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1483 return false;
1484 }
1485
1486 if (input_stream->HadError()) {
1487 context_->GetDiagnostics()->Error(DiagMessage(src)
1488 << "failed to open file: " << input_stream->GetError());
1489 return false;
1490 }
1491
1492 ContainerReaderEntry* entry;
1493 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001494
1495 if (reader.HadError()) {
1496 context_->GetDiagnostics()->Error(DiagMessage(src)
1497 << "failed to read file: " << reader.GetError());
1498 return false;
1499 }
1500
Adam Lesinski00451162017-10-03 07:44:08 -07001501 while ((entry = reader.Next()) != nullptr) {
1502 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001503 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001504 pb::ResourceTable pb_table;
1505 if (!entry->GetResTable(&pb_table)) {
1506 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1507 << entry->GetError());
1508 return false;
1509 }
1510
1511 ResourceTable table;
1512 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001513 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001514 context_->GetDiagnostics()->Error(DiagMessage(src)
1515 << "failed to deserialize resource table: " << error);
1516 return false;
1517 }
1518
1519 if (!table_merger_->Merge(src, &table, override)) {
1520 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1521 return false;
1522 }
1523 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001524 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001525 pb::internal::CompiledFile pb_compiled_file;
1526 off64_t offset;
1527 size_t len;
1528 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1529 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1530 << entry->GetError());
1531 return false;
1532 }
1533
1534 ResourceFile resource_file;
1535 std::string error;
1536 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1537 context_->GetDiagnostics()->Error(DiagMessage(src)
1538 << "failed to read compiled header: " << error);
1539 return false;
1540 }
1541
1542 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1543 return false;
1544 }
1545 }
1546 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001547 return true;
1548 }
1549
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001550 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1551 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1552 for (const std::string& assets_dir : options_.assets_dirs) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07001553 std::optional<std::vector<std::string>> files =
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001554 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1555 if (!files) {
1556 return false;
1557 }
1558
1559 for (const std::string& file : files.value()) {
1560 std::string full_key = "assets/" + file;
1561 std::string full_path = assets_dir;
1562 file::AppendPath(&full_path, file);
1563
1564 auto iter = merged_assets.find(full_key);
1565 if (iter == merged_assets.end()) {
1566 merged_assets.emplace(std::move(full_key),
1567 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1568 } else if (context_->IsVerbose()) {
1569 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1570 << "asset file overrides '" << full_path << "'");
1571 }
1572 }
1573 }
1574
1575 for (auto& entry : merged_assets) {
Ryan Mitchell81dfca02019-06-07 10:20:27 -07001576 uint32_t compression_flags = GetCompressionFlags(entry.first, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001577 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1578 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001579 return false;
1580 }
1581 }
1582 return true;
1583 }
1584
Rhed Jao2c434422020-11-12 10:48:03 +08001585 ResourceEntry* ResolveTableEntry(LinkContext* context, ResourceTable* table,
1586 Reference* reference) {
1587 if (!reference || !reference->name) {
1588 return nullptr;
1589 }
1590 auto name_ref = ResourceNameRef(reference->name.value());
1591 if (name_ref.package.empty()) {
1592 name_ref.package = context->GetCompilationPackage();
1593 }
1594 const auto search_result = table->FindResource(name_ref);
1595 if (!search_result) {
1596 return nullptr;
1597 }
1598 return search_result.value().entry;
1599 }
1600
Ryan Mitchelldba64562019-06-07 17:07:37 -07001601 void AliasAdaptiveIcon(xml::XmlResource* manifest, ResourceTable* table) {
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001602 const xml::Element* application = manifest->root->FindChild("", "application");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001603 if (!application) {
1604 return;
1605 }
1606
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001607 const xml::Attribute* icon = application->FindAttribute(xml::kSchemaAndroid, "icon");
1608 const xml::Attribute* round_icon = application->FindAttribute(xml::kSchemaAndroid, "roundIcon");
Ryan Mitchelldba64562019-06-07 17:07:37 -07001609 if (!icon || !round_icon) {
1610 return;
1611 }
1612
1613 // Find the icon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001614 const auto icon_reference = ValueCast<Reference>(icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001615 const auto icon_entry = ResolveTableEntry(context_, table, icon_reference);
1616 if (!icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001617 return;
1618 }
1619
1620 int icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001621 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001622 icon_max_sdk = (icon_max_sdk < config_value->config.sdkVersion)
1623 ? config_value->config.sdkVersion : icon_max_sdk;
1624 }
1625 if (icon_max_sdk < SDK_O) {
1626 // Adaptive icons must be versioned with v26 qualifiers, so this is not an adaptive icon.
1627 return;
1628 }
1629
1630 // Find the roundIcon resource defined within the application.
Ryan Mitchell30cd9b22020-02-13 10:42:44 -08001631 const auto round_icon_reference = ValueCast<Reference>(round_icon->compiled_value.get());
Rhed Jao2c434422020-11-12 10:48:03 +08001632 const auto round_icon_entry = ResolveTableEntry(context_, table, round_icon_reference);
1633 if (!round_icon_entry) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001634 return;
1635 }
1636
1637 int round_icon_max_sdk = 0;
Rhed Jao2c434422020-11-12 10:48:03 +08001638 for (auto& config_value : round_icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001639 round_icon_max_sdk = (round_icon_max_sdk < config_value->config.sdkVersion)
1640 ? config_value->config.sdkVersion : round_icon_max_sdk;
1641 }
1642 if (round_icon_max_sdk >= SDK_O) {
1643 // The developer explicitly used a v26 compatible drawable as the roundIcon, meaning we should
1644 // not generate an alias to the icon drawable.
1645 return;
1646 }
1647
1648 // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
Rhed Jao2c434422020-11-12 10:48:03 +08001649 for (auto& config_value : icon_entry->values) {
Ryan Mitchelldba64562019-06-07 17:07:37 -07001650 if (config_value->config.sdkVersion < SDK_O) {
1651 continue;
1652 }
1653
1654 context_->GetDiagnostics()->Note(DiagMessage() << "generating "
1655 << round_icon_reference->name.value()
1656 << " with config \"" << config_value->config
1657 << "\" for round icon compatibility");
1658
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001659 CloningValueTransformer cloner(&table->string_pool);
1660 auto value = icon_reference->Transform(cloner);
Rhed Jao2c434422020-11-12 10:48:03 +08001661 auto round_config_value =
1662 round_icon_entry->FindOrCreateValue(config_value->config, config_value->product);
Ryan Mitchellefcdb952021-04-14 17:31:37 -07001663 round_config_value->value = std::move(value);
Ryan Mitchelldba64562019-06-07 17:07:37 -07001664 }
1665 }
1666
Rhed Jao2c434422020-11-12 10:48:03 +08001667 bool VerifySharedUserId(xml::XmlResource* manifest, ResourceTable* table) {
1668 const xml::Element* manifest_el = xml::FindRootElement(manifest->root.get());
1669 if (manifest_el == nullptr) {
1670 return true;
1671 }
1672 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
1673 return true;
1674 }
1675 const xml::Attribute* attr = manifest_el->FindAttribute(xml::kSchemaAndroid, "sharedUserId");
1676 if (!attr) {
1677 return true;
1678 }
1679 const auto validate = [&](const std::string& shared_user_id) -> bool {
1680 if (util::IsAndroidSharedUserId(context_->GetCompilationPackage(), shared_user_id)) {
1681 return true;
1682 }
1683 DiagMessage error_msg(manifest_el->line_number);
1684 error_msg << "attribute 'sharedUserId' in <manifest> tag is not a valid shared user id: '"
1685 << shared_user_id << "'";
1686 if (options_.manifest_fixer_options.warn_validation) {
1687 // Treat the error only as a warning.
1688 context_->GetDiagnostics()->Warn(error_msg);
1689 return true;
1690 }
1691 context_->GetDiagnostics()->Error(error_msg);
1692 return false;
1693 };
1694 // If attr->compiled_value is not null, check if it is a ref
1695 if (attr->compiled_value) {
1696 const auto ref = ValueCast<Reference>(attr->compiled_value.get());
1697 if (ref == nullptr) {
1698 return true;
1699 }
1700 const auto shared_user_id_entry = ResolveTableEntry(context_, table, ref);
1701 if (!shared_user_id_entry) {
1702 return true;
1703 }
1704 for (const auto& value : shared_user_id_entry->values) {
1705 const auto str_value = ValueCast<String>(value->value.get());
1706 if (str_value != nullptr && !validate(*str_value->value)) {
1707 return false;
1708 }
1709 }
1710 return true;
1711 }
1712
1713 // Fallback to checking the raw value
1714 return validate(attr->value);
1715 }
1716
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001717 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1718 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001719 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1720 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001721 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001722 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1723 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001724 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001725 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001726 if (!result) {
1727 return false;
1728 }
1729
Ryan Mitchelldba64562019-06-07 17:07:37 -07001730 // When a developer specifies an adaptive application icon, and a non-adaptive round application
1731 // icon, create an alias from the round icon to the regular icon for v26 APIs and up. We do this
1732 // because certain devices prefer android:roundIcon over android:icon regardless of the API
1733 // levels of the drawables set for either. This auto-aliasing behaviour allows an app to prefer
1734 // the android:roundIcon on API 25 devices, and prefer the adaptive icon on API 26 devices.
1735 // See (b/34829129)
1736 AliasAdaptiveIcon(manifest, table);
1737
Rhed Jao2c434422020-11-12 10:48:03 +08001738 // Verify the shared user id here to handle the case of reference value.
1739 if (!VerifySharedUserId(manifest, table)) {
1740 return false;
1741 }
1742
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001743 ResourceFileFlattenerOptions file_flattener_options;
1744 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001745 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1746 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001747 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 file_flattener_options.no_auto_version = options_.no_auto_version;
1749 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001750 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001751 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1752 file_flattener_options.update_proguard_spec =
1753 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001754 file_flattener_options.output_format = options_.output_format;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001755 file_flattener_options.do_not_fail_on_missing_resources = options_.merge_only;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001756
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001757 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001758 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001759 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001760 return false;
1761 }
1762
Adam Lesinski490595a2017-11-07 17:08:07 -08001763 // Hack to fix b/68820737.
1764 // We need to modify the ResourceTable's package name, but that should NOT affect
1765 // anything else being generated, which includes the Java classes.
1766 // If required, the package name is modifed before flattening, and then modified back
1767 // to its original name.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001768 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001769 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1770 // or higher] as invalid. In order to work around this limitation, we allow the use
1771 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1772 // definition of what a valid "split" package ID is to account for this.
1773 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1774 context_->GetPackageId() != kAppPackageId &&
1775 context_->GetPackageId() != kFrameworkPackageId)
1776 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001777 if (isSplitPackage && included_feature_base_ == context_->GetCompilationPackage()) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001778 // The base APK is included, and this is a feature split. If the base package is
1779 // the same as this package, then we are building an old style Android Instant Apps feature
1780 // split and must apply this workaround to avoid requiring namespaces support.
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001781 if (!table->packages.empty() &&
1782 table->packages.back()->name == context_->GetCompilationPackage()) {
1783 package_to_rewrite = table->packages.back().get();
Adam Lesinski490595a2017-11-07 17:08:07 -08001784 std::string new_package_name =
1785 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
Ryan Mitchell4382e442021-07-14 12:53:01 -07001786 app_info_.split_name.value_or("feature").c_str());
Adam Lesinski490595a2017-11-07 17:08:07 -08001787
1788 if (context_->IsVerbose()) {
1789 context_->GetDiagnostics()->Note(
1790 DiagMessage() << "rewriting resource package name for feature split to '"
1791 << new_package_name << "'");
1792 }
1793 package_to_rewrite->name = new_package_name;
1794 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001796
1797 bool success = FlattenTable(table, options_.output_format, writer);
1798
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001799 if (package_to_rewrite != nullptr) {
Adam Lesinski490595a2017-11-07 17:08:07 -08001800 // Change the name back.
1801 package_to_rewrite->name = context_->GetCompilationPackage();
Ryan Mitchell87d30dd2021-03-30 08:22:39 -07001802
1803 // TableFlattener creates an `included_packages_` mapping entry for each package with a
1804 // non-standard package id (not 0x01 or 0x7f). Since this is a feature split and not a shared
1805 // library, do not include a mapping from the feature package name to the feature package id
1806 // in the feature's dynamic reference table.
1807 table->included_packages_.erase(context_->GetPackageId());
Adam Lesinski490595a2017-11-07 17:08:07 -08001808 }
1809
1810 if (!success) {
1811 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1812 }
1813 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001814 }
1815
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001816 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001817 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001818 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001819 std::unique_ptr<xml::XmlResource> manifest_xml =
1820 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1821 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001822 return 1;
1823 }
1824
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001825 // First extract the Package name without modifying it (via --rename-manifest-package).
Ryan Mitchell4382e442021-07-14 12:53:01 -07001826 if (std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001827 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001828 const AppInfo& app_info = maybe_app_info.value();
1829 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001830 }
1831
Ryan Mitchell2b7e8472020-05-06 11:26:48 -07001832 // Determine the package name under which to merge resources.
1833 if (options_.rename_resources_package) {
1834 if (!options_.custom_java_package) {
1835 // Generate the R.java under the original package name instead of the package name specified
1836 // through --rename-resources-package.
1837 options_.custom_java_package = context_->GetCompilationPackage();
1838 }
1839 context_->SetCompilationPackage(options_.rename_resources_package.value());
1840 }
1841
Adam Lesinskic6284372017-12-04 13:46:23 -08001842 // Now that the compilation package is set, load the dependencies. This will also extract
1843 // the Android framework's versionCode and versionName, if they exist.
1844 if (!LoadSymbolsFromIncludePaths()) {
1845 return 1;
1846 }
1847
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001848 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1849 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001850 return 1;
1851 }
1852
Ryan Mitchell4382e442021-07-14 12:53:01 -07001853 std::optional<AppInfo> maybe_app_info =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001854 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001855 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001856 return 1;
1857 }
1858
Adam Lesinski490595a2017-11-07 17:08:07 -08001859 app_info_ = maybe_app_info.value();
Ryan Mitchell4382e442021-07-14 12:53:01 -07001860 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001861
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001862 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Udam Sainib228df32019-06-18 16:50:34 -07001863 context_->SetSplitNameDependencies(app_info_.split_name_dependencies);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001864
1865 // Override the package ID when it is "android".
1866 if (context_->GetCompilationPackage() == "android") {
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001867 context_->SetPackageId(kAndroidPackageId);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001868
1869 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001870 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001871 context_->GetDiagnostics()->Error(
1872 DiagMessage() << "package 'android' can only be built as a regular app");
1873 return 1;
1874 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001875 }
1876
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001877 TableMergerOptions table_merger_options;
1878 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Donald Chai121c6e82019-06-12 12:51:57 -07001879 table_merger_options.override_styles_instead_of_overlaying =
1880 options_.override_styles_instead_of_overlaying;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001881 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001882 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001883
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 if (context_->IsVerbose()) {
1885 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001886 << StringPrintf("linking package '%s' using package ID %02x",
1887 context_->GetCompilationPackage().data(),
1888 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001889 }
1890
Adam Lesinski2427dce2017-11-30 15:10:28 -08001891 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1892 // in res/**/*.
1893 {
1894 XmlIdCollector collector;
1895 if (!collector.Consume(context_, manifest_xml.get())) {
1896 return false;
1897 }
1898
1899 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1900 return false;
1901 }
1902 }
1903
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 for (const std::string& input : input_files) {
1905 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001906 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001907 return 1;
1908 }
1909 }
1910
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001911 for (const std::string& input : options_.overlay_files) {
1912 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001913 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001914 return 1;
1915 }
1916 }
1917
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001919 return 1;
1920 }
1921
Adam Lesinskib522f042017-04-21 16:57:59 -07001922 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001923 PrivateAttributeMover mover;
Ryan Mitchell22dc5312020-06-01 12:17:07 -07001924 if (context_->GetPackageId() == kAndroidPackageId &&
1925 !mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001926 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001927 return 1;
1928 }
1929
1930 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001931 IdAssigner id_assigner(&options_.stable_id_map);
1932 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001933 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001934 return 1;
1935 }
1936
1937 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001938 if (options_.resource_id_map_path) {
1939 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001940 for (auto& type : package->types) {
1941 for (auto& entry : type->entries) {
1942 ResourceName name(package->name, type->type, entry->name);
1943 // The IDs are guaranteed to exist.
Ryan Mitchell9634efb2021-03-19 14:53:17 -07001944 options_.stable_id_map[std::move(name)] = entry->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001945 }
1946 }
1947 }
1948
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001949 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001950 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001951 return 1;
1952 }
1953 }
1954 } else {
1955 // Static libs are merged with other apps, and ID collisions are bad, so
1956 // verify that
1957 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001958 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001959 return 1;
1960 }
1961 }
1962
1963 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001964 context_->SetNameManglerPolicy(
1965 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001966
1967 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001968 context_->GetExternalSymbols()->PrependSource(
1969 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001970
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001971 // Workaround for pre-O runtime that would treat negative resource IDs
1972 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1973 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1974 // are just identifiers.
1975 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1976 if (context_->IsVerbose()) {
1977 context_->GetDiagnostics()->Note(DiagMessage()
1978 << "enabling pre-O feature split ID rewriting");
1979 }
1980 context_->GetExternalSymbols()->SetDelegate(
1981 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1982 }
1983
Adam Lesinski34a16872018-02-23 16:18:10 -08001984 // Before we process anything, remove the resources whose default values don't exist.
1985 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02001986 if (!options_.no_resource_removal) {
1987 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1988 context_->GetDiagnostics()->Error(DiagMessage()
1989 << "failed removing resources with no defaults");
1990 return 1;
1991 }
Adam Lesinski34a16872018-02-23 16:18:10 -08001992 }
1993
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001994 ReferenceLinker linker;
Izabela Orlowska84febea2019-06-03 18:34:12 +01001995 if (!options_.merge_only && !linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001996 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001997 return 1;
1998 }
1999
Adam Lesinskib522f042017-04-21 16:57:59 -07002000 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002001 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002002 context_->GetDiagnostics()->Warn(DiagMessage()
2003 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002004 }
2005 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002006 ProductFilter product_filter(options_.products);
2007 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002008 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002009 return 1;
2010 }
2011 }
2012
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002013 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002014 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002015 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002016 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002017 return 1;
2018 }
2019 }
2020
Adam Lesinskib522f042017-04-21 16:57:59 -07002021 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002022 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002023 context_->GetDiagnostics()->Note(DiagMessage()
2024 << "collapsing resource versions for minimum SDK "
2025 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002026 }
2027
2028 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002029 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002030 return 1;
2031 }
2032 }
2033
Winson3c918b82019-01-25 14:25:37 -08002034 if (!options_.exclude_configs_.empty()) {
2035 std::vector<ConfigDescription> excluded_configs;
2036
2037 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002038 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08002039 ConfigDescription config_description;
2040
2041 if (!ConfigDescription::Parse(config_string, &config_description)) {
2042 context_->GetDiagnostics()->Error(DiagMessage()
2043 << "failed to parse --excluded-configs "
2044 << config_string);
2045 return 1;
2046 }
2047
2048 excluded_configs.push_back(config_description);
2049 }
2050
2051 ResourceExcluder excluder(excluded_configs);
2052 if (!excluder.Consume(context_, &final_table_)) {
2053 context_->GetDiagnostics()->Error(DiagMessage() << "failed excluding configurations");
2054 return 1;
2055 }
2056 }
2057
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002058 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002059 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002060 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002061 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002062 return 1;
2063 }
2064 }
2065
Adam Koskidc21dea2017-07-21 10:55:27 -07002066 proguard::KeepSet proguard_keep_set =
2067 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002068 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002069
Adam Lesinskib522f042017-04-21 16:57:59 -07002070 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002071 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00002072 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002073 context_->GetDiagnostics()->Warn(DiagMessage()
2074 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002075 }
2076 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002077 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
2078 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002079 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002080 options_.split_constraints =
2081 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002082
Todd Kennedy9fbdf892018-08-28 16:31:15 -07002083 if (origConstraintSize != options_.split_constraints.size()) {
2084 context_->GetDiagnostics()->Warn(DiagMessage()
2085 << "requested to split resources prior to min sdk of "
2086 << context_->GetMinSdkVersion());
2087 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002088 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002089 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002090 return 1;
2091 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002092 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002093
2094 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002095 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002096 auto split_constraints_iter = options_.split_constraints.begin();
2097 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002098 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002099 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
2100 << "generating split with configurations '"
2101 << util::Joiner(split_constraints_iter->configs, ", ")
2102 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002103 }
2104
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002105 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002106 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002107 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002108 return 1;
2109 }
2110
2111 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002112 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08002113 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002114
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002115 XmlReferenceLinker linker(&final_table_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002116 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002117 context_->GetDiagnostics()->Error(DiagMessage()
2118 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002119 return 1;
2120 }
2121
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002122 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
2123 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002124 return 1;
2125 }
2126
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002127 ++path_iter;
2128 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002129 }
2130 }
2131
2132 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002133 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002134 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002135 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002136 return 1;
2137 }
2138
2139 bool error = false;
2140 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002141 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002142 // (aka, which package the AndroidManifest.xml is coming from).
2143 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002144 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002145
Ryan Mitchell326e35ff2021-04-12 07:50:42 -07002146 XmlReferenceLinker manifest_linker(&final_table_);
Izabela Orlowska84febea2019-06-03 18:34:12 +01002147 if (options_.merge_only || manifest_linker.Consume(context_, manifest_xml.get())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002148 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002149 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002150 error = true;
2151 }
2152
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002153 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07002154 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002155 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002156 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07002157 }
2158
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002159 if (options_.generate_java_class_path) {
2160 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002161 error = true;
2162 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002163 }
2164
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002165 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002166 // PackageParser will fail if URIs are removed from
2167 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002168 XmlNamespaceRemover namespace_remover(true /* keepUris */);
2169 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002170 error = true;
2171 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07002172 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002173 } else {
2174 error = true;
2175 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002176 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002177
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002178 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002179 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002180 return 1;
2181 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002182
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002183 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2184 return 1;
2185 }
2186
2187 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002188 return 1;
2189 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002190
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002191 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002192 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002193 return 1;
2194 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002195 }
2196
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002197 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002198 return 1;
2199 }
2200
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002201 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2202 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002203 return 1;
2204 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002205 return 0;
2206 }
2207
2208 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002209 LinkOptions options_;
2210 LinkContext* context_;
2211 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002212
Adam Lesinski490595a2017-11-07 17:08:07 -08002213 AppInfo app_info_;
2214
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002215 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002216
2217 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002218 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002219
Adam Lesinski8780eb62017-10-31 17:44:39 -07002220 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002221 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002222 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002223
Adam Lesinski8780eb62017-10-31 17:44:39 -07002224 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2225 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2226
2227 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2228 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002229
2230 // The set of shared libraries being used, mapping their assigned package ID to package name.
2231 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002232
2233 // The package name of the base application, if it is included.
Ryan Mitchell4382e442021-07-14 12:53:01 -07002234 std::optional<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002235};
2236
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002237int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002238 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002239 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002240
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002241 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002242 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002243 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002244 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002245 const std::string path = arg.substr(1, arg.size() - 1);
2246 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002247 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2248 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002249 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002250 }
2251 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002252 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002253 }
2254 }
2255
2256 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002257 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002258 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002259 const std::string path = arg.substr(1, arg.size() - 1);
2260 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002261 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002262 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002263 return 1;
2264 }
2265 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002266 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002267 }
2268 }
2269
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002270 if (verbose_) {
2271 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002272 }
2273
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002274 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002275 context.GetDiagnostics()->Error(
2276 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002277 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002278 return 1;
2279 }
2280
Ryan Mitchell5855de72021-02-24 14:39:13 -08002281 if (shared_lib_ && options_.private_symbols) {
2282 // If a shared library styleable in a public R.java uses a private attribute, attempting to
2283 // reference the private attribute within the styleable array will cause a link error because
2284 // the private attribute will not be emitted in the public R.java.
2285 context.GetDiagnostics()->Error(DiagMessage()
2286 << "--shared-lib cannot currently be used in combination with"
2287 << " --private-symbols");
2288 return 1;
2289 }
2290
Izabela Orlowska84febea2019-06-03 18:34:12 +01002291 if (options_.merge_only && !static_lib_) {
2292 context.GetDiagnostics()->Error(
2293 DiagMessage() << "the --merge-only flag can be only used when building a static library");
2294 return 1;
2295 }
2296
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002297 // The default build type.
2298 context.SetPackageType(PackageType::kApp);
2299 context.SetPackageId(kAppPackageId);
2300
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002301 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002302 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002303 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002304 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002305 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002306 options_.output_format = OutputFormat::kProto;
2307 } else if (proto_format_) {
2308 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002309 }
2310
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002311 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002312 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002313 context.GetDiagnostics()->Error(
2314 DiagMessage() << "can't specify --package-id when not building a regular app");
2315 return 1;
2316 }
2317
Ryan Mitchell4382e442021-07-14 12:53:01 -07002318 const std::optional<uint32_t> maybe_package_id_int =
2319 ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002320 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002321 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002322 << "' is not a valid integer");
2323 return 1;
2324 }
2325
2326 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002327 if (package_id_int > std::numeric_limits<uint8_t>::max()
2328 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002329 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002330 context.GetDiagnostics()->Error(
2331 DiagMessage() << StringPrintf(
2332 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2333 return 1;
2334 }
2335 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2336 }
2337
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002338 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002339 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002340 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002341 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002342 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002343 }
2344 }
2345
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002346 if (product_list_) {
2347 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002348 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002349 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002350 }
2351 }
2352 }
2353
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002354 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002355 if (!configs_.empty()) {
2356 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002357 if (filter == nullptr) {
2358 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002359 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002360 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002361 }
2362
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002363 if (preferred_density_) {
Ryan Mitchell4382e442021-07-14 12:53:01 -07002364 std::optional<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002365 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002366 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002367 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002368 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002369 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002370 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002371
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002372 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002373 for (const std::string& split_arg : split_args_) {
2374 options_.split_paths.push_back({});
2375 options_.split_constraints.push_back({});
2376 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2377 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002378 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002379 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002380 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002381
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002382 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2383 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2384 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002385 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002386 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002387 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002388
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002389 if (no_compress_regex) {
2390 std::string regex = no_compress_regex.value();
2391 if (util::StartsWith(regex, "@")) {
2392 const std::string path = regex.substr(1, regex.size() -1);
2393 std::string error;
2394 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
2395 context.GetDiagnostics()->Error(DiagMessage(path) << error);
2396 return 1;
2397 }
2398 } else {
2399 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2400 }
2401 }
2402
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002403 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchellbf511dd2020-09-14 10:28:14 -07002404 options_.extensions_to_not_compress.insert({
2405 // Image extensions
2406 ".jpg", ".jpeg", ".png", ".gif", ".webp",
2407 // Audio extensions
2408 ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy",
2409 ".xmf", ".amr", ".awb",
2410 // Audio/video extensions
2411 ".mpg", ".mpeg", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".wma", ".wmv",
2412 ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002413
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002414 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002415 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002416 options_.no_auto_version = true;
2417 options_.no_version_vectors = true;
2418 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002419 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002420
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002421 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002422 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002423}
2424
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002425} // namespace aapt