blob: 88e0f699fd580ebe9cbeb4775719adefb6c23fd5 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Adam Lesinskice5e56e2016-10-21 17:56:45 -070017#include <sys/stat.h>
18
19#include <fstream>
20#include <queue>
21#include <unordered_map>
22#include <vector>
23
24#include "android-base/errors.h"
25#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080026#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080027#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070028#include "google/protobuf/io/coded_stream.h"
29
Adam Lesinski1ab598f2015-08-14 14:26:04 -070030#include "AppInfo.h"
31#include "Debug.h"
32#include "Flags.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080033#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070034#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080035#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070036#include "ResourceValues.h"
37#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070038#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070039#include "compile/IdAssigner.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080040#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070041#include "format/Archive.h"
42#include "format/binary/BinaryResourceParser.h"
43#include "format/binary/TableFlattener.h"
44#include "format/binary/XmlFlattener.h"
45#include "format/proto/ProtoDeserialize.h"
46#include "format/proto/ProtoSerialize.h"
Adam Lesinski06460ef2017-03-14 18:52:13 -070047#include "io/BigBufferInputStream.h"
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070048#include "io/FileInputStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080049#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070050#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080051#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070052#include "java/JavaClassGenerator.h"
53#include "java/ManifestClassGenerator.h"
54#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070055#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070056#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080057#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070059#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080060#include "optimize/ResourceDeduper.h"
61#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062#include "process/IResourceTableConsumer.h"
63#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080064#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070065#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080066#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070068using ::aapt::io::FileInputStream;
69using ::android::StringPiece;
70using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070071
Adam Lesinski1ab598f2015-08-14 14:26:04 -070072namespace aapt {
73
74struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070075 std::string output_path;
76 std::string manifest_path;
77 std::vector<std::string> include_paths;
78 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070079 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070080 bool output_to_directory = false;
81 bool auto_add_overlay = false;
Adam Lesinski36c73a52016-08-11 13:39:24 -070082
Adam Lesinskicacb28f2016-10-19 12:18:14 -070083 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070084 Maybe<std::string> generate_java_class_path;
85 Maybe<std::string> custom_java_package;
86 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070087 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070088 Maybe<std::string> generate_proguard_rules_path;
89 Maybe<std::string> generate_main_dex_proguard_rules_path;
90 bool generate_non_final_ids = false;
91 std::vector<std::string> javadoc_annotations;
92 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -070093
Adam Lesinskice5e56e2016-10-21 17:56:45 -070094 // Optimizations/features.
95 bool no_auto_version = false;
96 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +090097 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070098 bool no_resource_deduping = false;
99 bool no_xml_namespaces = false;
100 bool do_not_compress_anything = false;
101 std::unordered_set<std::string> extensions_to_not_compress;
102
103 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700104 bool no_static_lib_packages = false;
105
106 // AndroidManifest.xml massaging options.
107 ManifestFixerOptions manifest_fixer_options;
108
109 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700110 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700111
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800112 // Flattening options.
113 TableFlattenerOptions table_flattener_options;
114
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700115 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700116 TableSplitterOptions table_splitter_options;
117 std::vector<SplitConstraints> split_constraints;
118 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700119
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700120 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700121 std::unordered_map<ResourceName, ResourceId> stable_id_map;
122 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700123};
124
Adam Lesinski64587af2016-02-18 18:33:06 -0800125class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700126 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100127 LinkContext(IDiagnostics* diagnostics)
128 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700129 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700130
Adam Lesinskib522f042017-04-21 16:57:59 -0700131 PackageType GetPackageType() override {
132 return package_type_;
133 }
134
135 void SetPackageType(PackageType type) {
136 package_type_ = type;
137 }
138
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700139 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100140 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700141 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700142
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700143 NameMangler* GetNameMangler() override {
144 return &name_mangler_;
145 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700146
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700147 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
148 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700149 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800150
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700151 const std::string& GetCompilationPackage() override {
152 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700153 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700154
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700155 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800156 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700157 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800158
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700159 uint8_t GetPackageId() override {
160 return package_id_;
161 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700162
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700163 void SetPackageId(uint8_t id) {
164 package_id_ = id;
165 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800166
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700167 SymbolTable* GetExternalSymbols() override {
168 return &symbols_;
169 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800170
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700171 bool IsVerbose() override {
172 return verbose_;
173 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800174
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700175 void SetVerbose(bool val) {
176 verbose_ = val;
177 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800178
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700179 int GetMinSdkVersion() override {
180 return min_sdk_version_;
181 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700182
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700183 void SetMinSdkVersion(int minSdk) {
184 min_sdk_version_ = minSdk;
185 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700186
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700187 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700188 DISALLOW_COPY_AND_ASSIGN(LinkContext);
189
Adam Lesinskib522f042017-04-21 16:57:59 -0700190 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100191 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700192 NameMangler name_mangler_;
193 std::string compilation_package_;
194 uint8_t package_id_ = 0x0;
195 SymbolTable symbols_;
196 bool verbose_ = false;
197 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700198};
199
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700200// A custom delegate that generates compatible pre-O IDs for use with feature splits.
201// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
202// is interpreted as a negative number. Some verification was wrongly assuming negative values
203// were invalid.
204//
205// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
206// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
207// an overlap exists.
208class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
209 public:
210 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
211 }
212
213 virtual ~FeatureSplitSymbolTableDelegate() = default;
214
215 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
216 const ResourceName& name,
217 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
218 std::unique_ptr<SymbolTable::Symbol> symbol =
219 DefaultSymbolTableDelegate::FindByName(name, sources);
220 if (symbol == nullptr) {
221 return {};
222 }
223
224 // Check to see if this is an 'id' with the target package.
225 if (name.type == ResourceType::kId && symbol->id) {
226 ResourceId* id = &symbol->id.value();
227 if (id->package_id() > kAppPackageId) {
228 // Rewrite the resource ID to be compatible pre-O.
229 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
230
231 // Check that this doesn't overlap another resource.
232 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
233 // The ID overlaps, so log a message (since this is a weird failure) and fail.
234 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
235 << " for pre-O feature split support");
236 return {};
237 }
238
239 if (context_->IsVerbose()) {
240 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
241 << ") -> (" << rewritten_id << ")");
242 }
243
244 *id = rewritten_id;
245 }
246 }
247 return symbol;
248 }
249
250 private:
251 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
252
253 IAaptContext* context_;
254};
255
Adam Lesinskic744ae82017-05-17 19:28:38 -0700256static bool FlattenXml(IAaptContext* context, xml::XmlResource* xml_res, const StringPiece& path,
257 bool keep_raw_values, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700258 BigBuffer buffer(1024);
259 XmlFlattenerOptions options = {};
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700260 options.keep_raw_values = keep_raw_values;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700261 XmlFlattener flattener(&buffer, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700262 if (!flattener.Consume(context, xml_res)) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800263 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700264 }
265
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700266 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700267 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
268 << (keep_raw_values ? "true" : "false")
269 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700270 }
271
Adam Lesinski06460ef2017-03-14 18:52:13 -0700272 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700273 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
274 ArchiveEntry::kCompress, writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800275}
276
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700277static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
278 size_t len, IDiagnostics* diag) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700279 pb::ResourceTable pb_table;
280 if (!pb_table.ParseFromArray(data, len)) {
281 diag->Error(DiagMessage(source) << "invalid compiled table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700282 return {};
283 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800284
Adam Lesinski8cdca1b2017-09-28 15:50:03 -0700285 std::unique_ptr<ResourceTable> table = util::make_unique<ResourceTable>();
286 std::string error;
287 if (!DeserializeTableFromPb(pb_table, table.get(), &error)) {
288 diag->Error(DiagMessage(source) << "invalid compiled table: " << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700289 return {};
290 }
291 return table;
Adam Lesinski355f2852016-02-13 20:26:45 -0800292}
293
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700294// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700295static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700296 FileInputStream fin(path);
297 if (fin.HadError()) {
298 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700299 return {};
300 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700301 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800302}
303
Adam Lesinski355f2852016-02-13 20:26:45 -0800304struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700305 bool no_auto_version = false;
306 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900307 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700308 bool no_xml_namespaces = false;
309 bool keep_raw_values = false;
310 bool do_not_compress_anything = false;
311 bool update_proguard_spec = false;
312 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800313};
314
Adam Lesinskic744ae82017-05-17 19:28:38 -0700315// A sampling of public framework resource IDs.
316struct R {
317 struct attr {
318 enum : uint32_t {
319 paddingLeft = 0x010100d6u,
320 paddingRight = 0x010100d8u,
321 paddingHorizontal = 0x0101053du,
322
323 paddingTop = 0x010100d7u,
324 paddingBottom = 0x010100d9u,
325 paddingVertical = 0x0101053eu,
326
327 layout_marginLeft = 0x010100f7u,
328 layout_marginRight = 0x010100f9u,
329 layout_marginHorizontal = 0x0101053bu,
330
331 layout_marginTop = 0x010100f8u,
332 layout_marginBottom = 0x010100fau,
333 layout_marginVertical = 0x0101053cu,
334 };
335 };
336};
337
Adam Lesinski355f2852016-02-13 20:26:45 -0800338class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700339 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700340 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700341 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800342
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700343 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800344
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700345 private:
346 struct FileOperation {
347 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700348
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700349 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700350 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700351
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700352 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700353 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700354
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700355 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700356 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700357
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700358 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700359 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700360 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800361
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700362 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800363
Adam Lesinskic744ae82017-05-17 19:28:38 -0700364 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
365 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800366
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700367 ResourceFileFlattenerOptions options_;
368 IAaptContext* context_;
369 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700370 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800371};
372
Adam Lesinskic744ae82017-05-17 19:28:38 -0700373ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
374 IAaptContext* context, proguard::KeepSet* keep_set)
375 : options_(options), context_(context), keep_set_(keep_set) {
376 SymbolTable* symm = context_->GetExternalSymbols();
377
378 // Build up the rules for degrading newer attributes to older ones.
379 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
380 // generated from the attribute definitions themselves (b/62028956).
381 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
382 std::vector<ReplacementAttr> replacements{
383 {"paddingLeft", R::attr::paddingLeft,
384 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
385 {"paddingRight", R::attr::paddingRight,
386 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
387 };
388 rules_[R::attr::paddingHorizontal] =
389 util::make_unique<DegradeToManyRule>(std::move(replacements));
390 }
391
392 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
393 std::vector<ReplacementAttr> replacements{
394 {"paddingTop", R::attr::paddingTop,
395 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
396 {"paddingBottom", R::attr::paddingBottom,
397 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
398 };
399 rules_[R::attr::paddingVertical] =
400 util::make_unique<DegradeToManyRule>(std::move(replacements));
401 }
402
403 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
404 std::vector<ReplacementAttr> replacements{
405 {"layout_marginLeft", R::attr::layout_marginLeft,
406 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
407 {"layout_marginRight", R::attr::layout_marginRight,
408 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
409 };
410 rules_[R::attr::layout_marginHorizontal] =
411 util::make_unique<DegradeToManyRule>(std::move(replacements));
412 }
413
414 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
415 std::vector<ReplacementAttr> replacements{
416 {"layout_marginTop", R::attr::layout_marginTop,
417 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
418 {"layout_marginBottom", R::attr::layout_marginBottom,
419 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
420 };
421 rules_[R::attr::layout_marginVertical] =
422 util::make_unique<DegradeToManyRule>(std::move(replacements));
423 }
424}
425
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700426uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
427 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700428 return 0;
429 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800430
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700431 for (const std::string& extension : options_.extensions_to_not_compress) {
432 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700433 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800434 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700435 }
436 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800437}
438
Adam Lesinskibb94f322017-07-12 07:41:55 -0700439static bool IsTransitionElement(const std::string& name) {
440 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
441 name == "changeImageTransform" || name == "changeTransform" ||
442 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
443 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
444 name == "transitionManager";
445}
446
447static bool IsVectorElement(const std::string& name) {
448 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
449 name == "objectAnimator";
450}
451
Adam Lesinskic744ae82017-05-17 19:28:38 -0700452template <typename T>
453std::vector<T> make_singleton_vec(T&& val) {
454 std::vector<T> vec;
455 vec.emplace_back(std::forward<T>(val));
456 return vec;
457}
458
459std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
460 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700461 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700462 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700463
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700464 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700465 context_->GetDiagnostics()->Note(DiagMessage()
466 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700467 }
468
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700469 XmlReferenceLinker xml_linker;
470 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700471 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700472 }
473
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700474 if (options_.update_proguard_spec && !proguard::CollectProguardRules(src, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700475 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700476 }
477
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700478 if (options_.no_xml_namespaces) {
479 XmlNamespaceRemover namespace_remover;
480 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700481 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800482 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700483 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800484
Adam Lesinskibb94f322017-07-12 07:41:55 -0700485 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700486 return make_singleton_vec(std::move(file_op->xml_to_flatten));
487 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700488
Adam Lesinskibb94f322017-07-12 07:41:55 -0700489 if (options_.no_version_vectors || options_.no_version_transitions) {
490 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700491 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700492 if (el && el->namespace_uri.empty()) {
493 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
494 (options_.no_version_transitions && IsTransitionElement(el->name))) {
495 return make_singleton_vec(std::move(file_op->xml_to_flatten));
496 }
497 }
498 }
499
Adam Lesinskic744ae82017-05-17 19:28:38 -0700500 const ConfigDescription& config = file_op->config;
501 ResourceEntry* entry = file_op->entry;
502
503 XmlCompatVersioner xml_compat_versioner(&rules_);
504 const util::Range<ApiVersion> api_range{config.sdkVersion,
505 FindNextApiVersionForConfig(entry, config)};
506 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800507}
508
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700509bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700510 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700511 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800512
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700513 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700514 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
515
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700516 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700517 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700518 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700519 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800520
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700521 // Populate the queue with all files in the ResourceTable.
522 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700523 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700524 // WARNING! Do not insert or remove any resources while executing in this scope. It will
525 // corrupt the iteration order.
526
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700527 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700528 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700529 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700530 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700531
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700532 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700533 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700534 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700535 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700536 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700537 }
538
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700539 FileOperation file_op;
540 file_op.entry = entry.get();
541 file_op.dst_path = *file_ref->path;
542 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700543 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700544
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700545 const StringPiece src_path = file->GetSource().path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700546 if (type->type != ResourceType::kRaw &&
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700547 (util::EndsWith(src_path, ".xml.flat") || util::EndsWith(src_path, ".xml"))) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700548 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700550 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 << "failed to open file");
552 return false;
553 }
554
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700555 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(),
556 context_->GetDiagnostics(), file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700558 if (!file_op.xml_to_flatten) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700559 return false;
560 }
561
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700562 file_op.xml_to_flatten->file.config = config_value->config;
563 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700564 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700566
567 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
568 // else we end up copying the string in the std::make_pair() method,
569 // then creating a StringPiece from the copy, which would cause us
570 // to end up referencing garbage in the map.
571 const StringPiece entry_name(entry->name);
572 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
573 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700574 }
575 }
576
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700577 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700578 for (auto& map_entry : config_sorted_files) {
579 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700580 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700581
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700582 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700583 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
584 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700585 if (versioned_docs.empty()) {
586 error = true;
587 continue;
588 }
589
Adam Lesinskic744ae82017-05-17 19:28:38 -0700590 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
591 std::string dst_path = file_op.dst_path;
592 if (doc->file.config != file_op.config) {
593 // Only add the new versioned configurations.
594 if (context_->IsVerbose()) {
595 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
596 << "auto-versioning resource from config '"
597 << config << "' -> '" << doc->file.config << "'");
598 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700599
Adam Lesinskic744ae82017-05-17 19:28:38 -0700600 dst_path =
601 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
602 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
603 doc->file.source, dst_path, nullptr,
604 context_->GetDiagnostics());
605 if (!result) {
606 return false;
607 }
608 }
609 error |= !FlattenXml(context_, doc.get(), dst_path, options_.keep_raw_values,
610 archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700611 }
612 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700613 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
614 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700615 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700617 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700618 }
619 return !error;
620}
621
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700622static bool WriteStableIdMapToPath(IDiagnostics* diag,
623 const std::unordered_map<ResourceName, ResourceId>& id_map,
624 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700625 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700626 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700627 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700628 return false;
629 }
630
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700631 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700632 const ResourceName& name = entry.first;
633 const ResourceId& id = entry.second;
634 fout << name << " = " << id << "\n";
635 }
636
637 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700638 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
639 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700640 return false;
641 }
642
643 return true;
644}
645
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700646static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
647 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700649 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700650 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700651 return false;
652 }
653
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700654 out_id_map->clear();
655 size_t line_no = 0;
656 for (StringPiece line : util::Tokenize(content, '\n')) {
657 line_no++;
658 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659 if (line.empty()) {
660 continue;
661 }
662
663 auto iter = std::find(line.begin(), line.end(), '=');
664 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700665 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700666 return false;
667 }
668
669 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700670 StringPiece res_name_str =
671 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
672 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700673 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
674 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700675 return false;
676 }
677
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700678 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
679 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700680 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700681
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700682 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
683 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700684 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
685 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700686 return false;
687 }
688
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700689 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700690 }
691 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700692}
693
Adam Lesinskifb48d292015-11-07 15:52:13 -0800694class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700695 public:
696 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700697 : options_(options),
698 context_(context),
699 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700700 file_collection_(util::make_unique<io::FileCollection>()) {
701 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700702
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 /**
704 * Creates a SymbolTable that loads symbols from the various APKs and caches
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700705 * the results for faster lookup.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700707 bool LoadSymbolsFromIncludePaths() {
708 std::unique_ptr<AssetManagerSymbolSource> asset_source =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700709 util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700710 for (const std::string& path : options_.include_paths) {
711 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700712 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700713 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700714
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700715 // First try to load the file as a static lib.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700716 std::string error_str;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800717 std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
718 if (include_static) {
Adam Lesinskib522f042017-04-21 16:57:59 -0700719 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800720 // Can't include static libraries when not building a static library (they have no IDs
721 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700722 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800723 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700724 return false;
725 }
726
727 // If we are using --no-static-lib-packages, we need to rename the
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800728 // package of this table to our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700729 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800730 // Since package names can differ, and multiple packages can exist in a ResourceTable,
731 // we place the requirement that all static libraries are built with the package
732 // ID 0x7f. So if one is not found, this is an error.
733 if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800735 } else {
736 context_->GetDiagnostics()->Error(DiagMessage(path)
737 << "no package with ID 0x7f found in static library");
738 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700739 }
740 }
741
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700742 context_->GetExternalSymbols()->AppendSource(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800743 util::make_unique<ResourceTableSymbolSource>(include_static.get()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700744
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800745 static_table_includes_.push_back(std::move(include_static));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700746
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700747 } else if (!error_str.empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700748 // We had an error with reading, so fail.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700749 context_->GetDiagnostics()->Error(DiagMessage(path) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700750 return false;
751 }
752
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700753 if (!asset_source->AddAssetPath(path)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800754 context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700755 return false;
756 }
757 }
758
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800759 // Capture the shared libraries so that the final resource table can be properly flattened
760 // with support for shared libraries.
761 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800762 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800763 final_table_.included_packages_[entry.first] = entry.second;
764 }
765 }
766
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700767 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700768 return true;
769 }
770
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800771 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700772 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800773 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
774 if (manifest_el == nullptr) {
775 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700776 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800777
778 AppInfo app_info;
779
780 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
781 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
782 return {};
783 }
784
785 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
786 if (!package_attr) {
787 diag->Error(DiagMessage(xml_res->file.source)
788 << "<manifest> must have a 'package' attribute");
789 return {};
790 }
791 app_info.package = package_attr->value;
792
793 if (xml::Attribute* version_code_attr =
794 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
795 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
796 if (!maybe_code) {
797 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
798 << "invalid android:versionCode '" << version_code_attr->value << "'");
799 return {};
800 }
801 app_info.version_code = maybe_code.value();
802 }
803
804 if (xml::Attribute* revision_code_attr =
805 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
806 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
807 if (!maybe_code) {
808 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
809 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
810 return {};
811 }
812 app_info.revision_code = maybe_code.value();
813 }
814
815 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
816 if (!split_name_attr->value.empty()) {
817 app_info.split_name = split_name_attr->value;
818 }
819 }
820
821 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
822 if (xml::Attribute* min_sdk =
823 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700824 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800825 }
826 }
827 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700828 }
829
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700830 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
831 // Postcondition: ResourceTable has only one package left. All others are
832 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700833 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700834 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700835 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
836 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700837 };
838
839 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700840 for (const auto& package : final_table_.packages) {
841 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700842 // We have a package that is not related to the one we're building!
843 for (const auto& type : package->types) {
844 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700845 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700846
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700847 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700848 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700849 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700850 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
851 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
852 << "generated id '" << res_name
853 << "' for external package '" << package->name
854 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700855 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700856 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
857 << "defined resource '" << res_name
858 << "' for external package '" << package->name
859 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700860 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700861 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700862 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700863 }
864 }
865 }
866 }
867
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700868 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
869 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700870 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700871 return !error;
872 }
873
874 /**
875 * Returns true if no IDs have been set, false otherwise.
876 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700877 bool VerifyNoIdsSet() {
878 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700879 for (const auto& type : package->types) {
880 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800881 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
882 << StringPrintf("%02x", type->id.value())
883 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700884 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700885 }
886
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700887 for (const auto& entry : type->entries) {
888 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700889 ResourceNameRef res_name(package->name, type->type, entry->name);
890 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800891 DiagMessage() << "entry " << res_name << " has ID "
892 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700893 return false;
894 }
895 }
896 }
897 }
898 return true;
899 }
900
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700901 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
902 if (options_.output_to_directory) {
903 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700904 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700905 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700906 }
907 }
908
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700909 bool FlattenTable(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700910 BigBuffer buffer(1024);
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800911 TableFlattener flattener(options_.table_flattener_options, &buffer);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700912 if (!flattener.Consume(context_, table)) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700913 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700914 return false;
915 }
916
Adam Lesinski06460ef2017-03-14 18:52:13 -0700917 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700918 return io::CopyInputStreamToArchive(context_, &input_stream, "resources.arsc",
919 ArchiveEntry::kAlign, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700920 }
921
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700922 bool FlattenTableToPb(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinski8cdca1b2017-09-28 15:50:03 -0700923 pb::ResourceTable pb_table;
924 SerializeTableToPb(*table, &pb_table);
925 return io::CopyProtoToArchive(context_, &pb_table, "resources.arsc.flat", 0, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700926 }
927
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700928 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700929 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700930 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700931 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700932 return true;
933 }
934
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700935 std::string out_path = options_.generate_java_class_path.value();
936 file::AppendPath(&out_path, file::PackageToPath(out_package));
937 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700938 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
939 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700940 return false;
941 }
942
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700943 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700944
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700945 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700946 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700947 context_->GetDiagnostics()->Error(DiagMessage()
948 << "failed writing to '" << out_path
949 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700950 return false;
951 }
952
Adam Lesinski418763f2017-04-11 17:36:53 -0700953 std::unique_ptr<std::ofstream> fout_text;
954 if (out_text_symbols_path) {
955 fout_text =
956 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
957 if (!*fout_text) {
958 context_->GetDiagnostics()->Error(
959 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
960 << "': " << android::base::SystemErrorCodeToString(errno));
961 return false;
962 }
963 }
964
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700965 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -0700966 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700967 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700968 return false;
969 }
970
971 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700972 context_->GetDiagnostics()->Error(DiagMessage()
973 << "failed writing to '" << out_path
974 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700975 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700976 }
977 return true;
978 }
979
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700980 bool GenerateJavaClasses() {
981 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
982 std::vector<std::string> packages_to_callback;
983
984 JavaClassGeneratorOptions template_options;
985 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
986 template_options.javadoc_annotations = options_.javadoc_annotations;
987
988 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
989 template_options.use_final = false;
990 }
991
992 if (context_->GetPackageType() == PackageType::kSharedLib) {
993 template_options.use_final = false;
994 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
995 }
996
997 const StringPiece actual_package = context_->GetCompilationPackage();
998 StringPiece output_package = context_->GetCompilationPackage();
999 if (options_.custom_java_package) {
1000 // Override the output java package to the custom one.
1001 output_package = options_.custom_java_package.value();
1002 }
1003
1004 // Generate the private symbols if required.
1005 if (options_.private_symbols) {
1006 packages_to_callback.push_back(options_.private_symbols.value());
1007
1008 // If we defined a private symbols package, we only emit Public symbols
1009 // to the original package, and private and public symbols to the private package.
1010 JavaClassGeneratorOptions options = template_options;
1011 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1012 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1013 options)) {
1014 return false;
1015 }
1016 }
1017
1018 // Generate copies of the original package R class but with different package names.
1019 // This is to support non-namespaced builds.
1020 for (const std::string& extra_package : options_.extra_java_packages) {
1021 packages_to_callback.push_back(extra_package);
1022
1023 JavaClassGeneratorOptions options = template_options;
1024 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1025 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1026 return false;
1027 }
1028 }
1029
1030 // Generate R classes for each package that was merged (static library).
1031 // Use the actual package's resources only.
1032 for (const std::string& package : table_merger_->merged_packages()) {
1033 packages_to_callback.push_back(package);
1034
1035 JavaClassGeneratorOptions options = template_options;
1036 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1037 if (!WriteJavaFile(&final_table_, package, package, options)) {
1038 return false;
1039 }
1040 }
1041
1042 // Generate the main public R class.
1043 JavaClassGeneratorOptions options = template_options;
1044
1045 // Only generate public symbols if we have a private package.
1046 if (options_.private_symbols) {
1047 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1048 }
1049
1050 if (options.rewrite_callback_options) {
1051 options.rewrite_callback_options.value().packages_to_callback =
1052 std::move(packages_to_callback);
1053 }
1054
1055 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1056 options_.generate_text_symbols_path)) {
1057 return false;
1058 }
1059
1060 return true;
1061 }
1062
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001063 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1064 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001065 return true;
1066 }
1067
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001068 std::unique_ptr<ClassDefinition> manifest_class =
1069 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001070
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001071 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001072 // Something bad happened, but we already logged it, so exit.
1073 return false;
1074 }
1075
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001076 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001077 // Empty Manifest class, no need to generate it.
1078 return true;
1079 }
1080
1081 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001082 for (const std::string& annotation : options_.javadoc_annotations) {
1083 std::string proper_annotation = "@";
1084 proper_annotation += annotation;
1085 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001086 }
1087
Adam Lesinski0d81f702017-06-27 15:51:09 -07001088 const std::string package_utf8 =
1089 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001090
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001091 std::string out_path = options_.generate_java_class_path.value();
1092 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001093
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001094 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001095 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1096 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001097 return false;
1098 }
1099
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001100 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001101
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001102 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001103 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001104 context_->GetDiagnostics()->Error(DiagMessage()
1105 << "failed writing to '" << out_path
1106 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001107 return false;
1108 }
1109
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001110 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1111 context_->GetDiagnostics()->Error(DiagMessage()
1112 << "failed writing to '" << out_path
1113 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001114 return false;
1115 }
1116 return true;
1117 }
1118
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001119 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001120 if (!out) {
1121 return true;
1122 }
1123
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001124 const std::string& out_path = out.value();
1125 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001126 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001127 context_->GetDiagnostics()->Error(DiagMessage()
1128 << "failed to open '" << out_path
1129 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001130 return false;
1131 }
1132
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001133 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001134 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001135 context_->GetDiagnostics()->Error(DiagMessage()
1136 << "failed writing to '" << out_path
1137 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001138 return false;
1139 }
1140 return true;
1141 }
1142
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001143 std::unique_ptr<ResourceTable> LoadStaticLibrary(const std::string& input,
1144 std::string* out_error) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001145 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001146 io::ZipFileCollection::Create(input, out_error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001147 if (!collection) {
1148 return {};
1149 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001150 return LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001151 }
1152
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001153 std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001154 io::IFile* file = collection->FindFile("resources.arsc.flat");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001155 if (!file) {
1156 return {};
1157 }
1158
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001159 std::unique_ptr<io::IData> data = file->OpenAsData();
1160 return LoadTableFromPb(file->GetSource(), data->data(), data->size(),
1161 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001162 }
1163
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001164 bool MergeStaticLibrary(const std::string& input, bool override) {
1165 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001166 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001167 }
1168
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001169 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001170 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001171 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001172 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001173 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001174 return false;
1175 }
1176
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001177 std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001178 if (!table) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001179 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001180 return false;
1181 }
1182
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001183 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001184 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001185 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001186 return false;
1187 }
1188
1189 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001190 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001191 // Merge all resources as if they were in the compilation package. This is the old behavior
1192 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001193
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001194 // Add the package to the set of --extra-packages so we emit an R.java for each library
1195 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001196 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001197 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001198 }
1199
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001200 // Clear the package name, so as to make the resources look like they are coming from the
1201 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202 pkg->name = "";
1203 if (override) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001204 result = table_merger_->MergeOverlay(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001205 } else {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001206 result = table_merger_->Merge(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001207 }
1208
1209 } else {
1210 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001211 // preserved and resource names are mangled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001212 result =
1213 table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001214 }
1215
1216 if (!result) {
1217 return false;
1218 }
1219
1220 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001221 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001222 return true;
1223 }
1224
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001225 bool MergeResourceTable(io::IFile* file, bool override) {
1226 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001227 context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
1228 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001229 }
1230
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001231 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001232 if (!data) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001233 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001234 return false;
1235 }
1236
1237 std::unique_ptr<ResourceTable> table =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001238 LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001239 if (!table) {
1240 return false;
1241 }
1242
1243 bool result = false;
1244 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001245 result = table_merger_->MergeOverlay(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001246 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001247 result = table_merger_->Merge(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001248 }
1249 return result;
1250 }
1251
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001252 bool MergeCompiledFile(io::IFile* file, ResourceFile* file_desc, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001253 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001254 context_->GetDiagnostics()->Note(DiagMessage() << "merging '" << file_desc->name
1255 << "' from compiled file "
1256 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001257 }
1258
1259 bool result = false;
1260 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001261 result = table_merger_->MergeFileOverlay(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001262 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001263 result = table_merger_->MergeFile(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001264 }
1265
1266 if (!result) {
1267 return false;
1268 }
1269
1270 // Add the exports of this file to the table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001271 for (SourcedResourceName& exported_symbol : file_desc->exported_symbols) {
1272 if (exported_symbol.name.package.empty()) {
1273 exported_symbol.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001274 }
1275
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001276 ResourceNameRef res_name = exported_symbol.name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001277
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001278 Maybe<ResourceName> mangled_name =
1279 context_->GetNameMangler()->MangleName(exported_symbol.name);
1280 if (mangled_name) {
1281 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001282 }
1283
1284 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001285 id->SetSource(file_desc->source.WithLine(exported_symbol.line));
1286 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001287 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1288 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001289 if (!result) {
1290 return false;
1291 }
1292 }
1293 return true;
1294 }
1295
1296 /**
1297 * Takes a path to load as a ZIP file and merges the files within into the
1298 * master ResourceTable.
1299 * If override is true, conflicting resources are allowed to override each
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001300 * other, in order of last seen.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001301 *
1302 * An io::IFileCollection is created from the ZIP file and added to the set of
1303 * io::IFileCollections that are open.
1304 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001305 bool MergeArchive(const std::string& input, bool override) {
1306 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001307 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001308 }
1309
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001310 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001311 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001312 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001313 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001314 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001315 return false;
1316 }
1317
1318 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001319 for (auto iter = collection->Iterator(); iter->HasNext();) {
1320 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001321 error = true;
1322 }
1323 }
1324
1325 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001326 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001327 return !error;
1328 }
1329
1330 /**
1331 * Takes a path to load and merge into the master ResourceTable. If override
1332 * is true,
1333 * conflicting resources are allowed to override each other, in order of last
1334 * seen.
1335 *
1336 * If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1337 * as ZIP archive
1338 * and the files within are merged individually.
1339 *
1340 * Otherwise the files is processed on its own.
1341 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001342 bool MergePath(const std::string& path, bool override) {
1343 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1344 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1345 return MergeArchive(path, override);
1346 } else if (util::EndsWith(path, ".apk")) {
1347 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001348 }
1349
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001350 io::IFile* file = file_collection_->InsertFile(path);
1351 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001352 }
1353
1354 /**
1355 * Takes a file to load and merge into the master ResourceTable. If override
1356 * is true,
1357 * conflicting resources are allowed to override each other, in order of last
1358 * seen.
1359 *
1360 * If the file ends with .arsc.flat, then it is loaded as a ResourceTable and
1361 * merged into the
1362 * master ResourceTable. If the file ends with .flat, then it is treated like
1363 * a compiled file
1364 * and the header data is read and merged into the final ResourceTable.
1365 *
1366 * All other file types are ignored. This is because these files could be
1367 * coming from a zip,
1368 * where we could have other files like classes.dex.
1369 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001370 bool MergeFile(io::IFile* file, bool override) {
1371 const Source& src = file->GetSource();
1372 if (util::EndsWith(src.path, ".arsc.flat")) {
1373 return MergeResourceTable(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001374
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001375 } else if (util::EndsWith(src.path, ".flat")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001376 // Try opening the file and looking for an Export header.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001377 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001378 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001379 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001380 return false;
1381 }
1382
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001383 CompiledFileInputStream input_stream(data->data(), data->size());
1384 uint32_t num_files = 0;
1385 if (!input_stream.ReadLittleEndian32(&num_files)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001386 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed read num files");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001387 return false;
1388 }
1389
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001390 for (uint32_t i = 0; i < num_files; i++) {
Adam Lesinski4ffea042017-08-10 15:37:28 -07001391 pb::internal::CompiledFile compiled_file;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001392 if (!input_stream.ReadCompiledFile(&compiled_file)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001393 context_->GetDiagnostics()->Error(DiagMessage(src)
1394 << "failed to read compiled file header");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001395 return false;
Adam Lesinski467f1712015-11-16 17:35:44 -08001396 }
1397
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001398 uint64_t offset, len;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001399 if (!input_stream.ReadDataMetaData(&offset, &len)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001400 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read data meta data");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001401 return false;
1402 }
1403
Adam Lesinski8cdca1b2017-09-28 15:50:03 -07001404 ResourceFile resource_file;
1405 std::string error;
1406 if (!DeserializeCompiledFileFromPb(compiled_file, &resource_file, &error)) {
1407 context_->GetDiagnostics()->Error(DiagMessage(src)
1408 << "failed to read compiled header: " << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001409 return false;
1410 }
1411
Adam Lesinski8cdca1b2017-09-28 15:50:03 -07001412 if (!MergeCompiledFile(file->CreateFileSegment(offset, len), &resource_file, override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001413 return false;
1414 }
1415 }
1416 return true;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001417 } else if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001418 // Since AAPT compiles these file types and appends .flat to them, seeing
1419 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001420 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1421 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1422 << " file passed as argument. Must be "
1423 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001424 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001425 }
1426
1427 // Ignore non .flat files. This could be classes.dex or something else that
1428 // happens
1429 // to be in an archive.
1430 return true;
1431 }
1432
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001433 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1434 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1435 for (const std::string& assets_dir : options_.assets_dirs) {
1436 Maybe<std::vector<std::string>> files =
1437 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1438 if (!files) {
1439 return false;
1440 }
1441
1442 for (const std::string& file : files.value()) {
1443 std::string full_key = "assets/" + file;
1444 std::string full_path = assets_dir;
1445 file::AppendPath(&full_path, file);
1446
1447 auto iter = merged_assets.find(full_key);
1448 if (iter == merged_assets.end()) {
1449 merged_assets.emplace(std::move(full_key),
1450 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1451 } else if (context_->IsVerbose()) {
1452 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1453 << "asset file overrides '" << full_path << "'");
1454 }
1455 }
1456 }
1457
1458 for (auto& entry : merged_assets) {
1459 uint32_t compression_flags = ArchiveEntry::kCompress;
1460 std::string extension = file::GetExtension(entry.first).to_string();
1461 if (options_.extensions_to_not_compress.count(extension) > 0) {
1462 compression_flags = 0u;
1463 }
1464
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001465 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1466 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001467 return false;
1468 }
1469 }
1470 return true;
1471 }
1472
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001473 /**
1474 * Writes the AndroidManifest, ResourceTable, and all XML files referenced by
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001475 * the ResourceTable to the IArchiveWriter.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001476 */
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001477 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1478 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001479 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskic744ae82017-05-17 19:28:38 -07001480 bool result = FlattenXml(context_, manifest, "AndroidManifest.xml", keep_raw_values, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001481 if (!result) {
1482 return false;
1483 }
1484
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001485 ResourceFileFlattenerOptions file_flattener_options;
1486 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001487 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1488 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001489 file_flattener_options.no_auto_version = options_.no_auto_version;
1490 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001491 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001492 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1493 file_flattener_options.update_proguard_spec =
1494 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001495
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001496 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001497
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001498 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001499 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001500 return false;
1501 }
1502
Adam Lesinskib522f042017-04-21 16:57:59 -07001503 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001504 if (!FlattenTableToPb(table, writer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001505 return false;
1506 }
1507 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001508 if (!FlattenTable(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001509 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resources.arsc");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001510 return false;
1511 }
1512 }
1513 return true;
1514 }
1515
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001516 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001517 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001518 std::unique_ptr<xml::XmlResource> manifest_xml =
1519 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1520 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001521 return 1;
1522 }
1523
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001524 // First extract the Package name without modifying it (via --rename-manifest-package).
1525 if (Maybe<AppInfo> maybe_app_info =
1526 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001527 const AppInfo& app_info = maybe_app_info.value();
1528 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001529 }
1530
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001531 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1532 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001533 return 1;
1534 }
1535
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001536 Maybe<AppInfo> maybe_app_info =
1537 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001538 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001539 return 1;
1540 }
1541
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001542 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001543 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001544
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001545 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001546
1547 // Override the package ID when it is "android".
1548 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001549 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001550
1551 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001552 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001553 context_->GetDiagnostics()->Error(
1554 DiagMessage() << "package 'android' can only be built as a regular app");
1555 return 1;
1556 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001557 }
1558
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001559 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001560 return 1;
1561 }
1562
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001563 TableMergerOptions table_merger_options;
1564 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001565 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001566
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001567 if (context_->IsVerbose()) {
1568 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001569 << StringPrintf("linking package '%s' using package ID %02x",
1570 context_->GetCompilationPackage().data(),
1571 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001572 }
1573
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001574 for (const std::string& input : input_files) {
1575 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001576 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001577 return 1;
1578 }
1579 }
1580
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001581 for (const std::string& input : options_.overlay_files) {
1582 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001583 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001584 return 1;
1585 }
1586 }
1587
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001588 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001589 return 1;
1590 }
1591
Adam Lesinskib522f042017-04-21 16:57:59 -07001592 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001593 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001594 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001595 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001596 return 1;
1597 }
1598
1599 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001600 IdAssigner id_assigner(&options_.stable_id_map);
1601 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001602 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001603 return 1;
1604 }
1605
1606 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001607 if (options_.resource_id_map_path) {
1608 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001609 for (auto& type : package->types) {
1610 for (auto& entry : type->entries) {
1611 ResourceName name(package->name, type->type, entry->name);
1612 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001613 options_.stable_id_map[std::move(name)] =
1614 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001615 }
1616 }
1617 }
1618
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001619 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001620 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001621 return 1;
1622 }
1623 }
1624 } else {
1625 // Static libs are merged with other apps, and ID collisions are bad, so
1626 // verify that
1627 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001628 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001629 return 1;
1630 }
1631 }
1632
1633 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001634 context_->SetNameManglerPolicy(
1635 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001636
1637 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001638 context_->GetExternalSymbols()->PrependSource(
1639 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001640
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001641 // Workaround for pre-O runtime that would treat negative resource IDs
1642 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1643 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1644 // are just identifiers.
1645 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1646 if (context_->IsVerbose()) {
1647 context_->GetDiagnostics()->Note(DiagMessage()
1648 << "enabling pre-O feature split ID rewriting");
1649 }
1650 context_->GetExternalSymbols()->SetDelegate(
1651 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1652 }
1653
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001654 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001655 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001656 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001657 return 1;
1658 }
1659
Adam Lesinskib522f042017-04-21 16:57:59 -07001660 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001661 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001662 context_->GetDiagnostics()->Warn(DiagMessage()
1663 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001664 }
1665 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001666 ProductFilter product_filter(options_.products);
1667 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001668 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001669 return 1;
1670 }
1671 }
1672
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001673 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001674 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001675 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001676 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001677 return 1;
1678 }
1679 }
1680
Adam Lesinskib522f042017-04-21 16:57:59 -07001681 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001682 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001683 context_->GetDiagnostics()->Note(DiagMessage()
1684 << "collapsing resource versions for minimum SDK "
1685 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001686 }
1687
1688 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001689 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001690 return 1;
1691 }
1692 }
1693
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001694 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001695 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001696 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001697 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001698 return 1;
1699 }
1700 }
1701
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001702 proguard::KeepSet proguard_keep_set;
1703 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001704
Adam Lesinskib522f042017-04-21 16:57:59 -07001705 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001706 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001707 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001708 context_->GetDiagnostics()->Warn(DiagMessage()
1709 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001710 }
1711 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001712 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1713 // equal to the minSdk.
1714 options_.split_constraints =
1715 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001716
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001717 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001718 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001719 return 1;
1720 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001721 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001722
1723 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001724 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001725 auto split_constraints_iter = options_.split_constraints.begin();
1726 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001727 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001728 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1729 << "generating split with configurations '"
1730 << util::Joiner(split_constraints_iter->configs, ", ")
1731 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001732 }
1733
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001734 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001735 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001736 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001737 return 1;
1738 }
1739
1740 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001741 std::unique_ptr<xml::XmlResource> split_manifest =
1742 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743
1744 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001745 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001746 context_->GetDiagnostics()->Error(DiagMessage()
1747 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001748 return 1;
1749 }
1750
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001751 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1752 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001753 return 1;
1754 }
1755
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001756 ++path_iter;
1757 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001758 }
1759 }
1760
1761 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001762 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001763 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001764 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001765 return 1;
1766 }
1767
1768 bool error = false;
1769 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001770 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001771 // (aka, which package the AndroidManifest.xml is coming from).
1772 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001773 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001774
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001775 XmlReferenceLinker manifest_linker;
1776 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1777 if (options_.generate_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001778 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1779 manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001780 error = true;
1781 }
1782
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001783 if (options_.generate_main_dex_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001784 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1785 manifest_xml.get(),
1786 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001787 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001788 }
1789
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001790 if (options_.generate_java_class_path) {
1791 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792 error = true;
1793 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001794 }
1795
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001796 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001797 // PackageParser will fail if URIs are removed from
1798 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001799 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1800 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001801 error = true;
1802 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001803 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001804 } else {
1805 error = true;
1806 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001807 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001808
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001809 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001810 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001811 return 1;
1812 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001813
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001814 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1815 return 1;
1816 }
1817
1818 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001819 return 1;
1820 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001821
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001822 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001823 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001824 return 1;
1825 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001826 }
1827
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001828 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 return 1;
1830 }
1831
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001832 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1833 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001834 return 1;
1835 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001836 return 0;
1837 }
1838
1839 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001840 LinkOptions options_;
1841 LinkContext* context_;
1842 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001843
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001844 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001845
1846 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001848
1849 // A vector of IFileCollections. This is mainly here to keep ownership of the
1850 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001851 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001852
1853 // A vector of ResourceTables. This is here to retain ownership, so that the
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001854 // SymbolTable can use these.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001855 std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001856
1857 // The set of shared libraries being used, mapping their assigned package ID to package name.
1858 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001859};
1860
Chris Warrington820d72a2017-04-27 15:27:01 +01001861int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1862 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001863 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001864 std::vector<std::string> overlay_arg_list;
1865 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001866 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001867 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001868 Maybe<std::string> preferred_density;
1869 Maybe<std::string> product_list;
1870 bool legacy_x_flag = false;
1871 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001872 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001873 bool shared_lib = false;
1874 bool static_lib = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001875 Maybe<std::string> stable_id_file_path;
1876 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001877 Flags flags =
1878 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001879 .RequiredFlag("-o", "Output path.", &options.output_path)
1880 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001881 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001882 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001883 .OptionalFlagList("-A",
1884 "An assets directory to include in the APK. These are unprocessed.",
1885 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001886 .OptionalFlagList("-R",
1887 "Compilation unit to link, using `overlay` semantics.\n"
1888 "The last conflicting resource given takes precedence.",
1889 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001890 .OptionalFlag("--package-id",
1891 "Specify the package ID to use for this app. Must be greater or equal to\n"
1892 "0x7f and can't be used with --static-lib or --shared-lib.",
1893 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001894 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001895 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001896 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001897 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001898 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001899 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001900 &options.generate_main_dex_proguard_rules_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001901 .OptionalSwitch("--no-auto-version",
1902 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001903 &options.no_auto_version)
1904 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 "Disables automatic versioning of vector drawables. Use this only\n"
1906 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001907 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001908 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001909 "Disables automatic versioning of transition resources. Use this only\n"
1910 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001911 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001912 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001913 "Disables automatic deduping of resources with\n"
1914 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001915 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001916 .OptionalSwitch("--enable-sparse-encoding",
1917 "Enables encoding sparse entries using a binary search tree.\n"
1918 "This decreases APK size at the cost of resource retrieval performance.",
1919 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001920 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001921 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001922 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001923 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001924 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001925 "Comma separated list of configurations to include. The default\n"
1926 "is all configurations.",
1927 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001928 .OptionalFlag("--preferred-density",
1929 "Selects the closest matching density and strips out all others.",
1930 &preferred_density)
1931 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001932 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001933 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001934 &options.output_to_directory)
1935 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001936 "Removes XML namespace prefix and URI information from\n"
1937 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001938 &options.no_xml_namespaces)
1939 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001940 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001941 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001942 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001943 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001944 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001945 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001946 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1947 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001948 &options.manifest_fixer_options.version_code_default)
1949 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001950 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001951 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001952 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1953 &shared_lib)
1954 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001955 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001956 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001957 &options.no_static_lib_packages)
1958 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001959 "Generates R.java without the final modifier. This is implied when\n"
1960 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001961 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001962 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001963 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001964 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001965 "Emit a file at the given path with a list of name to ID mappings,\n"
1966 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001967 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001968 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001969 "Package name to use when generating R.java for private symbols.\n"
1970 "If not specified, public and private symbols will use the application's\n"
1971 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001972 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001973 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001974 &options.custom_java_package)
1975 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001976 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001977 &extra_java_packages)
1978 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001979 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001980 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001981 .OptionalFlag("--output-text-symbols",
1982 "Generates a text file containing the resource symbols of the R class in\n"
1983 "the specified folder.",
1984 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001985 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001986 "Allows the addition of new resources in overlays without\n"
1987 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001988 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001989 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001990 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001991 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001992 "Changes the name of the target package for instrumentation. Most useful\n"
1993 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001994 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001995 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001997 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001998 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07001999 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2000 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002001 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002002 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002003
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002004 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002005 return 1;
2006 }
2007
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002008 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002009 std::vector<std::string> arg_list;
2010 for (const std::string& arg : flags.GetArgs()) {
2011 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002012 const std::string path = arg.substr(1, arg.size() - 1);
2013 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002014 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2015 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002016 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002017 }
2018 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002019 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002020 }
2021 }
2022
2023 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002024 for (const std::string& arg : overlay_arg_list) {
2025 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002026 const std::string path = arg.substr(1, arg.size() - 1);
2027 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002028 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2029 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002030 return 1;
2031 }
2032 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002033 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002034 }
2035 }
2036
2037 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002038 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002039 }
2040
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002041 if (shared_lib && static_lib) {
2042 context.GetDiagnostics()->Error(DiagMessage()
2043 << "only one of --shared-lib and --static-lib can be defined");
2044 return 1;
2045 }
2046
2047 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002048 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002049 context.SetPackageId(0x00);
2050 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002051 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002052 context.SetPackageId(kAppPackageId);
2053 } else {
Adam Lesinskib522f042017-04-21 16:57:59 -07002054 context.SetPackageType(PackageType::kApp);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002055 context.SetPackageId(kAppPackageId);
2056 }
2057
2058 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002059 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002060 context.GetDiagnostics()->Error(
2061 DiagMessage() << "can't specify --package-id when not building a regular app");
2062 return 1;
2063 }
2064
2065 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2066 if (!maybe_package_id_int) {
2067 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2068 << "' is not a valid integer");
2069 return 1;
2070 }
2071
2072 const uint32_t package_id_int = maybe_package_id_int.value();
2073 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2074 context.GetDiagnostics()->Error(
2075 DiagMessage() << StringPrintf(
2076 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2077 return 1;
2078 }
2079 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2080 }
2081
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002082 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002083 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002084 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002085 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002086 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 }
2088 }
2089
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002090 if (product_list) {
2091 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002092 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002093 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002094 }
2095 }
2096 }
2097
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002098 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002099 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002100 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2101 if (filter == nullptr) {
2102 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002103 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002104 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002105 }
2106
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002107 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002108 Maybe<uint16_t> density =
2109 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2110 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002111 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002112 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002113 options.table_splitter_options.preferred_densities.push_back(density.value());
2114 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002115
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002116 // Parse the split parameters.
2117 for (const std::string& split_arg : split_args) {
2118 options.split_paths.push_back({});
2119 options.split_constraints.push_back({});
2120 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2121 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002122 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002123 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002124 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002125
Adam Lesinskib522f042017-04-21 16:57:59 -07002126 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002127 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2128 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002129 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002130 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002131 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002132
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002133 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002134 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002135 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2136 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2137 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2138 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2139
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002141 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002142 options.no_auto_version = true;
2143 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002144 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002145 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002146
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002147 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002148 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002149}
2150
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002151} // namespace aapt