blob: e3ee206df8f9de5a5ebea31ca5898a0577c83322 [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 Lesinski1ab598f2015-08-14 14:26:04 -070041#include "flatten/Archive.h"
42#include "flatten/TableFlattener.h"
43#include "flatten/XmlFlattener.h"
Adam Lesinski06460ef2017-03-14 18:52:13 -070044#include "io/BigBufferInputStream.h"
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070045#include "io/FileInputStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080046#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070047#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080048#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070049#include "java/JavaClassGenerator.h"
50#include "java/ManifestClassGenerator.h"
51#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070052#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070053#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080054#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070055#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070056#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080057#include "optimize/ResourceDeduper.h"
58#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059#include "process/IResourceTableConsumer.h"
60#include "process/SymbolTable.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080061#include "proto/ProtoSerialize.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080062#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070063#include "unflatten/BinaryResourceParser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080065#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070067using ::aapt::io::FileInputStream;
68using ::android::StringPiece;
69using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070070
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071namespace aapt {
72
73struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070074 std::string output_path;
75 std::string manifest_path;
76 std::vector<std::string> include_paths;
77 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070078 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070079 bool output_to_directory = false;
80 bool auto_add_overlay = false;
Adam Lesinski36c73a52016-08-11 13:39:24 -070081
Adam Lesinskicacb28f2016-10-19 12:18:14 -070082 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070083 Maybe<std::string> generate_java_class_path;
84 Maybe<std::string> custom_java_package;
85 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070086 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070087 Maybe<std::string> generate_proguard_rules_path;
88 Maybe<std::string> generate_main_dex_proguard_rules_path;
89 bool generate_non_final_ids = false;
90 std::vector<std::string> javadoc_annotations;
91 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -070092
Adam Lesinskice5e56e2016-10-21 17:56:45 -070093 // Optimizations/features.
94 bool no_auto_version = false;
95 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +090096 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070097 bool no_resource_deduping = false;
98 bool no_xml_namespaces = false;
99 bool do_not_compress_anything = false;
100 std::unordered_set<std::string> extensions_to_not_compress;
101
102 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700103 bool no_static_lib_packages = false;
104
105 // AndroidManifest.xml massaging options.
106 ManifestFixerOptions manifest_fixer_options;
107
108 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700109 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700110
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800111 // Flattening options.
112 TableFlattenerOptions table_flattener_options;
113
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700114 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700115 TableSplitterOptions table_splitter_options;
116 std::vector<SplitConstraints> split_constraints;
117 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700118
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700119 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700120 std::unordered_map<ResourceName, ResourceId> stable_id_map;
121 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700122};
123
Adam Lesinski64587af2016-02-18 18:33:06 -0800124class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700125 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100126 LinkContext(IDiagnostics* diagnostics)
127 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700128 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700129
Adam Lesinskib522f042017-04-21 16:57:59 -0700130 PackageType GetPackageType() override {
131 return package_type_;
132 }
133
134 void SetPackageType(PackageType type) {
135 package_type_ = type;
136 }
137
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700138 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100139 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700140 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700141
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700142 NameMangler* GetNameMangler() override {
143 return &name_mangler_;
144 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700145
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700146 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
147 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700148 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800149
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700150 const std::string& GetCompilationPackage() override {
151 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700152 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700153
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700154 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800155 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700156 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800157
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700158 uint8_t GetPackageId() override {
159 return package_id_;
160 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700161
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700162 void SetPackageId(uint8_t id) {
163 package_id_ = id;
164 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800165
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700166 SymbolTable* GetExternalSymbols() override {
167 return &symbols_;
168 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800169
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700170 bool IsVerbose() override {
171 return verbose_;
172 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800173
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700174 void SetVerbose(bool val) {
175 verbose_ = val;
176 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800177
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700178 int GetMinSdkVersion() override {
179 return min_sdk_version_;
180 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700181
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700182 void SetMinSdkVersion(int minSdk) {
183 min_sdk_version_ = minSdk;
184 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700185
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700186 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700187 DISALLOW_COPY_AND_ASSIGN(LinkContext);
188
Adam Lesinskib522f042017-04-21 16:57:59 -0700189 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100190 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700191 NameMangler name_mangler_;
192 std::string compilation_package_;
193 uint8_t package_id_ = 0x0;
194 SymbolTable symbols_;
195 bool verbose_ = false;
196 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700197};
198
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700199// A custom delegate that generates compatible pre-O IDs for use with feature splits.
200// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
201// is interpreted as a negative number. Some verification was wrongly assuming negative values
202// were invalid.
203//
204// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
205// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
206// an overlap exists.
207class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
208 public:
209 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
210 }
211
212 virtual ~FeatureSplitSymbolTableDelegate() = default;
213
214 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
215 const ResourceName& name,
216 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
217 std::unique_ptr<SymbolTable::Symbol> symbol =
218 DefaultSymbolTableDelegate::FindByName(name, sources);
219 if (symbol == nullptr) {
220 return {};
221 }
222
223 // Check to see if this is an 'id' with the target package.
224 if (name.type == ResourceType::kId && symbol->id) {
225 ResourceId* id = &symbol->id.value();
226 if (id->package_id() > kAppPackageId) {
227 // Rewrite the resource ID to be compatible pre-O.
228 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
229
230 // Check that this doesn't overlap another resource.
231 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
232 // The ID overlaps, so log a message (since this is a weird failure) and fail.
233 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
234 << " for pre-O feature split support");
235 return {};
236 }
237
238 if (context_->IsVerbose()) {
239 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
240 << ") -> (" << rewritten_id << ")");
241 }
242
243 *id = rewritten_id;
244 }
245 }
246 return symbol;
247 }
248
249 private:
250 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
251
252 IAaptContext* context_;
253};
254
Adam Lesinskic744ae82017-05-17 19:28:38 -0700255static bool FlattenXml(IAaptContext* context, xml::XmlResource* xml_res, const StringPiece& path,
256 bool keep_raw_values, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700257 BigBuffer buffer(1024);
258 XmlFlattenerOptions options = {};
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700259 options.keep_raw_values = keep_raw_values;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700260 XmlFlattener flattener(&buffer, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700261 if (!flattener.Consume(context, xml_res)) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800262 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700263 }
264
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700265 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700266 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
267 << (keep_raw_values ? "true" : "false")
268 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700269 }
270
Adam Lesinski06460ef2017-03-14 18:52:13 -0700271 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700272 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
273 ArchiveEntry::kCompress, writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800274}
275
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700276static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
277 size_t len, IDiagnostics* diag) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700278 pb::ResourceTable pb_table;
279 if (!pb_table.ParseFromArray(data, len)) {
280 diag->Error(DiagMessage(source) << "invalid compiled table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700281 return {};
282 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800283
Adam Lesinski06460ef2017-03-14 18:52:13 -0700284 std::unique_ptr<ResourceTable> table = DeserializeTableFromPb(pb_table, source, diag);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700285 if (!table) {
286 return {};
287 }
288 return table;
Adam Lesinski355f2852016-02-13 20:26:45 -0800289}
290
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700291// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700292static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700293 FileInputStream fin(path);
294 if (fin.HadError()) {
295 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700296 return {};
297 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700298 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800299}
300
Adam Lesinski355f2852016-02-13 20:26:45 -0800301struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700302 bool no_auto_version = false;
303 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900304 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700305 bool no_xml_namespaces = false;
306 bool keep_raw_values = false;
307 bool do_not_compress_anything = false;
308 bool update_proguard_spec = false;
309 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800310};
311
Adam Lesinskic744ae82017-05-17 19:28:38 -0700312// A sampling of public framework resource IDs.
313struct R {
314 struct attr {
315 enum : uint32_t {
316 paddingLeft = 0x010100d6u,
317 paddingRight = 0x010100d8u,
318 paddingHorizontal = 0x0101053du,
319
320 paddingTop = 0x010100d7u,
321 paddingBottom = 0x010100d9u,
322 paddingVertical = 0x0101053eu,
323
324 layout_marginLeft = 0x010100f7u,
325 layout_marginRight = 0x010100f9u,
326 layout_marginHorizontal = 0x0101053bu,
327
328 layout_marginTop = 0x010100f8u,
329 layout_marginBottom = 0x010100fau,
330 layout_marginVertical = 0x0101053cu,
331 };
332 };
333};
334
Adam Lesinski355f2852016-02-13 20:26:45 -0800335class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700336 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700337 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700338 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800339
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700340 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800341
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700342 private:
343 struct FileOperation {
344 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700345
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700346 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700347 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700348
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700349 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700350 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700351
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700352 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700353 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700354
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700355 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700356 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700357 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800358
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700359 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800360
Adam Lesinskic744ae82017-05-17 19:28:38 -0700361 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
362 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800363
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700364 ResourceFileFlattenerOptions options_;
365 IAaptContext* context_;
366 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700367 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800368};
369
Adam Lesinskic744ae82017-05-17 19:28:38 -0700370ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
371 IAaptContext* context, proguard::KeepSet* keep_set)
372 : options_(options), context_(context), keep_set_(keep_set) {
373 SymbolTable* symm = context_->GetExternalSymbols();
374
375 // Build up the rules for degrading newer attributes to older ones.
376 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
377 // generated from the attribute definitions themselves (b/62028956).
378 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
379 std::vector<ReplacementAttr> replacements{
380 {"paddingLeft", R::attr::paddingLeft,
381 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
382 {"paddingRight", R::attr::paddingRight,
383 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
384 };
385 rules_[R::attr::paddingHorizontal] =
386 util::make_unique<DegradeToManyRule>(std::move(replacements));
387 }
388
389 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
390 std::vector<ReplacementAttr> replacements{
391 {"paddingTop", R::attr::paddingTop,
392 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
393 {"paddingBottom", R::attr::paddingBottom,
394 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
395 };
396 rules_[R::attr::paddingVertical] =
397 util::make_unique<DegradeToManyRule>(std::move(replacements));
398 }
399
400 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
401 std::vector<ReplacementAttr> replacements{
402 {"layout_marginLeft", R::attr::layout_marginLeft,
403 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
404 {"layout_marginRight", R::attr::layout_marginRight,
405 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
406 };
407 rules_[R::attr::layout_marginHorizontal] =
408 util::make_unique<DegradeToManyRule>(std::move(replacements));
409 }
410
411 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
412 std::vector<ReplacementAttr> replacements{
413 {"layout_marginTop", R::attr::layout_marginTop,
414 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
415 {"layout_marginBottom", R::attr::layout_marginBottom,
416 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
417 };
418 rules_[R::attr::layout_marginVertical] =
419 util::make_unique<DegradeToManyRule>(std::move(replacements));
420 }
421}
422
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700423uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
424 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700425 return 0;
426 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800427
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700428 for (const std::string& extension : options_.extensions_to_not_compress) {
429 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700430 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800431 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700432 }
433 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800434}
435
Adam Lesinskibb94f322017-07-12 07:41:55 -0700436static bool IsTransitionElement(const std::string& name) {
437 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
438 name == "changeImageTransform" || name == "changeTransform" ||
439 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
440 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
441 name == "transitionManager";
442}
443
444static bool IsVectorElement(const std::string& name) {
445 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
446 name == "objectAnimator";
447}
448
Adam Lesinskic744ae82017-05-17 19:28:38 -0700449template <typename T>
450std::vector<T> make_singleton_vec(T&& val) {
451 std::vector<T> vec;
452 vec.emplace_back(std::forward<T>(val));
453 return vec;
454}
455
456std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
457 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700458 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700459 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700460
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700461 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700462 context_->GetDiagnostics()->Note(DiagMessage()
463 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700464 }
465
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700466 XmlReferenceLinker xml_linker;
467 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700468 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700469 }
470
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700471 if (options_.update_proguard_spec && !proguard::CollectProguardRules(src, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700472 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700473 }
474
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700475 if (options_.no_xml_namespaces) {
476 XmlNamespaceRemover namespace_remover;
477 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700478 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800479 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700480 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800481
Adam Lesinskibb94f322017-07-12 07:41:55 -0700482 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700483 return make_singleton_vec(std::move(file_op->xml_to_flatten));
484 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700485
Adam Lesinskibb94f322017-07-12 07:41:55 -0700486 if (options_.no_version_vectors || options_.no_version_transitions) {
487 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700488 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700489 if (el && el->namespace_uri.empty()) {
490 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
491 (options_.no_version_transitions && IsTransitionElement(el->name))) {
492 return make_singleton_vec(std::move(file_op->xml_to_flatten));
493 }
494 }
495 }
496
Adam Lesinskic744ae82017-05-17 19:28:38 -0700497 const ConfigDescription& config = file_op->config;
498 ResourceEntry* entry = file_op->entry;
499
500 XmlCompatVersioner xml_compat_versioner(&rules_);
501 const util::Range<ApiVersion> api_range{config.sdkVersion,
502 FindNextApiVersionForConfig(entry, config)};
503 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800504}
505
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700506bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700507 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700508 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800509
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700510 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700511 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
512
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700513 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700514 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700515 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700516 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800517
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700518 // Populate the queue with all files in the ResourceTable.
519 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700520 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700521 // WARNING! Do not insert or remove any resources while executing in this scope. It will
522 // corrupt the iteration order.
523
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700524 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700525 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700526 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700527 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700528
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700529 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700530 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700531 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700532 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700533 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700534 }
535
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700536 FileOperation file_op;
537 file_op.entry = entry.get();
538 file_op.dst_path = *file_ref->path;
539 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700540 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700541
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700542 const StringPiece src_path = file->GetSource().path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700543 if (type->type != ResourceType::kRaw &&
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700544 (util::EndsWith(src_path, ".xml.flat") || util::EndsWith(src_path, ".xml"))) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700545 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700546 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700547 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700548 << "failed to open file");
549 return false;
550 }
551
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700552 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(),
553 context_->GetDiagnostics(), file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700554
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700555 if (!file_op.xml_to_flatten) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700556 return false;
557 }
558
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700559 file_op.xml_to_flatten->file.config = config_value->config;
560 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700561 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700562 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700563
564 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
565 // else we end up copying the string in the std::make_pair() method,
566 // then creating a StringPiece from the copy, which would cause us
567 // to end up referencing garbage in the map.
568 const StringPiece entry_name(entry->name);
569 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
570 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700571 }
572 }
573
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700574 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700575 for (auto& map_entry : config_sorted_files) {
576 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700577 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700578
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700579 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700580 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
581 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700582 if (versioned_docs.empty()) {
583 error = true;
584 continue;
585 }
586
Adam Lesinskic744ae82017-05-17 19:28:38 -0700587 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
588 std::string dst_path = file_op.dst_path;
589 if (doc->file.config != file_op.config) {
590 // Only add the new versioned configurations.
591 if (context_->IsVerbose()) {
592 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
593 << "auto-versioning resource from config '"
594 << config << "' -> '" << doc->file.config << "'");
595 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700596
Adam Lesinskic744ae82017-05-17 19:28:38 -0700597 dst_path =
598 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
599 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
600 doc->file.source, dst_path, nullptr,
601 context_->GetDiagnostics());
602 if (!result) {
603 return false;
604 }
605 }
606 error |= !FlattenXml(context_, doc.get(), dst_path, options_.keep_raw_values,
607 archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608 }
609 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700610 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
611 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700612 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700613 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700614 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700615 }
616 return !error;
617}
618
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700619static bool WriteStableIdMapToPath(IDiagnostics* diag,
620 const std::unordered_map<ResourceName, ResourceId>& id_map,
621 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700622 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700623 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700624 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700625 return false;
626 }
627
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700628 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700629 const ResourceName& name = entry.first;
630 const ResourceId& id = entry.second;
631 fout << name << " = " << id << "\n";
632 }
633
634 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700635 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
636 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700637 return false;
638 }
639
640 return true;
641}
642
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700643static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
644 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700645 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700646 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700647 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648 return false;
649 }
650
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700651 out_id_map->clear();
652 size_t line_no = 0;
653 for (StringPiece line : util::Tokenize(content, '\n')) {
654 line_no++;
655 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700656 if (line.empty()) {
657 continue;
658 }
659
660 auto iter = std::find(line.begin(), line.end(), '=');
661 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700662 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700663 return false;
664 }
665
666 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700667 StringPiece res_name_str =
668 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
669 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700670 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
671 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700672 return false;
673 }
674
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700675 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
676 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700677 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700678
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700679 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
680 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700681 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
682 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700683 return false;
684 }
685
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700686 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700687 }
688 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700689}
690
Adam Lesinskifb48d292015-11-07 15:52:13 -0800691class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700692 public:
693 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700694 : options_(options),
695 context_(context),
696 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700697 file_collection_(util::make_unique<io::FileCollection>()) {
698 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700699
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 /**
701 * Creates a SymbolTable that loads symbols from the various APKs and caches
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700702 * the results for faster lookup.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700704 bool LoadSymbolsFromIncludePaths() {
705 std::unique_ptr<AssetManagerSymbolSource> asset_source =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700707 for (const std::string& path : options_.include_paths) {
708 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700709 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700710 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700711
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700712 // First try to load the file as a static lib.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700713 std::string error_str;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800714 std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
715 if (include_static) {
Adam Lesinskib522f042017-04-21 16:57:59 -0700716 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800717 // Can't include static libraries when not building a static library (they have no IDs
718 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700719 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800720 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700721 return false;
722 }
723
724 // If we are using --no-static-lib-packages, we need to rename the
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800725 // package of this table to our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700726 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800727 // Since package names can differ, and multiple packages can exist in a ResourceTable,
728 // we place the requirement that all static libraries are built with the package
729 // ID 0x7f. So if one is not found, this is an error.
730 if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700731 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800732 } else {
733 context_->GetDiagnostics()->Error(DiagMessage(path)
734 << "no package with ID 0x7f found in static library");
735 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736 }
737 }
738
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700739 context_->GetExternalSymbols()->AppendSource(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800740 util::make_unique<ResourceTableSymbolSource>(include_static.get()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700741
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800742 static_table_includes_.push_back(std::move(include_static));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700743
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700744 } else if (!error_str.empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700745 // We had an error with reading, so fail.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700746 context_->GetDiagnostics()->Error(DiagMessage(path) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700747 return false;
748 }
749
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700750 if (!asset_source->AddAssetPath(path)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800751 context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700752 return false;
753 }
754 }
755
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800756 // Capture the shared libraries so that the final resource table can be properly flattened
757 // with support for shared libraries.
758 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800759 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800760 final_table_.included_packages_[entry.first] = entry.second;
761 }
762 }
763
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700764 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700765 return true;
766 }
767
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800768 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700769 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800770 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
771 if (manifest_el == nullptr) {
772 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700773 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800774
775 AppInfo app_info;
776
777 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
778 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
779 return {};
780 }
781
782 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
783 if (!package_attr) {
784 diag->Error(DiagMessage(xml_res->file.source)
785 << "<manifest> must have a 'package' attribute");
786 return {};
787 }
788 app_info.package = package_attr->value;
789
790 if (xml::Attribute* version_code_attr =
791 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
792 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
793 if (!maybe_code) {
794 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
795 << "invalid android:versionCode '" << version_code_attr->value << "'");
796 return {};
797 }
798 app_info.version_code = maybe_code.value();
799 }
800
801 if (xml::Attribute* revision_code_attr =
802 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
803 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
804 if (!maybe_code) {
805 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
806 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
807 return {};
808 }
809 app_info.revision_code = maybe_code.value();
810 }
811
812 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
813 if (!split_name_attr->value.empty()) {
814 app_info.split_name = split_name_attr->value;
815 }
816 }
817
818 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
819 if (xml::Attribute* min_sdk =
820 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700821 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800822 }
823 }
824 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700825 }
826
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700827 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
828 // Postcondition: ResourceTable has only one package left. All others are
829 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700830 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700831 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700832 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
833 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700834 };
835
836 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700837 for (const auto& package : final_table_.packages) {
838 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700839 // We have a package that is not related to the one we're building!
840 for (const auto& type : package->types) {
841 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700842 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700843
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700844 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700845 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700846 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700847 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
848 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
849 << "generated id '" << res_name
850 << "' for external package '" << package->name
851 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700852 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700853 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
854 << "defined resource '" << res_name
855 << "' for external package '" << package->name
856 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700857 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700858 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700859 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700860 }
861 }
862 }
863 }
864
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700865 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
866 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700867 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700868 return !error;
869 }
870
871 /**
872 * Returns true if no IDs have been set, false otherwise.
873 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700874 bool VerifyNoIdsSet() {
875 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700876 for (const auto& type : package->types) {
877 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800878 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
879 << StringPrintf("%02x", type->id.value())
880 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700881 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700882 }
883
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700884 for (const auto& entry : type->entries) {
885 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700886 ResourceNameRef res_name(package->name, type->type, entry->name);
887 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800888 DiagMessage() << "entry " << res_name << " has ID "
889 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700890 return false;
891 }
892 }
893 }
894 }
895 return true;
896 }
897
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700898 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
899 if (options_.output_to_directory) {
900 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700901 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700902 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700903 }
904 }
905
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700906 bool FlattenTable(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700907 BigBuffer buffer(1024);
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800908 TableFlattener flattener(options_.table_flattener_options, &buffer);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700909 if (!flattener.Consume(context_, table)) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700910 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700911 return false;
912 }
913
Adam Lesinski06460ef2017-03-14 18:52:13 -0700914 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700915 return io::CopyInputStreamToArchive(context_, &input_stream, "resources.arsc",
916 ArchiveEntry::kAlign, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700917 }
918
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700919 bool FlattenTableToPb(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700920 std::unique_ptr<pb::ResourceTable> pb_table = SerializeTableToPb(table);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700921 return io::CopyProtoToArchive(context_, pb_table.get(), "resources.arsc.flat", 0, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700922 }
923
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700924 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700925 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700926 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700927 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700928 return true;
929 }
930
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700931 std::string out_path = options_.generate_java_class_path.value();
932 file::AppendPath(&out_path, file::PackageToPath(out_package));
933 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700934 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
935 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700936 return false;
937 }
938
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700939 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700940
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700941 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700942 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700943 context_->GetDiagnostics()->Error(DiagMessage()
944 << "failed writing to '" << out_path
945 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700946 return false;
947 }
948
Adam Lesinski418763f2017-04-11 17:36:53 -0700949 std::unique_ptr<std::ofstream> fout_text;
950 if (out_text_symbols_path) {
951 fout_text =
952 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
953 if (!*fout_text) {
954 context_->GetDiagnostics()->Error(
955 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
956 << "': " << android::base::SystemErrorCodeToString(errno));
957 return false;
958 }
959 }
960
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700961 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -0700962 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700963 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700964 return false;
965 }
966
967 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700968 context_->GetDiagnostics()->Error(DiagMessage()
969 << "failed writing to '" << out_path
970 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700971 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700972 }
973 return true;
974 }
975
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700976 bool GenerateJavaClasses() {
977 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
978 std::vector<std::string> packages_to_callback;
979
980 JavaClassGeneratorOptions template_options;
981 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
982 template_options.javadoc_annotations = options_.javadoc_annotations;
983
984 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
985 template_options.use_final = false;
986 }
987
988 if (context_->GetPackageType() == PackageType::kSharedLib) {
989 template_options.use_final = false;
990 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
991 }
992
993 const StringPiece actual_package = context_->GetCompilationPackage();
994 StringPiece output_package = context_->GetCompilationPackage();
995 if (options_.custom_java_package) {
996 // Override the output java package to the custom one.
997 output_package = options_.custom_java_package.value();
998 }
999
1000 // Generate the private symbols if required.
1001 if (options_.private_symbols) {
1002 packages_to_callback.push_back(options_.private_symbols.value());
1003
1004 // If we defined a private symbols package, we only emit Public symbols
1005 // to the original package, and private and public symbols to the private package.
1006 JavaClassGeneratorOptions options = template_options;
1007 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1008 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1009 options)) {
1010 return false;
1011 }
1012 }
1013
1014 // Generate copies of the original package R class but with different package names.
1015 // This is to support non-namespaced builds.
1016 for (const std::string& extra_package : options_.extra_java_packages) {
1017 packages_to_callback.push_back(extra_package);
1018
1019 JavaClassGeneratorOptions options = template_options;
1020 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1021 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1022 return false;
1023 }
1024 }
1025
1026 // Generate R classes for each package that was merged (static library).
1027 // Use the actual package's resources only.
1028 for (const std::string& package : table_merger_->merged_packages()) {
1029 packages_to_callback.push_back(package);
1030
1031 JavaClassGeneratorOptions options = template_options;
1032 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1033 if (!WriteJavaFile(&final_table_, package, package, options)) {
1034 return false;
1035 }
1036 }
1037
1038 // Generate the main public R class.
1039 JavaClassGeneratorOptions options = template_options;
1040
1041 // Only generate public symbols if we have a private package.
1042 if (options_.private_symbols) {
1043 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1044 }
1045
1046 if (options.rewrite_callback_options) {
1047 options.rewrite_callback_options.value().packages_to_callback =
1048 std::move(packages_to_callback);
1049 }
1050
1051 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1052 options_.generate_text_symbols_path)) {
1053 return false;
1054 }
1055
1056 return true;
1057 }
1058
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001059 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1060 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001061 return true;
1062 }
1063
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001064 std::unique_ptr<ClassDefinition> manifest_class =
1065 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001066
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001067 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001068 // Something bad happened, but we already logged it, so exit.
1069 return false;
1070 }
1071
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001072 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001073 // Empty Manifest class, no need to generate it.
1074 return true;
1075 }
1076
1077 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001078 for (const std::string& annotation : options_.javadoc_annotations) {
1079 std::string proper_annotation = "@";
1080 proper_annotation += annotation;
1081 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001082 }
1083
Adam Lesinski0d81f702017-06-27 15:51:09 -07001084 const std::string package_utf8 =
1085 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001086
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001087 std::string out_path = options_.generate_java_class_path.value();
1088 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001089
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001090 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001091 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1092 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001093 return false;
1094 }
1095
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001096 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001097
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001098 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001099 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001100 context_->GetDiagnostics()->Error(DiagMessage()
1101 << "failed writing to '" << out_path
1102 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001103 return false;
1104 }
1105
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001106 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1107 context_->GetDiagnostics()->Error(DiagMessage()
1108 << "failed writing to '" << out_path
1109 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001110 return false;
1111 }
1112 return true;
1113 }
1114
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001115 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001116 if (!out) {
1117 return true;
1118 }
1119
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001120 const std::string& out_path = out.value();
1121 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001122 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001123 context_->GetDiagnostics()->Error(DiagMessage()
1124 << "failed to open '" << out_path
1125 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001126 return false;
1127 }
1128
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001129 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001130 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001131 context_->GetDiagnostics()->Error(DiagMessage()
1132 << "failed writing to '" << out_path
1133 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001134 return false;
1135 }
1136 return true;
1137 }
1138
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001139 std::unique_ptr<ResourceTable> LoadStaticLibrary(const std::string& input,
1140 std::string* out_error) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001141 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001142 io::ZipFileCollection::Create(input, out_error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001143 if (!collection) {
1144 return {};
1145 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001146 return LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001147 }
1148
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001149 std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001150 io::IFile* file = collection->FindFile("resources.arsc.flat");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001151 if (!file) {
1152 return {};
1153 }
1154
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001155 std::unique_ptr<io::IData> data = file->OpenAsData();
1156 return LoadTableFromPb(file->GetSource(), data->data(), data->size(),
1157 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001158 }
1159
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001160 bool MergeStaticLibrary(const std::string& input, bool override) {
1161 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001162 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001163 }
1164
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001165 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001166 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001167 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001168 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001169 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001170 return false;
1171 }
1172
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001173 std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001174 if (!table) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001175 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001176 return false;
1177 }
1178
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001179 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001180 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001181 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001182 return false;
1183 }
1184
1185 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001186 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001187 // Merge all resources as if they were in the compilation package. This is the old behavior
1188 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001189
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001190 // Add the package to the set of --extra-packages so we emit an R.java for each library
1191 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001192 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001193 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001194 }
1195
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001196 // Clear the package name, so as to make the resources look like they are coming from the
1197 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001198 pkg->name = "";
1199 if (override) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001200 result = table_merger_->MergeOverlay(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001201 } else {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001202 result = table_merger_->Merge(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001203 }
1204
1205 } else {
1206 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001207 // preserved and resource names are mangled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001208 result =
1209 table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001210 }
1211
1212 if (!result) {
1213 return false;
1214 }
1215
1216 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001217 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 return true;
1219 }
1220
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001221 bool MergeResourceTable(io::IFile* file, bool override) {
1222 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001223 context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
1224 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001225 }
1226
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 if (!data) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001229 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001230 return false;
1231 }
1232
1233 std::unique_ptr<ResourceTable> table =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001234 LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235 if (!table) {
1236 return false;
1237 }
1238
1239 bool result = false;
1240 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001241 result = table_merger_->MergeOverlay(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001242 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001243 result = table_merger_->Merge(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001244 }
1245 return result;
1246 }
1247
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001248 bool MergeCompiledFile(io::IFile* file, ResourceFile* file_desc, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001249 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001250 context_->GetDiagnostics()->Note(DiagMessage() << "merging '" << file_desc->name
1251 << "' from compiled file "
1252 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253 }
1254
1255 bool result = false;
1256 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001257 result = table_merger_->MergeFileOverlay(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001258 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001259 result = table_merger_->MergeFile(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001260 }
1261
1262 if (!result) {
1263 return false;
1264 }
1265
1266 // Add the exports of this file to the table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001267 for (SourcedResourceName& exported_symbol : file_desc->exported_symbols) {
1268 if (exported_symbol.name.package.empty()) {
1269 exported_symbol.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001270 }
1271
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001272 ResourceNameRef res_name = exported_symbol.name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001273
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001274 Maybe<ResourceName> mangled_name =
1275 context_->GetNameMangler()->MangleName(exported_symbol.name);
1276 if (mangled_name) {
1277 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001278 }
1279
1280 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001281 id->SetSource(file_desc->source.WithLine(exported_symbol.line));
1282 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001283 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1284 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001285 if (!result) {
1286 return false;
1287 }
1288 }
1289 return true;
1290 }
1291
1292 /**
1293 * Takes a path to load as a ZIP file and merges the files within into the
1294 * master ResourceTable.
1295 * If override is true, conflicting resources are allowed to override each
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001296 * other, in order of last seen.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001297 *
1298 * An io::IFileCollection is created from the ZIP file and added to the set of
1299 * io::IFileCollections that are open.
1300 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001301 bool MergeArchive(const std::string& input, bool override) {
1302 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001303 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001304 }
1305
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001306 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001307 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001308 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001309 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001310 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001311 return false;
1312 }
1313
1314 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001315 for (auto iter = collection->Iterator(); iter->HasNext();) {
1316 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001317 error = true;
1318 }
1319 }
1320
1321 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001322 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001323 return !error;
1324 }
1325
1326 /**
1327 * Takes a path to load and merge into the master ResourceTable. If override
1328 * is true,
1329 * conflicting resources are allowed to override each other, in order of last
1330 * seen.
1331 *
1332 * If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1333 * as ZIP archive
1334 * and the files within are merged individually.
1335 *
1336 * Otherwise the files is processed on its own.
1337 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001338 bool MergePath(const std::string& path, bool override) {
1339 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1340 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1341 return MergeArchive(path, override);
1342 } else if (util::EndsWith(path, ".apk")) {
1343 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001344 }
1345
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001346 io::IFile* file = file_collection_->InsertFile(path);
1347 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001348 }
1349
1350 /**
1351 * Takes a file to load and merge into the master ResourceTable. If override
1352 * is true,
1353 * conflicting resources are allowed to override each other, in order of last
1354 * seen.
1355 *
1356 * If the file ends with .arsc.flat, then it is loaded as a ResourceTable and
1357 * merged into the
1358 * master ResourceTable. If the file ends with .flat, then it is treated like
1359 * a compiled file
1360 * and the header data is read and merged into the final ResourceTable.
1361 *
1362 * All other file types are ignored. This is because these files could be
1363 * coming from a zip,
1364 * where we could have other files like classes.dex.
1365 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001366 bool MergeFile(io::IFile* file, bool override) {
1367 const Source& src = file->GetSource();
1368 if (util::EndsWith(src.path, ".arsc.flat")) {
1369 return MergeResourceTable(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001370
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001371 } else if (util::EndsWith(src.path, ".flat")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001372 // Try opening the file and looking for an Export header.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001373 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001374 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001375 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001376 return false;
1377 }
1378
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001379 CompiledFileInputStream input_stream(data->data(), data->size());
1380 uint32_t num_files = 0;
1381 if (!input_stream.ReadLittleEndian32(&num_files)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001382 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed read num files");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001383 return false;
1384 }
1385
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001386 for (uint32_t i = 0; i < num_files; i++) {
Adam Lesinski4ffea042017-08-10 15:37:28 -07001387 pb::internal::CompiledFile compiled_file;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001388 if (!input_stream.ReadCompiledFile(&compiled_file)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001389 context_->GetDiagnostics()->Error(DiagMessage(src)
1390 << "failed to read compiled file header");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001391 return false;
Adam Lesinski467f1712015-11-16 17:35:44 -08001392 }
1393
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001394 uint64_t offset, len;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001395 if (!input_stream.ReadDataMetaData(&offset, &len)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001396 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read data meta data");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001397 return false;
1398 }
1399
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001400 std::unique_ptr<ResourceFile> resource_file = DeserializeCompiledFileFromPb(
1401 compiled_file, file->GetSource(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001402 if (!resource_file) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001403 return false;
1404 }
1405
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001406 if (!MergeCompiledFile(file->CreateFileSegment(offset, len), resource_file.get(),
1407 override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001408 return false;
1409 }
1410 }
1411 return true;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001412 } else if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001413 // Since AAPT compiles these file types and appends .flat to them, seeing
1414 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001415 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1416 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1417 << " file passed as argument. Must be "
1418 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001419 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001420 }
1421
1422 // Ignore non .flat files. This could be classes.dex or something else that
1423 // happens
1424 // to be in an archive.
1425 return true;
1426 }
1427
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001428 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1429 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1430 for (const std::string& assets_dir : options_.assets_dirs) {
1431 Maybe<std::vector<std::string>> files =
1432 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1433 if (!files) {
1434 return false;
1435 }
1436
1437 for (const std::string& file : files.value()) {
1438 std::string full_key = "assets/" + file;
1439 std::string full_path = assets_dir;
1440 file::AppendPath(&full_path, file);
1441
1442 auto iter = merged_assets.find(full_key);
1443 if (iter == merged_assets.end()) {
1444 merged_assets.emplace(std::move(full_key),
1445 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1446 } else if (context_->IsVerbose()) {
1447 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1448 << "asset file overrides '" << full_path << "'");
1449 }
1450 }
1451 }
1452
1453 for (auto& entry : merged_assets) {
1454 uint32_t compression_flags = ArchiveEntry::kCompress;
1455 std::string extension = file::GetExtension(entry.first).to_string();
1456 if (options_.extensions_to_not_compress.count(extension) > 0) {
1457 compression_flags = 0u;
1458 }
1459
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001460 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1461 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001462 return false;
1463 }
1464 }
1465 return true;
1466 }
1467
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001468 /**
1469 * Writes the AndroidManifest, ResourceTable, and all XML files referenced by
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001470 * the ResourceTable to the IArchiveWriter.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001471 */
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001472 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1473 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001474 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskic744ae82017-05-17 19:28:38 -07001475 bool result = FlattenXml(context_, manifest, "AndroidManifest.xml", keep_raw_values, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001476 if (!result) {
1477 return false;
1478 }
1479
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001480 ResourceFileFlattenerOptions file_flattener_options;
1481 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001482 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1483 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001484 file_flattener_options.no_auto_version = options_.no_auto_version;
1485 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001486 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001487 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1488 file_flattener_options.update_proguard_spec =
1489 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001490
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001491 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001492
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001493 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001494 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001495 return false;
1496 }
1497
Adam Lesinskib522f042017-04-21 16:57:59 -07001498 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001499 if (!FlattenTableToPb(table, writer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001500 return false;
1501 }
1502 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001503 if (!FlattenTable(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001504 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resources.arsc");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001505 return false;
1506 }
1507 }
1508 return true;
1509 }
1510
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001511 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001512 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001513 std::unique_ptr<xml::XmlResource> manifest_xml =
1514 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1515 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001516 return 1;
1517 }
1518
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001519 // First extract the Package name without modifying it (via --rename-manifest-package).
1520 if (Maybe<AppInfo> maybe_app_info =
1521 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001522 const AppInfo& app_info = maybe_app_info.value();
1523 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001524 }
1525
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001526 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1527 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001528 return 1;
1529 }
1530
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001531 Maybe<AppInfo> maybe_app_info =
1532 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001533 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001534 return 1;
1535 }
1536
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001537 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001538 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001539
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001540 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001541
1542 // Override the package ID when it is "android".
1543 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001544 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001545
1546 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001547 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001548 context_->GetDiagnostics()->Error(
1549 DiagMessage() << "package 'android' can only be built as a regular app");
1550 return 1;
1551 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001552 }
1553
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001554 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001555 return 1;
1556 }
1557
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001558 TableMergerOptions table_merger_options;
1559 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001560 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001561
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001562 if (context_->IsVerbose()) {
1563 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001564 << StringPrintf("linking package '%s' using package ID %02x",
1565 context_->GetCompilationPackage().data(),
1566 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001567 }
1568
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001569 for (const std::string& input : input_files) {
1570 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001571 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001572 return 1;
1573 }
1574 }
1575
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001576 for (const std::string& input : options_.overlay_files) {
1577 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001578 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001579 return 1;
1580 }
1581 }
1582
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001583 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001584 return 1;
1585 }
1586
Adam Lesinskib522f042017-04-21 16:57:59 -07001587 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001588 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001589 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001590 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001591 return 1;
1592 }
1593
1594 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001595 IdAssigner id_assigner(&options_.stable_id_map);
1596 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001597 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001598 return 1;
1599 }
1600
1601 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001602 if (options_.resource_id_map_path) {
1603 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001604 for (auto& type : package->types) {
1605 for (auto& entry : type->entries) {
1606 ResourceName name(package->name, type->type, entry->name);
1607 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001608 options_.stable_id_map[std::move(name)] =
1609 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001610 }
1611 }
1612 }
1613
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001614 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001615 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001616 return 1;
1617 }
1618 }
1619 } else {
1620 // Static libs are merged with other apps, and ID collisions are bad, so
1621 // verify that
1622 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001623 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001624 return 1;
1625 }
1626 }
1627
1628 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001629 context_->SetNameManglerPolicy(
1630 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001631
1632 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001633 context_->GetExternalSymbols()->PrependSource(
1634 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001635
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001636 // Workaround for pre-O runtime that would treat negative resource IDs
1637 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1638 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1639 // are just identifiers.
1640 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1641 if (context_->IsVerbose()) {
1642 context_->GetDiagnostics()->Note(DiagMessage()
1643 << "enabling pre-O feature split ID rewriting");
1644 }
1645 context_->GetExternalSymbols()->SetDelegate(
1646 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1647 }
1648
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001649 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001650 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001651 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001652 return 1;
1653 }
1654
Adam Lesinskib522f042017-04-21 16:57:59 -07001655 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001656 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001657 context_->GetDiagnostics()->Warn(DiagMessage()
1658 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001659 }
1660 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001661 ProductFilter product_filter(options_.products);
1662 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001663 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001664 return 1;
1665 }
1666 }
1667
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001668 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001669 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001670 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001671 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001672 return 1;
1673 }
1674 }
1675
Adam Lesinskib522f042017-04-21 16:57:59 -07001676 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001677 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001678 context_->GetDiagnostics()->Note(DiagMessage()
1679 << "collapsing resource versions for minimum SDK "
1680 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001681 }
1682
1683 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001684 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001685 return 1;
1686 }
1687 }
1688
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001689 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001690 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001691 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001692 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001693 return 1;
1694 }
1695 }
1696
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001697 proguard::KeepSet proguard_keep_set;
1698 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001699
Adam Lesinskib522f042017-04-21 16:57:59 -07001700 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001701 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001702 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001703 context_->GetDiagnostics()->Warn(DiagMessage()
1704 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001705 }
1706 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001707 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1708 // equal to the minSdk.
1709 options_.split_constraints =
1710 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001711
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001712 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001713 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001714 return 1;
1715 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001716 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001717
1718 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001719 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001720 auto split_constraints_iter = options_.split_constraints.begin();
1721 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001722 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001723 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1724 << "generating split with configurations '"
1725 << util::Joiner(split_constraints_iter->configs, ", ")
1726 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001727 }
1728
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001729 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001730 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001731 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001732 return 1;
1733 }
1734
1735 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001736 std::unique_ptr<xml::XmlResource> split_manifest =
1737 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001738
1739 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001740 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001741 context_->GetDiagnostics()->Error(DiagMessage()
1742 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743 return 1;
1744 }
1745
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001746 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1747 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001748 return 1;
1749 }
1750
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001751 ++path_iter;
1752 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001753 }
1754 }
1755
1756 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001757 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001758 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001759 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001760 return 1;
1761 }
1762
1763 bool error = false;
1764 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001765 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001766 // (aka, which package the AndroidManifest.xml is coming from).
1767 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001768 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001769
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001770 XmlReferenceLinker manifest_linker;
1771 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1772 if (options_.generate_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001773 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1774 manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001775 error = true;
1776 }
1777
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001778 if (options_.generate_main_dex_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001779 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1780 manifest_xml.get(),
1781 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001782 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001783 }
1784
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001785 if (options_.generate_java_class_path) {
1786 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001787 error = true;
1788 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001789 }
1790
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001791 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792 // PackageParser will fail if URIs are removed from
1793 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001794 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1795 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001796 error = true;
1797 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001798 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001799 } else {
1800 error = true;
1801 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001802 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001803
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001804 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001805 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001806 return 1;
1807 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001808
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001809 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1810 return 1;
1811 }
1812
1813 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001814 return 1;
1815 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001816
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001817 if (options_.generate_java_class_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001818 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001819 return 1;
1820 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001821 }
1822
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001823 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001824 return 1;
1825 }
1826
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001827 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1828 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 return 1;
1830 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001831 return 0;
1832 }
1833
1834 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001835 LinkOptions options_;
1836 LinkContext* context_;
1837 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001838
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001839 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001840
1841 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001842 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001843
1844 // A vector of IFileCollections. This is mainly here to keep ownership of the
1845 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001846 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001847
1848 // A vector of ResourceTables. This is here to retain ownership, so that the
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001849 // SymbolTable can use these.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001850 std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001851
1852 // The set of shared libraries being used, mapping their assigned package ID to package name.
1853 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001854};
1855
Chris Warrington820d72a2017-04-27 15:27:01 +01001856int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1857 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001858 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001859 std::vector<std::string> overlay_arg_list;
1860 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001861 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001862 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001863 Maybe<std::string> preferred_density;
1864 Maybe<std::string> product_list;
1865 bool legacy_x_flag = false;
1866 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001867 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001868 bool shared_lib = false;
1869 bool static_lib = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001870 Maybe<std::string> stable_id_file_path;
1871 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001872 Flags flags =
1873 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001874 .RequiredFlag("-o", "Output path.", &options.output_path)
1875 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001876 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001877 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001878 .OptionalFlagList("-A",
1879 "An assets directory to include in the APK. These are unprocessed.",
1880 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001881 .OptionalFlagList("-R",
1882 "Compilation unit to link, using `overlay` semantics.\n"
1883 "The last conflicting resource given takes precedence.",
1884 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001885 .OptionalFlag("--package-id",
1886 "Specify the package ID to use for this app. Must be greater or equal to\n"
1887 "0x7f and can't be used with --static-lib or --shared-lib.",
1888 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001889 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001890 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001891 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001892 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001893 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001894 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001895 &options.generate_main_dex_proguard_rules_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001896 .OptionalSwitch("--no-auto-version",
1897 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001898 &options.no_auto_version)
1899 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001900 "Disables automatic versioning of vector drawables. Use this only\n"
1901 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001902 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001903 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001904 "Disables automatic versioning of transition resources. Use this only\n"
1905 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001906 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001907 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001908 "Disables automatic deduping of resources with\n"
1909 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001910 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001911 .OptionalSwitch("--enable-sparse-encoding",
1912 "Enables encoding sparse entries using a binary search tree.\n"
1913 "This decreases APK size at the cost of resource retrieval performance.",
1914 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001915 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001916 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001917 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001919 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001920 "Comma separated list of configurations to include. The default\n"
1921 "is all configurations.",
1922 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001923 .OptionalFlag("--preferred-density",
1924 "Selects the closest matching density and strips out all others.",
1925 &preferred_density)
1926 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001927 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001928 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001929 &options.output_to_directory)
1930 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001931 "Removes XML namespace prefix and URI information from\n"
1932 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 &options.no_xml_namespaces)
1934 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001935 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001936 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001937 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001938 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001939 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001941 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1942 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001943 &options.manifest_fixer_options.version_code_default)
1944 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001945 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001946 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001947 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1948 &shared_lib)
1949 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001950 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001951 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001952 &options.no_static_lib_packages)
1953 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001954 "Generates R.java without the final modifier. This is implied when\n"
1955 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001956 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001957 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001958 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001959 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001960 "Emit a file at the given path with a list of name to ID mappings,\n"
1961 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001962 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001963 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001964 "Package name to use when generating R.java for private symbols.\n"
1965 "If not specified, public and private symbols will use the application's\n"
1966 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001967 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001968 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001969 &options.custom_java_package)
1970 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001971 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001972 &extra_java_packages)
1973 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001974 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001975 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001976 .OptionalFlag("--output-text-symbols",
1977 "Generates a text file containing the resource symbols of the R class in\n"
1978 "the specified folder.",
1979 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001980 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001981 "Allows the addition of new resources in overlays without\n"
1982 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001983 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001984 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001985 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001986 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001987 "Changes the name of the target package for instrumentation. Most useful\n"
1988 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001989 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001990 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001991 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001992 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001993 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07001994 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
1995 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001996 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001997 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001998
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001999 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002000 return 1;
2001 }
2002
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002003 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002004 std::vector<std::string> arg_list;
2005 for (const std::string& arg : flags.GetArgs()) {
2006 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002007 const std::string path = arg.substr(1, arg.size() - 1);
2008 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002009 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2010 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002011 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002012 }
2013 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002014 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002015 }
2016 }
2017
2018 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002019 for (const std::string& arg : overlay_arg_list) {
2020 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002021 const std::string path = arg.substr(1, arg.size() - 1);
2022 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002023 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2024 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002025 return 1;
2026 }
2027 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002028 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002029 }
2030 }
2031
2032 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002033 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002034 }
2035
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002036 if (shared_lib && static_lib) {
2037 context.GetDiagnostics()->Error(DiagMessage()
2038 << "only one of --shared-lib and --static-lib can be defined");
2039 return 1;
2040 }
2041
2042 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002043 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002044 context.SetPackageId(0x00);
2045 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002046 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002047 context.SetPackageId(kAppPackageId);
2048 } else {
Adam Lesinskib522f042017-04-21 16:57:59 -07002049 context.SetPackageType(PackageType::kApp);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002050 context.SetPackageId(kAppPackageId);
2051 }
2052
2053 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002054 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002055 context.GetDiagnostics()->Error(
2056 DiagMessage() << "can't specify --package-id when not building a regular app");
2057 return 1;
2058 }
2059
2060 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2061 if (!maybe_package_id_int) {
2062 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2063 << "' is not a valid integer");
2064 return 1;
2065 }
2066
2067 const uint32_t package_id_int = maybe_package_id_int.value();
2068 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2069 context.GetDiagnostics()->Error(
2070 DiagMessage() << StringPrintf(
2071 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2072 return 1;
2073 }
2074 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2075 }
2076
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002077 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002078 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002079 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002080 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002081 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002082 }
2083 }
2084
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002085 if (product_list) {
2086 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002087 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002088 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002089 }
2090 }
2091 }
2092
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002093 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002094 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002095 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2096 if (filter == nullptr) {
2097 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002098 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002099 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002100 }
2101
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002102 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002103 Maybe<uint16_t> density =
2104 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2105 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002106 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002107 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002108 options.table_splitter_options.preferred_densities.push_back(density.value());
2109 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002110
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002111 // Parse the split parameters.
2112 for (const std::string& split_arg : split_args) {
2113 options.split_paths.push_back({});
2114 options.split_constraints.push_back({});
2115 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2116 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002117 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002118 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002119 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002120
Adam Lesinskib522f042017-04-21 16:57:59 -07002121 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002122 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2123 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002124 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002125 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002126 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002127
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002128 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002129 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002130 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2131 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2132 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2133 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2134
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002135 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002136 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002137 options.no_auto_version = true;
2138 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002139 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002140 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002141
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002142 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002143 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002144}
2145
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002146} // namespace aapt