blob: f354bb6102241425906e01c510105ad94b882012 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ryan Mitchell833a1a62018-07-10 13:51:36 -070017#include "Link.h"
18
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019#include <sys/stat.h>
Adam Lesinskic6284372017-12-04 13:46:23 -080020#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070021
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050022#include <algorithm>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070023#include <queue>
24#include <unordered_map>
25#include <vector>
26
27#include "android-base/errors.h"
28#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080029#include "android-base/stringprintf.h"
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020030#include "androidfw/Locale.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080031#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070032
Adam Lesinski1ab598f2015-08-14 14:26:04 -070033#include "AppInfo.h"
34#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070035#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070036#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080037#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070038#include "ResourceValues.h"
39#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070040#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070041#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080042#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080043#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070045#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070046#include "format/binary/TableFlattener.h"
47#include "format/binary/XmlFlattener.h"
48#include "format/proto/ProtoDeserialize.h"
49#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070050#include "io/BigBufferStream.h"
51#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070053#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080054#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070055#include "java/JavaClassGenerator.h"
56#include "java/ManifestClassGenerator.h"
57#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070059#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080060#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080061#include "link/ReferenceLinker.h"
Winson3c918b82019-01-25 14:25:37 -080062#include "link/ResourceExcluder.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070063#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070064#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080065#include "optimize/ResourceDeduper.h"
66#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067#include "process/IResourceTableConsumer.h"
68#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080069#include "split/TableSplitter.h"
Fabien Sanglard2d34e762019-02-21 15:13:29 -080070#include "trace/TraceBuffer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080072#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070073
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070074using ::aapt::io::FileInputStream;
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020075using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070076using ::android::StringPiece;
77using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070078
Adam Lesinski1ab598f2015-08-14 14:26:04 -070079namespace aapt {
80
Adam Lesinski64587af2016-02-18 18:33:06 -080081class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070082 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -080083 explicit LinkContext(IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +010084 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -070085 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070086
Adam Lesinskib522f042017-04-21 16:57:59 -070087 PackageType GetPackageType() override {
88 return package_type_;
89 }
90
91 void SetPackageType(PackageType type) {
92 package_type_ = type;
93 }
94
Adam Lesinskid0f492d2017-04-03 18:12:45 -070095 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +010096 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070097 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070098
Adam Lesinskid0f492d2017-04-03 18:12:45 -070099 NameMangler* GetNameMangler() override {
100 return &name_mangler_;
101 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700102
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700103 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
104 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700105 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800106
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700107 const std::string& GetCompilationPackage() override {
108 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700109 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700110
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700111 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800112 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700113 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800114
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700115 uint8_t GetPackageId() override {
116 return package_id_;
117 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700118
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700119 void SetPackageId(uint8_t id) {
120 package_id_ = id;
121 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800122
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700123 SymbolTable* GetExternalSymbols() override {
124 return &symbols_;
125 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800126
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700127 bool IsVerbose() override {
128 return verbose_;
129 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800130
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700131 void SetVerbose(bool val) {
132 verbose_ = val;
133 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800134
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700135 int GetMinSdkVersion() override {
136 return min_sdk_version_;
137 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700138
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700139 void SetMinSdkVersion(int minSdk) {
140 min_sdk_version_ = minSdk;
141 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700142
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700143 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700144 DISALLOW_COPY_AND_ASSIGN(LinkContext);
145
Adam Lesinskib522f042017-04-21 16:57:59 -0700146 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100147 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700148 NameMangler name_mangler_;
149 std::string compilation_package_;
150 uint8_t package_id_ = 0x0;
151 SymbolTable symbols_;
152 bool verbose_ = false;
153 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700154};
155
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700156// A custom delegate that generates compatible pre-O IDs for use with feature splits.
157// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
158// is interpreted as a negative number. Some verification was wrongly assuming negative values
159// were invalid.
160//
161// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
162// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
163// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800164//
165// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700166class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
167 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800168 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700169 }
170
171 virtual ~FeatureSplitSymbolTableDelegate() = default;
172
173 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
174 const ResourceName& name,
175 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
176 std::unique_ptr<SymbolTable::Symbol> symbol =
177 DefaultSymbolTableDelegate::FindByName(name, sources);
178 if (symbol == nullptr) {
179 return {};
180 }
181
182 // Check to see if this is an 'id' with the target package.
183 if (name.type == ResourceType::kId && symbol->id) {
184 ResourceId* id = &symbol->id.value();
185 if (id->package_id() > kAppPackageId) {
186 // Rewrite the resource ID to be compatible pre-O.
187 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
188
189 // Check that this doesn't overlap another resource.
190 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
191 // The ID overlaps, so log a message (since this is a weird failure) and fail.
192 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
193 << " for pre-O feature split support");
194 return {};
195 }
196
197 if (context_->IsVerbose()) {
198 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
199 << ") -> (" << rewritten_id << ")");
200 }
201
202 *id = rewritten_id;
203 }
204 }
205 return symbol;
206 }
207
208 private:
209 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
210
211 IAaptContext* context_;
212};
213
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700214static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
215 const StringPiece& path, bool keep_raw_values, bool utf16,
216 OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800217 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700218 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700219 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
220 << (keep_raw_values ? "true" : "false")
221 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700222 }
223
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700224 switch (format) {
225 case OutputFormat::kApk: {
226 BigBuffer buffer(1024);
227 XmlFlattenerOptions options = {};
228 options.keep_raw_values = keep_raw_values;
229 options.use_utf16 = utf16;
230 XmlFlattener flattener(&buffer, options);
231 if (!flattener.Consume(context, &xml_res)) {
232 return false;
233 }
234
235 io::BigBufferInputStream input_stream(&buffer);
236 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
237 ArchiveEntry::kCompress, writer);
238 } break;
239
240 case OutputFormat::kProto: {
241 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800242 // Strip whitespace text nodes from tha AndroidManifest.xml
243 SerializeXmlOptions options;
244 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700245 SerializeXmlResourceToPb(xml_res, &pb_node);
246 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
247 writer);
248 } break;
249 }
250 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800251}
252
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700253// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700254static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800255 TRACE_CALL();
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700256 FileInputStream fin(path);
257 if (fin.HadError()) {
258 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700259 return {};
260 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700261 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800262}
263
Adam Lesinski355f2852016-02-13 20:26:45 -0800264struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700265 bool no_auto_version = false;
266 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900267 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700268 bool no_xml_namespaces = false;
269 bool keep_raw_values = false;
270 bool do_not_compress_anything = false;
271 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700272 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700273 std::unordered_set<std::string> extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +0100274 Maybe<std::regex> regex_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800275};
276
Adam Lesinskic744ae82017-05-17 19:28:38 -0700277// A sampling of public framework resource IDs.
278struct R {
279 struct attr {
280 enum : uint32_t {
281 paddingLeft = 0x010100d6u,
282 paddingRight = 0x010100d8u,
283 paddingHorizontal = 0x0101053du,
284
285 paddingTop = 0x010100d7u,
286 paddingBottom = 0x010100d9u,
287 paddingVertical = 0x0101053eu,
288
289 layout_marginLeft = 0x010100f7u,
290 layout_marginRight = 0x010100f9u,
291 layout_marginHorizontal = 0x0101053bu,
292
293 layout_marginTop = 0x010100f8u,
294 layout_marginBottom = 0x010100fau,
295 layout_marginVertical = 0x0101053cu,
296 };
297 };
298};
299
Adam Lesinski355f2852016-02-13 20:26:45 -0800300class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700301 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700302 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700303 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800304
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700305 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800306
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700307 private:
308 struct FileOperation {
309 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700310
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700311 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700312 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700313
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700314 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700315 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700316
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700317 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700318 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700319
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700320 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700321 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700322 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800323
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700324 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800325
Adam Lesinskic744ae82017-05-17 19:28:38 -0700326 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
327 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800328
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700329 ResourceFileFlattenerOptions options_;
330 IAaptContext* context_;
331 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700332 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800333};
334
Adam Lesinskic744ae82017-05-17 19:28:38 -0700335ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
336 IAaptContext* context, proguard::KeepSet* keep_set)
337 : options_(options), context_(context), keep_set_(keep_set) {
338 SymbolTable* symm = context_->GetExternalSymbols();
339
340 // Build up the rules for degrading newer attributes to older ones.
341 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
342 // generated from the attribute definitions themselves (b/62028956).
343 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
344 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800345 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
346 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700347 };
348 rules_[R::attr::paddingHorizontal] =
349 util::make_unique<DegradeToManyRule>(std::move(replacements));
350 }
351
352 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
353 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800354 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
355 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700356 };
357 rules_[R::attr::paddingVertical] =
358 util::make_unique<DegradeToManyRule>(std::move(replacements));
359 }
360
361 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
362 std::vector<ReplacementAttr> replacements{
363 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800364 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700365 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800366 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700367 };
368 rules_[R::attr::layout_marginHorizontal] =
369 util::make_unique<DegradeToManyRule>(std::move(replacements));
370 }
371
372 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
373 std::vector<ReplacementAttr> replacements{
374 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800375 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700376 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800377 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700378 };
379 rules_[R::attr::layout_marginVertical] =
380 util::make_unique<DegradeToManyRule>(std::move(replacements));
381 }
382}
383
Izabela Orlowska0faba5f2018-06-01 12:06:31 +0100384// TODO(rtmitchell): turn this function into a variable that points to a method that retrieves the
385// compression flag
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700386uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
387 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700388 return 0;
389 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800390
Izabela Orlowska0faba5f2018-06-01 12:06:31 +0100391 if (options_.regex_to_not_compress
392 && std::regex_search(str.to_string(), options_.regex_to_not_compress.value())) {
393 return 0;
394 }
395
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700396 for (const std::string& extension : options_.extensions_to_not_compress) {
397 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700398 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800399 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700400 }
401 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800402}
403
Adam Lesinskibb94f322017-07-12 07:41:55 -0700404static bool IsTransitionElement(const std::string& name) {
405 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
406 name == "changeImageTransform" || name == "changeTransform" ||
407 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
408 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
409 name == "transitionManager";
410}
411
412static bool IsVectorElement(const std::string& name) {
413 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800414 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
415 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700416}
417
Adam Lesinskic744ae82017-05-17 19:28:38 -0700418template <typename T>
419std::vector<T> make_singleton_vec(T&& val) {
420 std::vector<T> vec;
421 vec.emplace_back(std::forward<T>(val));
422 return vec;
423}
424
425std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
426 ResourceTable* table, FileOperation* file_op) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800427 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700428 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700429 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700430
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700431 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700432 context_->GetDiagnostics()->Note(DiagMessage()
433 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700434 }
435
Adam Lesinski00451162017-10-03 07:44:08 -0700436 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
437 // that existing projects have out-of-date references which pass compilation.
438 xml::StripAndroidStudioAttributes(doc->root.get());
439
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700440 XmlReferenceLinker xml_linker;
441 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700442 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700443 }
444
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700445 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700446 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700447 }
448
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700449 if (options_.no_xml_namespaces) {
450 XmlNamespaceRemover namespace_remover;
451 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700452 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800453 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700454 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800455
Adam Lesinskibb94f322017-07-12 07:41:55 -0700456 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700457 return make_singleton_vec(std::move(file_op->xml_to_flatten));
458 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700459
Adam Lesinskibb94f322017-07-12 07:41:55 -0700460 if (options_.no_version_vectors || options_.no_version_transitions) {
461 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700462 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700463 if (el && el->namespace_uri.empty()) {
464 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
465 (options_.no_version_transitions && IsTransitionElement(el->name))) {
466 return make_singleton_vec(std::move(file_op->xml_to_flatten));
467 }
468 }
469 }
470
Adam Lesinskic744ae82017-05-17 19:28:38 -0700471 const ConfigDescription& config = file_op->config;
472 ResourceEntry* entry = file_op->entry;
473
474 XmlCompatVersioner xml_compat_versioner(&rules_);
475 const util::Range<ApiVersion> api_range{config.sdkVersion,
476 FindNextApiVersionForConfig(entry, config)};
477 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800478}
479
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800480ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
481 switch (format) {
482 case OutputFormat::kApk:
483 return ResourceFile::Type::kBinaryXml;
484 case OutputFormat::kProto:
485 return ResourceFile::Type::kProtoXml;
486 }
487 LOG_ALWAYS_FATAL("unreachable");
488 return ResourceFile::Type::kUnknown;
489}
490
Ryan Mitchell70f79722018-08-13 07:37:24 -0700491static auto kDrawableVersions = std::map<std::string, ApiVersion>{
492 { "adaptive-icon" , SDK_O },
493};
494
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700495bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800496 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700497 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700498 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800499
Adam Koskidc21dea2017-07-21 10:55:27 -0700500 proguard::CollectResourceReferences(context_, table, keep_set_);
501
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700502 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700503 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
504
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700505 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700506 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700507 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700508 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800509
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700510 // Populate the queue with all files in the ResourceTable.
511 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700512 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700513 // WARNING! Do not insert or remove any resources while executing in this scope. It will
514 // corrupt the iteration order.
515
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700516 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700517 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700518 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700519 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700520
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700521 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700522 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700523 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700524 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700525 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700526 }
527
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700528 FileOperation file_op;
529 file_op.entry = entry.get();
530 file_op.dst_path = *file_ref->path;
531 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700532 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700534 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700535 (file_ref->type == ResourceFile::Type::kBinaryXml ||
536 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700537 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700538 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700539 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700540 << "failed to open file");
541 return false;
542 }
543
Adam Lesinski00451162017-10-03 07:44:08 -0700544 if (file_ref->type == ResourceFile::Type::kProtoXml) {
545 pb::XmlNode pb_xml_node;
546 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
547 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700548 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700549 return false;
550 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551
Adam Lesinski00451162017-10-03 07:44:08 -0700552 std::string error;
553 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
554 if (file_op.xml_to_flatten == nullptr) {
555 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700556 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700557 return false;
558 }
559 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700560 std::string error_str;
561 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700562 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700563 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
564 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700565 return false;
566 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700567 }
568
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800569 // Update the type that this file will be written as.
570 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
571
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700572 file_op.xml_to_flatten->file.config = config_value->config;
573 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700574 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700575 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700576
577 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
578 // else we end up copying the string in the std::make_pair() method,
579 // then creating a StringPiece from the copy, which would cause us
580 // to end up referencing garbage in the map.
581 const StringPiece entry_name(entry->name);
582 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
583 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700584 }
585 }
586
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700587 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700588 for (auto& map_entry : config_sorted_files) {
589 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700590 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700592 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700593 // Check minimum sdk versions supported for drawables
594 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
595 if (drawable_entry != kDrawableVersions.end()) {
596 if (drawable_entry->second > context_->GetMinSdkVersion()
597 && drawable_entry->second > config.sdkVersion) {
598 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
599 << "<" << drawable_entry->first << "> elements "
600 << "require a sdk version of at least "
601 << (int16_t) drawable_entry->second);
602 error = true;
603 continue;
604 }
605 }
606
Adam Lesinskic744ae82017-05-17 19:28:38 -0700607 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
608 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700609 if (versioned_docs.empty()) {
610 error = true;
611 continue;
612 }
613
Adam Lesinskic744ae82017-05-17 19:28:38 -0700614 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
615 std::string dst_path = file_op.dst_path;
616 if (doc->file.config != file_op.config) {
617 // Only add the new versioned configurations.
618 if (context_->IsVerbose()) {
619 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
620 << "auto-versioning resource from config '"
621 << config << "' -> '" << doc->file.config << "'");
622 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700623
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800624 const ResourceFile& file = doc->file;
625 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
626
627 std::unique_ptr<FileReference> file_ref =
628 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
629 file_ref->SetSource(doc->file.source);
630 // Update the output format of this XML file.
631 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
632 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
633 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700634 return false;
635 }
636 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700637
638 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
639 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700640 }
641 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700642 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
643 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700644 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700645 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700646 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700647 }
648 return !error;
649}
650
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700651static bool WriteStableIdMapToPath(IDiagnostics* diag,
652 const std::unordered_map<ResourceName, ResourceId>& id_map,
653 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800654 io::FileOutputStream fout(id_map_path);
655 if (fout.HadError()) {
656 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700657 return false;
658 }
659
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800660 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700661 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700662 const ResourceName& name = entry.first;
663 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800664 printer.Print(name.to_string());
665 printer.Print(" = ");
666 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700667 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800668 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700669
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800670 if (fout.HadError()) {
671 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700672 return false;
673 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700674 return true;
675}
676
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700677static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
678 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700679 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700680 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700681 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 return false;
683 }
684
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700685 out_id_map->clear();
686 size_t line_no = 0;
687 for (StringPiece line : util::Tokenize(content, '\n')) {
688 line_no++;
689 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700690 if (line.empty()) {
691 continue;
692 }
693
694 auto iter = std::find(line.begin(), line.end(), '=');
695 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700696 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700697 return false;
698 }
699
700 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700701 StringPiece res_name_str =
702 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
703 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700704 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
705 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 return false;
707 }
708
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700709 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
710 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700711 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700712
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700713 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
714 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700715 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
716 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700717 return false;
718 }
719
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700720 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700721 }
722 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700723}
724
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800725static android::ApkAssetsCookie FindFrameworkAssetManagerCookie(
726 const android::AssetManager2& assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800727 using namespace android;
728
729 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
730 // we're looking for the first attribute resource in the system package.
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800731 Res_value val{};
732 ResTable_config config{};
733 uint32_t type_spec_flags;
734 ApkAssetsCookie idx = assets.GetResource(0x01010000, true /** may_be_bag */,
735 0 /** density_override */, &val, &config,
736 &type_spec_flags);
Adam Lesinskic6284372017-12-04 13:46:23 -0800737
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800738 return idx;
Adam Lesinskic6284372017-12-04 13:46:23 -0800739}
740
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700741class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700742 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700743 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700744 : options_(options),
745 context_(context),
746 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700747 file_collection_(util::make_unique<io::FileCollection>()) {
748 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700749
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800750 void ExtractCompileSdkVersions(android::AssetManager2* assets) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800751 using namespace android;
752
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800753 android::ApkAssetsCookie cookie = FindFrameworkAssetManagerCookie(*assets);
754 if (cookie == android::kInvalidCookie) {
Adam Lesinskic6284372017-12-04 13:46:23 -0800755 // No Framework assets loaded. Not a failure.
756 return;
757 }
758
759 std::unique_ptr<Asset> manifest(
Ryan Mitchella55dc2e2019-01-24 10:58:23 -0800760 assets->OpenNonAsset(kAndroidManifestPath, cookie, Asset::AccessMode::ACCESS_BUFFER));
Adam Lesinskic6284372017-12-04 13:46:23 -0800761 if (manifest == nullptr) {
762 // No errors.
763 return;
764 }
765
766 std::string error;
767 std::unique_ptr<xml::XmlResource> manifest_xml =
768 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
769 if (manifest_xml == nullptr) {
770 // No errors.
771 return;
772 }
773
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700774 if (!options_.manifest_fixer_options.compile_sdk_version) {
775 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
776 if (attr != nullptr) {
777 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
778 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
779 switch (prim->value.dataType) {
780 case Res_value::TYPE_INT_DEC:
781 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
782 break;
783 case Res_value::TYPE_INT_HEX:
784 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
785 break;
786 default:
787 break;
788 }
789 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
790 compile_sdk_version = *str->value;
791 } else {
792 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800793 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800794 }
795 }
796
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700797 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
798 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
799 if (attr != nullptr) {
800 Maybe<std::string>& compile_sdk_version_codename =
801 options_.manifest_fixer_options.compile_sdk_version_codename;
802 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
803 compile_sdk_version_codename = *str->value;
804 } else {
805 compile_sdk_version_codename = attr->value;
806 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800807 }
808 }
809 }
810
Adam Lesinski8780eb62017-10-31 17:44:39 -0700811 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800812 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700813 bool LoadSymbolsFromIncludePaths() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800814 TRACE_NAME("LoadSymbolsFromIncludePaths: #" + std::to_string(options_.include_paths.size()));
Adam Lesinski8780eb62017-10-31 17:44:39 -0700815 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700816 for (const std::string& path : options_.include_paths) {
817 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700818 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700819 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700820
Adam Lesinski8780eb62017-10-31 17:44:39 -0700821 std::string error;
822 auto zip_collection = io::ZipFileCollection::Create(path, &error);
823 if (zip_collection == nullptr) {
824 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
825 return false;
826 }
827
828 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
829 // Load this as a static library include.
830 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
831 Source(path), std::move(zip_collection), context_->GetDiagnostics());
832 if (static_apk == nullptr) {
833 return false;
834 }
835
Adam Lesinskib522f042017-04-21 16:57:59 -0700836 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800837 // Can't include static libraries when not building a static library (they have no IDs
838 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700839 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800840 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700841 return false;
842 }
843
Adam Lesinski8780eb62017-10-31 17:44:39 -0700844 ResourceTable* table = static_apk->GetResourceTable();
845
846 // If we are using --no-static-lib-packages, we need to rename the package of this table to
847 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700848 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800849 // Since package names can differ, and multiple packages can exist in a ResourceTable,
850 // we place the requirement that all static libraries are built with the package
851 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700852 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700853 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800854 } else {
855 context_->GetDiagnostics()->Error(DiagMessage(path)
856 << "no package with ID 0x7f found in static library");
857 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700858 }
859 }
860
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700861 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700862 util::make_unique<ResourceTableSymbolSource>(table));
863 static_library_includes_.push_back(std::move(static_apk));
864 } else {
865 if (!asset_source->AddAssetPath(path)) {
866 context_->GetDiagnostics()->Error(DiagMessage()
867 << "failed to load include path " << path);
868 return false;
869 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700870 }
871 }
872
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800873 // Capture the shared libraries so that the final resource table can be properly flattened
874 // with support for shared libraries.
875 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700876 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800877 // Capture the included base feature package.
878 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800879 } else if (entry.first == kFrameworkPackageId) {
880 // Try to embed which version of the framework we're compiling against.
881 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
882 // when linking our synthesized 'android:compileSdkVersion' attribute.
883 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
884 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
885 if (symbol != nullptr && symbol->is_public) {
886 // The symbol is present and public, extract the android:versionName and
887 // android:versionCode from the framework AndroidManifest.xml.
888 ExtractCompileSdkVersions(asset_source->GetAssetManager());
889 }
Todd Kennedy32512992018-04-25 16:45:59 -0700890 } else if (asset_source->IsPackageDynamic(entry.first)) {
891 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800892 }
893 }
894
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700895 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700896 return true;
897 }
898
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800899 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -0800900 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700901 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800902 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
903 if (manifest_el == nullptr) {
904 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700905 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800906
907 AppInfo app_info;
908
909 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
910 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
911 return {};
912 }
913
914 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
915 if (!package_attr) {
916 diag->Error(DiagMessage(xml_res->file.source)
917 << "<manifest> must have a 'package' attribute");
918 return {};
919 }
920 app_info.package = package_attr->value;
921
922 if (xml::Attribute* version_code_attr =
923 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
924 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
925 if (!maybe_code) {
926 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
927 << "invalid android:versionCode '" << version_code_attr->value << "'");
928 return {};
929 }
930 app_info.version_code = maybe_code.value();
931 }
932
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700933 if (xml::Attribute* version_code_major_attr =
934 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
935 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
936 if (!maybe_code) {
937 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
938 << "invalid android:versionCodeMajor '"
939 << version_code_major_attr->value << "'");
940 return {};
941 }
942 app_info.version_code_major = maybe_code.value();
943 }
944
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800945 if (xml::Attribute* revision_code_attr =
946 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
947 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
948 if (!maybe_code) {
949 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
950 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
951 return {};
952 }
953 app_info.revision_code = maybe_code.value();
954 }
955
956 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
957 if (!split_name_attr->value.empty()) {
958 app_info.split_name = split_name_attr->value;
959 }
960 }
961
962 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
963 if (xml::Attribute* min_sdk =
964 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700965 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800966 }
967 }
968 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700969 }
970
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700971 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
972 // Postcondition: ResourceTable has only one package left. All others are
973 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700974 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700975 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700976 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
977 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700978 };
979
980 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700981 for (const auto& package : final_table_.packages) {
982 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700983 // We have a package that is not related to the one we're building!
984 for (const auto& type : package->types) {
985 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700986 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700987
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700988 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700989 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700990 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700991 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
992 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
993 << "generated id '" << res_name
994 << "' for external package '" << package->name
995 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700997 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
998 << "defined resource '" << res_name
999 << "' for external package '" << package->name
1000 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001001 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001002 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001003 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 }
1005 }
1006 }
1007 }
1008
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001009 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1010 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001011 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001012 return !error;
1013 }
1014
1015 /**
1016 * Returns true if no IDs have been set, false otherwise.
1017 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001018 bool VerifyNoIdsSet() {
1019 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001020 for (const auto& type : package->types) {
1021 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001022 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1023 << StringPrintf("%02x", type->id.value())
1024 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001025 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001026 }
1027
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001028 for (const auto& entry : type->entries) {
1029 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001030 ResourceNameRef res_name(package->name, type->type, entry->name);
1031 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001032 DiagMessage() << "entry " << res_name << " has ID "
1033 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001034 return false;
1035 }
1036 }
1037 }
1038 }
1039 return true;
1040 }
1041
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001042 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1043 if (options_.output_to_directory) {
1044 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001045 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001046 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001047 }
1048 }
1049
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001050 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001051 TRACE_CALL();
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001052 switch (format) {
1053 case OutputFormat::kApk: {
1054 BigBuffer buffer(1024);
1055 TableFlattener flattener(options_.table_flattener_options, &buffer);
1056 if (!flattener.Consume(context_, table)) {
1057 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1058 return false;
1059 }
1060
1061 io::BigBufferInputStream input_stream(&buffer);
1062 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1063 ArchiveEntry::kAlign, writer);
1064 } break;
1065
1066 case OutputFormat::kProto: {
1067 pb::ResourceTable pb_table;
Ryan Mitchella15c2a82018-03-26 11:05:31 -07001068 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001069 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1070 ArchiveEntry::kCompress, writer);
1071 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001072 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001073 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001074 }
1075
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001076 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001077 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001078 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001079 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001080 return true;
1081 }
1082
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001083 std::string out_path;
1084 std::unique_ptr<io::FileOutputStream> fout;
1085 if (options_.generate_java_class_path) {
1086 out_path = options_.generate_java_class_path.value();
1087 file::AppendPath(&out_path, file::PackageToPath(out_package));
1088 if (!file::mkdirs(out_path)) {
1089 context_->GetDiagnostics()->Error(DiagMessage()
1090 << "failed to create directory '" << out_path << "'");
1091 return false;
1092 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001093
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001094 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001095
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001096 fout = util::make_unique<io::FileOutputStream>(out_path);
1097 if (fout->HadError()) {
1098 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1099 << "': " << fout->GetError());
1100 return false;
1101 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001102 }
1103
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001104 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001105 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001106 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1107 if (fout_text->HadError()) {
1108 context_->GetDiagnostics()->Error(DiagMessage()
1109 << "failed writing to '" << out_text_symbols_path.value()
1110 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001111 return false;
1112 }
1113 }
1114
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001115 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001116 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001117 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001118 return false;
1119 }
1120
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001121 return true;
1122 }
1123
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001124 bool GenerateJavaClasses() {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001125 TRACE_CALL();
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001126 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1127 std::vector<std::string> packages_to_callback;
1128
1129 JavaClassGeneratorOptions template_options;
1130 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1131 template_options.javadoc_annotations = options_.javadoc_annotations;
1132
1133 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1134 template_options.use_final = false;
1135 }
1136
1137 if (context_->GetPackageType() == PackageType::kSharedLib) {
1138 template_options.use_final = false;
1139 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1140 }
1141
1142 const StringPiece actual_package = context_->GetCompilationPackage();
1143 StringPiece output_package = context_->GetCompilationPackage();
1144 if (options_.custom_java_package) {
1145 // Override the output java package to the custom one.
1146 output_package = options_.custom_java_package.value();
1147 }
1148
1149 // Generate the private symbols if required.
1150 if (options_.private_symbols) {
1151 packages_to_callback.push_back(options_.private_symbols.value());
1152
1153 // If we defined a private symbols package, we only emit Public symbols
1154 // to the original package, and private and public symbols to the private package.
1155 JavaClassGeneratorOptions options = template_options;
1156 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1157 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1158 options)) {
1159 return false;
1160 }
1161 }
1162
1163 // Generate copies of the original package R class but with different package names.
1164 // This is to support non-namespaced builds.
1165 for (const std::string& extra_package : options_.extra_java_packages) {
1166 packages_to_callback.push_back(extra_package);
1167
1168 JavaClassGeneratorOptions options = template_options;
1169 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1170 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1171 return false;
1172 }
1173 }
1174
1175 // Generate R classes for each package that was merged (static library).
1176 // Use the actual package's resources only.
1177 for (const std::string& package : table_merger_->merged_packages()) {
1178 packages_to_callback.push_back(package);
1179
1180 JavaClassGeneratorOptions options = template_options;
1181 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1182 if (!WriteJavaFile(&final_table_, package, package, options)) {
1183 return false;
1184 }
1185 }
1186
1187 // Generate the main public R class.
1188 JavaClassGeneratorOptions options = template_options;
1189
1190 // Only generate public symbols if we have a private package.
1191 if (options_.private_symbols) {
1192 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1193 }
1194
1195 if (options.rewrite_callback_options) {
1196 options.rewrite_callback_options.value().packages_to_callback =
1197 std::move(packages_to_callback);
1198 }
1199
1200 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1201 options_.generate_text_symbols_path)) {
1202 return false;
1203 }
1204
1205 return true;
1206 }
1207
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001208 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001209 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001210 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001211 return true;
1212 }
1213
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001214 std::unique_ptr<ClassDefinition> manifest_class =
1215 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001216
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001217 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 // Something bad happened, but we already logged it, so exit.
1219 return false;
1220 }
1221
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001222 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001223 // Empty Manifest class, no need to generate it.
1224 return true;
1225 }
1226
1227 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001228 for (const std::string& annotation : options_.javadoc_annotations) {
1229 std::string proper_annotation = "@";
1230 proper_annotation += annotation;
1231 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001232 }
1233
Adam Lesinski0d81f702017-06-27 15:51:09 -07001234 const std::string package_utf8 =
1235 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001236
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001237 std::string out_path = options_.generate_java_class_path.value();
1238 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001239
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001240 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001241 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1242 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001243 return false;
1244 }
1245
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001246 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001247
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001248 io::FileOutputStream fout(out_path);
1249 if (fout.HadError()) {
1250 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1251 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001252 return false;
1253 }
1254
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001255 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1256 fout.Flush();
1257
1258 if (fout.HadError()) {
1259 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1260 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001261 return false;
1262 }
1263 return true;
1264 }
1265
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001266 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001267 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001268 if (!out) {
1269 return true;
1270 }
1271
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001272 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001273 io::FileOutputStream fout(out_path);
1274 if (fout.HadError()) {
1275 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1276 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001277 return false;
1278 }
1279
Ryan Mitchell7e5236d2018-09-25 15:20:59 -07001280 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001281 fout.Flush();
1282
1283 if (fout.HadError()) {
1284 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1285 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001286 return false;
1287 }
1288 return true;
1289 }
1290
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001291 bool MergeStaticLibrary(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001292 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001293 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001294 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001295 }
1296
Adam Lesinski8780eb62017-10-31 17:44:39 -07001297 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1298 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001299 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001300 return false;
1301 }
1302
Adam Lesinski8780eb62017-10-31 17:44:39 -07001303 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001304 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001305 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001306 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001307 return false;
1308 }
1309
1310 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001311 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001312 // Merge all resources as if they were in the compilation package. This is the old behavior
1313 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001314
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001315 // Add the package to the set of --extra-packages so we emit an R.java for each library
1316 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001317 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001318 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001319 }
1320
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001321 // Clear the package name, so as to make the resources look like they are coming from the
1322 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001323 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001324 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001325
1326 } else {
1327 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001328 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001329 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001330 }
1331
1332 if (!result) {
1333 return false;
1334 }
1335
1336 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001337 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001338 return true;
1339 }
1340
Adam Lesinski2427dce2017-11-30 15:10:28 -08001341 bool MergeExportedSymbols(const Source& source,
1342 const std::vector<SourcedResourceName>& exported_symbols) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001343 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001344 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001345 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001346 ResourceName res_name = exported_symbol.name;
1347 if (res_name.package.empty()) {
1348 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001349 }
1350
Adam Lesinski00451162017-10-03 07:44:08 -07001351 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001352 if (mangled_name) {
1353 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001354 }
1355
1356 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001357 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001358 bool result =
1359 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1360 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001361 if (!result) {
1362 return false;
1363 }
1364 }
1365 return true;
1366 }
1367
Adam Lesinski2427dce2017-11-30 15:10:28 -08001368 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001369 TRACE_CALL();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001370 if (context_->IsVerbose()) {
1371 context_->GetDiagnostics()->Note(DiagMessage()
1372 << "merging '" << compiled_file.name
1373 << "' from compiled file " << compiled_file.source);
1374 }
1375
1376 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1377 return false;
1378 }
1379 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1380 }
1381
Adam Lesinski00451162017-10-03 07:44:08 -07001382 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1383 // If override is true, conflicting resources are allowed to override each other, in order of last
1384 // seen.
1385 // An io::IFileCollection is created from the ZIP file and added to the set of
1386 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001387 bool MergeArchive(const std::string& input, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001388 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001389 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001390 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001391 }
1392
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001393 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001394 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001395 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001396 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001397 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001398 return false;
1399 }
1400
1401 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001402 for (auto iter = collection->Iterator(); iter->HasNext();) {
1403 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001404 error = true;
1405 }
1406 }
1407
1408 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001409 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001410 return !error;
1411 }
1412
Adam Lesinski00451162017-10-03 07:44:08 -07001413 // Takes a path to load and merge into the master ResourceTable. If override is true,
1414 // conflicting resources are allowed to override each other, in order of last seen.
1415 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1416 // as ZIP archive and the files within are merged individually.
1417 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001418 bool MergePath(const std::string& path, bool override) {
1419 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1420 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1421 return MergeArchive(path, override);
1422 } else if (util::EndsWith(path, ".apk")) {
1423 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001424 }
1425
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001426 io::IFile* file = file_collection_->InsertFile(path);
1427 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001428 }
1429
Adam Lesinski00451162017-10-03 07:44:08 -07001430 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1431 // If override is true, conflicting resources are allowed to override each other, in order of last
1432 // seen.
1433 // All other file types are ignored. This is because these files could be coming from a zip,
1434 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001435 bool MergeFile(io::IFile* file, bool override) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001436 TRACE_CALL();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001437 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001438
Adam Lesinski00451162017-10-03 07:44:08 -07001439 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001440 // Since AAPT compiles these file types and appends .flat to them, seeing
1441 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001442 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1443 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1444 << " file passed as argument. Must be "
1445 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001446 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001447 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1448 if (context_->IsVerbose()) {
1449 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1450 return true;
1451 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001452 }
1453
Adam Lesinski00451162017-10-03 07:44:08 -07001454 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1455 if (input_stream == nullptr) {
1456 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1457 return false;
1458 }
1459
1460 if (input_stream->HadError()) {
1461 context_->GetDiagnostics()->Error(DiagMessage(src)
1462 << "failed to open file: " << input_stream->GetError());
1463 return false;
1464 }
1465
1466 ContainerReaderEntry* entry;
1467 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001468
1469 if (reader.HadError()) {
1470 context_->GetDiagnostics()->Error(DiagMessage(src)
1471 << "failed to read file: " << reader.GetError());
1472 return false;
1473 }
1474
Adam Lesinski00451162017-10-03 07:44:08 -07001475 while ((entry = reader.Next()) != nullptr) {
1476 if (entry->Type() == ContainerEntryType::kResTable) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001477 TRACE_NAME(std::string("Process ResTable:") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001478 pb::ResourceTable pb_table;
1479 if (!entry->GetResTable(&pb_table)) {
1480 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1481 << entry->GetError());
1482 return false;
1483 }
1484
1485 ResourceTable table;
1486 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001487 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001488 context_->GetDiagnostics()->Error(DiagMessage(src)
1489 << "failed to deserialize resource table: " << error);
1490 return false;
1491 }
1492
1493 if (!table_merger_->Merge(src, &table, override)) {
1494 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1495 return false;
1496 }
1497 } else if (entry->Type() == ContainerEntryType::kResFile) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001498 TRACE_NAME(std::string("Process ResFile") + file->GetSource().path);
Adam Lesinski00451162017-10-03 07:44:08 -07001499 pb::internal::CompiledFile pb_compiled_file;
1500 off64_t offset;
1501 size_t len;
1502 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1503 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1504 << entry->GetError());
1505 return false;
1506 }
1507
1508 ResourceFile resource_file;
1509 std::string error;
1510 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1511 context_->GetDiagnostics()->Error(DiagMessage(src)
1512 << "failed to read compiled header: " << error);
1513 return false;
1514 }
1515
1516 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1517 return false;
1518 }
1519 }
1520 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001521 return true;
1522 }
1523
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001524 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1525 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1526 for (const std::string& assets_dir : options_.assets_dirs) {
1527 Maybe<std::vector<std::string>> files =
1528 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1529 if (!files) {
1530 return false;
1531 }
1532
1533 for (const std::string& file : files.value()) {
1534 std::string full_key = "assets/" + file;
1535 std::string full_path = assets_dir;
1536 file::AppendPath(&full_path, file);
1537
1538 auto iter = merged_assets.find(full_key);
1539 if (iter == merged_assets.end()) {
1540 merged_assets.emplace(std::move(full_key),
1541 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1542 } else if (context_->IsVerbose()) {
1543 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1544 << "asset file overrides '" << full_path << "'");
1545 }
1546 }
1547 }
1548
1549 for (auto& entry : merged_assets) {
1550 uint32_t compression_flags = ArchiveEntry::kCompress;
1551 std::string extension = file::GetExtension(entry.first).to_string();
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001552
1553 if (options_.do_not_compress_anything
1554 || options_.extensions_to_not_compress.count(extension) > 0
1555 || (options_.regex_to_not_compress
1556 && std::regex_search(extension, options_.regex_to_not_compress.value()))) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001557 compression_flags = 0u;
1558 }
1559
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001560 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1561 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001562 return false;
1563 }
1564 }
1565 return true;
1566 }
1567
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001568 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1569 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001570 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1571 ResourceTable* table) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001572 TRACE_CALL();
Ryan Mitchell479fa392019-01-02 17:15:39 -08001573 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1574 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001575 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001576 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001577 if (!result) {
1578 return false;
1579 }
1580
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001581 ResourceFileFlattenerOptions file_flattener_options;
1582 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001583 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1584 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01001585 file_flattener_options.regex_to_not_compress = options_.regex_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001586 file_flattener_options.no_auto_version = options_.no_auto_version;
1587 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001588 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001589 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1590 file_flattener_options.update_proguard_spec =
1591 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001592 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001593
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001594 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001595
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001596 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001597 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001598 return false;
1599 }
1600
Adam Lesinski490595a2017-11-07 17:08:07 -08001601 // Hack to fix b/68820737.
1602 // We need to modify the ResourceTable's package name, but that should NOT affect
1603 // anything else being generated, which includes the Java classes.
1604 // If required, the package name is modifed before flattening, and then modified back
1605 // to its original name.
1606 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001607 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1608 // or higher] as invalid. In order to work around this limitation, we allow the use
1609 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1610 // definition of what a valid "split" package ID is to account for this.
1611 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1612 context_->GetPackageId() != kAppPackageId &&
1613 context_->GetPackageId() != kFrameworkPackageId)
1614 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1615 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001616 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1617 // The base APK is included, and this is a feature split. If the base package is
1618 // the same as this package, then we are building an old style Android Instant Apps feature
1619 // split and must apply this workaround to avoid requiring namespaces support.
1620 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1621 if (package_to_rewrite != nullptr) {
1622 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1623
1624 std::string new_package_name =
1625 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1626 app_info_.split_name.value_or_default("feature").c_str());
1627
1628 if (context_->IsVerbose()) {
1629 context_->GetDiagnostics()->Note(
1630 DiagMessage() << "rewriting resource package name for feature split to '"
1631 << new_package_name << "'");
1632 }
1633 package_to_rewrite->name = new_package_name;
1634 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001635 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001636
1637 bool success = FlattenTable(table, options_.output_format, writer);
1638
1639 if (package_to_rewrite != nullptr) {
1640 // Change the name back.
1641 package_to_rewrite->name = context_->GetCompilationPackage();
1642 if (package_to_rewrite->id) {
1643 table->included_packages_.erase(package_to_rewrite->id.value());
1644 }
1645 }
1646
1647 if (!success) {
1648 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1649 }
1650 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001651 }
1652
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001653 int Run(const std::vector<std::string>& input_files) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001654 TRACE_CALL();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001655 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001656 std::unique_ptr<xml::XmlResource> manifest_xml =
1657 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1658 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001659 return 1;
1660 }
1661
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001662 // First extract the Package name without modifying it (via --rename-manifest-package).
1663 if (Maybe<AppInfo> maybe_app_info =
1664 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001665 const AppInfo& app_info = maybe_app_info.value();
1666 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001667 }
1668
Adam Lesinskic6284372017-12-04 13:46:23 -08001669 // Now that the compilation package is set, load the dependencies. This will also extract
1670 // the Android framework's versionCode and versionName, if they exist.
1671 if (!LoadSymbolsFromIncludePaths()) {
1672 return 1;
1673 }
1674
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001675 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1676 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001677 return 1;
1678 }
1679
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001680 Maybe<AppInfo> maybe_app_info =
1681 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001682 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001683 return 1;
1684 }
1685
Adam Lesinski490595a2017-11-07 17:08:07 -08001686 app_info_ = maybe_app_info.value();
1687 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001688
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001689 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001690
1691 // Override the package ID when it is "android".
1692 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001693 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001694
1695 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001696 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001697 context_->GetDiagnostics()->Error(
1698 DiagMessage() << "package 'android' can only be built as a regular app");
1699 return 1;
1700 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001701 }
1702
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001703 TableMergerOptions table_merger_options;
1704 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001705 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001706 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001707
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001708 if (context_->IsVerbose()) {
1709 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001710 << StringPrintf("linking package '%s' using package ID %02x",
1711 context_->GetCompilationPackage().data(),
1712 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001713 }
1714
Adam Lesinski2427dce2017-11-30 15:10:28 -08001715 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1716 // in res/**/*.
1717 {
1718 XmlIdCollector collector;
1719 if (!collector.Consume(context_, manifest_xml.get())) {
1720 return false;
1721 }
1722
1723 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1724 return false;
1725 }
1726 }
1727
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001728 for (const std::string& input : input_files) {
1729 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001730 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001731 return 1;
1732 }
1733 }
1734
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001735 for (const std::string& input : options_.overlay_files) {
1736 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001737 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001738 return 1;
1739 }
1740 }
1741
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743 return 1;
1744 }
1745
Adam Lesinskib522f042017-04-21 16:57:59 -07001746 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001747 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001749 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001750 return 1;
1751 }
1752
1753 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001754 IdAssigner id_assigner(&options_.stable_id_map);
1755 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001756 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001757 return 1;
1758 }
1759
1760 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001761 if (options_.resource_id_map_path) {
1762 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001763 for (auto& type : package->types) {
1764 for (auto& entry : type->entries) {
1765 ResourceName name(package->name, type->type, entry->name);
1766 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001767 options_.stable_id_map[std::move(name)] =
1768 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001769 }
1770 }
1771 }
1772
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001773 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001774 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001775 return 1;
1776 }
1777 }
1778 } else {
1779 // Static libs are merged with other apps, and ID collisions are bad, so
1780 // verify that
1781 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001782 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001783 return 1;
1784 }
1785 }
1786
1787 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001788 context_->SetNameManglerPolicy(
1789 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001790
1791 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001792 context_->GetExternalSymbols()->PrependSource(
1793 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001794
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001795 // Workaround for pre-O runtime that would treat negative resource IDs
1796 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1797 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1798 // are just identifiers.
1799 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1800 if (context_->IsVerbose()) {
1801 context_->GetDiagnostics()->Note(DiagMessage()
1802 << "enabling pre-O feature split ID rewriting");
1803 }
1804 context_->GetExternalSymbols()->SetDelegate(
1805 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1806 }
1807
Adam Lesinski34a16872018-02-23 16:18:10 -08001808 // Before we process anything, remove the resources whose default values don't exist.
1809 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02001810 if (!options_.no_resource_removal) {
1811 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1812 context_->GetDiagnostics()->Error(DiagMessage()
1813 << "failed removing resources with no defaults");
1814 return 1;
1815 }
Adam Lesinski34a16872018-02-23 16:18:10 -08001816 }
1817
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001818 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001819 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001820 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001821 return 1;
1822 }
1823
Adam Lesinskib522f042017-04-21 16:57:59 -07001824 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001825 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001826 context_->GetDiagnostics()->Warn(DiagMessage()
1827 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001828 }
1829 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001830 ProductFilter product_filter(options_.products);
1831 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001832 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001833 return 1;
1834 }
1835 }
1836
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001837 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001838 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001839 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001840 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001841 return 1;
1842 }
1843 }
1844
Adam Lesinskib522f042017-04-21 16:57:59 -07001845 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001846 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001847 context_->GetDiagnostics()->Note(DiagMessage()
1848 << "collapsing resource versions for minimum SDK "
1849 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001850 }
1851
1852 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001853 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001854 return 1;
1855 }
1856 }
1857
Winson3c918b82019-01-25 14:25:37 -08001858 if (!options_.exclude_configs_.empty()) {
1859 std::vector<ConfigDescription> excluded_configs;
1860
1861 for (auto& config_string : options_.exclude_configs_) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08001862 TRACE_NAME("ConfigDescription::Parse");
Winson3c918b82019-01-25 14:25:37 -08001863 ConfigDescription config_description;
1864
1865 if (!ConfigDescription::Parse(config_string, &config_description)) {
1866 context_->GetDiagnostics()->Error(DiagMessage()
1867 << "failed to parse --excluded-configs "
1868 << config_string);
1869 return 1;
1870 }
1871
1872 excluded_configs.push_back(config_description);
1873 }
1874
1875 ResourceExcluder excluder(excluded_configs);
1876 if (!excluder.Consume(context_, &final_table_)) {
1877 context_->GetDiagnostics()->Error(DiagMessage() << "failed excluding configurations");
1878 return 1;
1879 }
1880 }
1881
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001882 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001883 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001885 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001886 return 1;
1887 }
1888 }
1889
Adam Koskidc21dea2017-07-21 10:55:27 -07001890 proguard::KeepSet proguard_keep_set =
1891 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001892 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001893
Adam Lesinskib522f042017-04-21 16:57:59 -07001894 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001895 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001896 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001897 context_->GetDiagnostics()->Warn(DiagMessage()
1898 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001899 }
1900 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001901 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1902 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07001903 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001904 options_.split_constraints =
1905 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001906
Todd Kennedy9fbdf892018-08-28 16:31:15 -07001907 if (origConstraintSize != options_.split_constraints.size()) {
1908 context_->GetDiagnostics()->Warn(DiagMessage()
1909 << "requested to split resources prior to min sdk of "
1910 << context_->GetMinSdkVersion());
1911 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001912 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001913 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001914 return 1;
1915 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001916 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001917
1918 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001919 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001920 auto split_constraints_iter = options_.split_constraints.begin();
1921 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001922 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001923 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1924 << "generating split with configurations '"
1925 << util::Joiner(split_constraints_iter->configs, ", ")
1926 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001927 }
1928
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001929 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001930 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001931 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001932 return 1;
1933 }
1934
1935 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001936 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001937 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001938
1939 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001941 context_->GetDiagnostics()->Error(DiagMessage()
1942 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001943 return 1;
1944 }
1945
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001946 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1947 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001948 return 1;
1949 }
1950
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001951 ++path_iter;
1952 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001953 }
1954 }
1955
1956 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001957 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001958 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001959 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001960 return 1;
1961 }
1962
1963 bool error = false;
1964 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001965 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001966 // (aka, which package the AndroidManifest.xml is coming from).
1967 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001968 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001969
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001970 XmlReferenceLinker manifest_linker;
1971 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1972 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001973 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001974 error = true;
1975 }
1976
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001977 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001978 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001979 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001980 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001981 }
1982
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001983 if (options_.generate_java_class_path) {
1984 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001985 error = true;
1986 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001987 }
1988
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001989 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001990 // PackageParser will fail if URIs are removed from
1991 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001992 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1993 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001994 error = true;
1995 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001996 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001997 } else {
1998 error = true;
1999 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002000 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002001
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002002 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002003 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002004 return 1;
2005 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08002006
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002007 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
2008 return 1;
2009 }
2010
2011 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002012 return 1;
2013 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08002014
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00002015 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07002016 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002017 return 1;
2018 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002019 }
2020
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08002021 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002022 return 1;
2023 }
2024
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002025 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
2026 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002027 return 1;
2028 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002029 return 0;
2030 }
2031
2032 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002033 LinkOptions options_;
2034 LinkContext* context_;
2035 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002036
Adam Lesinski490595a2017-11-07 17:08:07 -08002037 AppInfo app_info_;
2038
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002039 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002040
2041 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002042 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002043
Adam Lesinski8780eb62017-10-31 17:44:39 -07002044 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002045 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002046 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002047
Adam Lesinski8780eb62017-10-31 17:44:39 -07002048 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
2049 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2050
2051 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2052 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002053
2054 // The set of shared libraries being used, mapping their assigned package ID to package name.
2055 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002056
2057 // The package name of the base application, if it is included.
2058 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002059};
2060
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002061int LinkCommand::Action(const std::vector<std::string>& args) {
Fabien Sanglard2d34e762019-02-21 15:13:29 -08002062 TRACE_FLUSH(trace_folder_ ? trace_folder_.value() : "", "LinkCommand::Action");
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002063 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002065 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002066 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002067 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002068 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002069 const std::string path = arg.substr(1, arg.size() - 1);
2070 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002071 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2072 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002073 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002074 }
2075 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002076 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002077 }
2078 }
2079
2080 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002081 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002082 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002083 const std::string path = arg.substr(1, arg.size() - 1);
2084 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002085 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002086 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 return 1;
2088 }
2089 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002090 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002091 }
2092 }
2093
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002094 if (verbose_) {
2095 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002096 }
2097
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002098 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002099 context.GetDiagnostics()->Error(
2100 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002101 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002102 return 1;
2103 }
2104
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002105 // The default build type.
2106 context.SetPackageType(PackageType::kApp);
2107 context.SetPackageId(kAppPackageId);
2108
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002109 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002110 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002111 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002112 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002113 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002114 options_.output_format = OutputFormat::kProto;
2115 } else if (proto_format_) {
2116 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002117 }
2118
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002119 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002120 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002121 context.GetDiagnostics()->Error(
2122 DiagMessage() << "can't specify --package-id when not building a regular app");
2123 return 1;
2124 }
2125
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002126 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002127 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002128 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002129 << "' is not a valid integer");
2130 return 1;
2131 }
2132
2133 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002134 if (package_id_int > std::numeric_limits<uint8_t>::max()
2135 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002136 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002137 context.GetDiagnostics()->Error(
2138 DiagMessage() << StringPrintf(
2139 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2140 return 1;
2141 }
2142 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2143 }
2144
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002145 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002146 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002147 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002148 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002149 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002150 }
2151 }
2152
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002153 if (product_list_) {
2154 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002155 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002156 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002157 }
2158 }
2159 }
2160
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002161 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002162 if (!configs_.empty()) {
2163 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002164 if (filter == nullptr) {
2165 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002166 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002167 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002168 }
2169
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002170 if (preferred_density_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002171 Maybe<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002172 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002173 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002174 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002175 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002176 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002177 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002178
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002179 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002180 for (const std::string& split_arg : split_args_) {
2181 options_.split_paths.push_back({});
2182 options_.split_constraints.push_back({});
2183 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2184 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002185 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002186 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002187 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002188
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002189 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2190 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2191 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002192 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002193 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002194 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002195
Izabela Orlowska0faba5f2018-06-01 12:06:31 +01002196 if (no_compress_regex) {
2197 std::string regex = no_compress_regex.value();
2198 if (util::StartsWith(regex, "@")) {
2199 const std::string path = regex.substr(1, regex.size() -1);
2200 std::string error;
2201 if (!file::AppendSetArgsFromFile(path, &options_.extensions_to_not_compress, &error)) {
2202 context.GetDiagnostics()->Error(DiagMessage(path) << error);
2203 return 1;
2204 }
2205 } else {
2206 options_.regex_to_not_compress = GetRegularExpression(no_compress_regex.value());
2207 }
2208 }
2209
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002210 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002211 options_.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002212 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002213 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2214 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2215 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002216
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002217 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002218 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002219 options_.no_auto_version = true;
2220 options_.no_version_vectors = true;
2221 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002222 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002223
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002224 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002225 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002226}
2227
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002228} // namespace aapt