blob: b28415dc4a7619184dbb264810cd22123d5e5daa [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
17#include "AppInfo.h"
18#include "Debug.h"
19#include "Flags.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080020#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070021#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080022#include "ResourceUtils.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070023#include "compile/IdAssigner.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080024#include "filter/ConfigFilter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070025#include "flatten/Archive.h"
26#include "flatten/TableFlattener.h"
27#include "flatten/XmlFlattener.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080028#include "io/FileSystem.h"
29#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070030#include "java/JavaClassGenerator.h"
31#include "java/ManifestClassGenerator.h"
32#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070033#include "link/Linkers.h"
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -080034#include "link/ProductFilter.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080035#include "link/ReferenceLinker.h"
Adam Lesinski2ae4a872015-11-02 16:10:55 -080036#include "link/ManifestFixer.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070037#include "link/TableMerger.h"
38#include "process/IResourceTableConsumer.h"
39#include "process/SymbolTable.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080040#include "proto/ProtoSerialize.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080041#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070042#include "unflatten/BinaryResourceParser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070043#include "util/Files.h"
44#include "util/StringPiece.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080045#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070046
Adam Lesinski59e04c62016-02-04 15:59:23 -080047#include <google/protobuf/io/coded_stream.h>
48
Adam Lesinski1ab598f2015-08-14 14:26:04 -070049#include <fstream>
50#include <sys/stat.h>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070051#include <vector>
52
53namespace aapt {
54
55struct LinkOptions {
56 std::string outputPath;
57 std::string manifestPath;
58 std::vector<std::string> includePaths;
Adam Lesinskifb48d292015-11-07 15:52:13 -080059 std::vector<std::string> overlayFiles;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070060 Maybe<std::string> generateJavaClassPath;
Adam Lesinski52364f72016-01-11 13:10:24 -080061 Maybe<std::u16string> customJavaPackage;
62 std::set<std::u16string> extraJavaPackages;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070063 Maybe<std::string> generateProguardRulesPath;
64 bool noAutoVersion = false;
Adam Lesinski64587af2016-02-18 18:33:06 -080065 bool noVersionVectors = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066 bool staticLib = false;
Adam Lesinski64587af2016-02-18 18:33:06 -080067 bool noStaticLibPackages = false;
Adam Lesinskief9c5012016-01-22 14:09:53 -080068 bool generateNonFinalIds = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069 bool outputToDirectory = false;
Adam Lesinskia6fe3452015-12-09 15:20:52 -080070 bool autoAddOverlay = false;
Adam Lesinski52364f72016-01-11 13:10:24 -080071 bool doNotCompressAnything = false;
72 std::vector<std::string> extensionsToNotCompress;
Adam Lesinski9e10ac72015-10-16 14:37:48 -070073 Maybe<std::u16string> privateSymbols;
Adam Lesinski52364f72016-01-11 13:10:24 -080074 ManifestFixerOptions manifestFixerOptions;
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -080075 std::unordered_set<std::string> products;
Adam Lesinski355f2852016-02-13 20:26:45 -080076 TableSplitterOptions tableSplitterOptions;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070077};
78
Adam Lesinski64587af2016-02-18 18:33:06 -080079class LinkContext : public IAaptContext {
80public:
81 LinkContext() : mNameMangler({}) {
82 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070083
84 IDiagnostics* getDiagnostics() override {
85 return &mDiagnostics;
86 }
87
88 NameMangler* getNameMangler() override {
Adam Lesinski64587af2016-02-18 18:33:06 -080089 return &mNameMangler;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070090 }
91
Adam Lesinski64587af2016-02-18 18:33:06 -080092 void setNameManglerPolicy(const NameManglerPolicy& policy) {
93 mNameMangler = NameMangler(policy);
94 }
95
96 const std::u16string& getCompilationPackage() override {
Adam Lesinski1ab598f2015-08-14 14:26:04 -070097 return mCompilationPackage;
98 }
99
Adam Lesinski64587af2016-02-18 18:33:06 -0800100 void setCompilationPackage(const StringPiece16& packageName) {
101 mCompilationPackage = packageName.toString();
102 }
103
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700104 uint8_t getPackageId() override {
105 return mPackageId;
106 }
107
Adam Lesinski64587af2016-02-18 18:33:06 -0800108 void setPackageId(uint8_t id) {
109 mPackageId = id;
110 }
111
112 SymbolTable* getExternalSymbols() override {
113 return &mSymbols;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700114 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800115
116 bool verbose() override {
117 return mVerbose;
118 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800119
120 void setVerbose(bool val) {
121 mVerbose = val;
122 }
123
124private:
125 StdErrDiagnostics mDiagnostics;
126 NameMangler mNameMangler;
127 std::u16string mCompilationPackage;
128 uint8_t mPackageId = 0x0;
129 SymbolTable mSymbols;
130 bool mVerbose = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700131};
132
Adam Lesinski355f2852016-02-13 20:26:45 -0800133static bool copyFileToArchive(io::IFile* file, const std::string& outPath,
134 uint32_t compressionFlags,
135 IArchiveWriter* writer, IAaptContext* context) {
136 std::unique_ptr<io::IData> data = file->openAsData();
137 if (!data) {
138 context->getDiagnostics()->error(DiagMessage(file->getSource())
139 << "failed to open file");
140 return false;
141 }
142
Adam Lesinski64587af2016-02-18 18:33:06 -0800143 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data->data());
144 size_t bufferSize = data->size();
145
146 // If the file ends with .flat, we must strip off the CompiledFileHeader from it.
147 if (util::stringEndsWith<char>(file->getSource().path, ".flat")) {
148 CompiledFileInputStream inputStream(data->data(), data->size());
149 if (!inputStream.CompiledFile()) {
150 context->getDiagnostics()->error(DiagMessage(file->getSource())
151 << "invalid compiled file header");
152 return false;
153 }
154 buffer = reinterpret_cast<const uint8_t*>(inputStream.data());
155 bufferSize = inputStream.size();
Adam Lesinski355f2852016-02-13 20:26:45 -0800156 }
157
158 if (context->verbose()) {
159 context->getDiagnostics()->note(DiagMessage() << "writing " << outPath << " to archive");
160 }
161
162 if (writer->startEntry(outPath, compressionFlags)) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800163 if (writer->writeEntry(buffer, bufferSize)) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800164 if (writer->finishEntry()) {
165 return true;
166 }
167 }
168 }
169
170 context->getDiagnostics()->error(DiagMessage() << "failed to write file " << outPath);
171 return false;
172}
173
174static bool flattenXml(xml::XmlResource* xmlRes, const StringPiece& path, Maybe<size_t> maxSdkLevel,
175 bool keepRawValues, IArchiveWriter* writer, IAaptContext* context) {
176 BigBuffer buffer(1024);
177 XmlFlattenerOptions options = {};
178 options.keepRawValues = keepRawValues;
179 options.maxSdkLevel = maxSdkLevel;
180 XmlFlattener flattener(&buffer, options);
181 if (!flattener.consume(context, xmlRes)) {
182 return false;
183 }
184
185 if (context->verbose()) {
186 DiagMessage msg;
187 msg << "writing " << path << " to archive";
188 if (maxSdkLevel) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800189 msg << " maxSdkLevel=" << maxSdkLevel.value() << " keepRawValues=" << keepRawValues;
Adam Lesinski355f2852016-02-13 20:26:45 -0800190 }
191 context->getDiagnostics()->note(msg);
192 }
193
194 if (writer->startEntry(path, ArchiveEntry::kCompress)) {
195 if (writer->writeEntry(buffer)) {
196 if (writer->finishEntry()) {
197 return true;
198 }
199 }
200 }
201 context->getDiagnostics()->error(DiagMessage() << "failed to write " << path << " to archive");
202 return false;
203}
204
205/*static std::unique_ptr<ResourceTable> loadTable(const Source& source, const void* data, size_t len,
206 IDiagnostics* diag) {
207 std::unique_ptr<ResourceTable> table = util::make_unique<ResourceTable>();
208 BinaryResourceParser parser(diag, table.get(), source, data, len);
209 if (!parser.parse()) {
210 return {};
211 }
212 return table;
213}*/
214
215static std::unique_ptr<ResourceTable> loadTableFromPb(const Source& source,
216 const void* data, size_t len,
217 IDiagnostics* diag) {
218 pb::ResourceTable pbTable;
219 if (!pbTable.ParseFromArray(data, len)) {
220 diag->error(DiagMessage(source) << "invalid compiled table");
221 return {};
222 }
223
224 std::unique_ptr<ResourceTable> table = deserializeTableFromPb(pbTable, source, diag);
225 if (!table) {
226 return {};
227 }
228 return table;
229}
230
231/**
232 * Inflates an XML file from the source path.
233 */
234static std::unique_ptr<xml::XmlResource> loadXml(const std::string& path, IDiagnostics* diag) {
235 std::ifstream fin(path, std::ifstream::binary);
236 if (!fin) {
237 diag->error(DiagMessage(path) << strerror(errno));
238 return {};
239 }
240 return xml::inflate(&fin, diag, Source(path));
241}
242
243static std::unique_ptr<xml::XmlResource> loadBinaryXmlSkipFileExport(const Source& source,
244 const void* data, size_t len,
245 IDiagnostics* diag) {
246 CompiledFileInputStream inputStream(data, len);
247 if (!inputStream.CompiledFile()) {
248 diag->error(DiagMessage(source) << "invalid compiled file header");
249 return {};
250 }
251
252 const uint8_t* xmlData = reinterpret_cast<const uint8_t*>(inputStream.data());
253 const size_t xmlDataLen = inputStream.size();
254
255 std::unique_ptr<xml::XmlResource> xmlRes = xml::inflate(xmlData, xmlDataLen, diag, source);
256 if (!xmlRes) {
257 return {};
258 }
259 return xmlRes;
260}
261
262static std::unique_ptr<ResourceFile> loadFileExportHeader(const Source& source,
263 const void* data, size_t len,
264 IDiagnostics* diag) {
265 CompiledFileInputStream inputStream(data, len);
266 const pb::CompiledFile* pbFile = inputStream.CompiledFile();
267 if (!pbFile) {
268 diag->error(DiagMessage(source) << "invalid compiled file header");
269 return {};
270 }
271
272 std::unique_ptr<ResourceFile> resFile = deserializeCompiledFileFromPb(*pbFile, source, diag);
273 if (!resFile) {
274 return {};
275 }
276 return resFile;
277}
278
279struct ResourceFileFlattenerOptions {
280 bool noAutoVersion = false;
281 bool keepRawValues = false;
282 bool doNotCompressAnything = false;
283 std::vector<std::string> extensionsToNotCompress;
284};
285
286class ResourceFileFlattener {
287public:
288 ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
289 IAaptContext* context, proguard::KeepSet* keepSet) :
290 mOptions(options), mContext(context), mKeepSet(keepSet) {
291 }
292
293 bool flatten(ResourceTable* table, IArchiveWriter* archiveWriter);
294
295private:
296 struct FileOperation {
297 io::IFile* fileToCopy;
298 std::unique_ptr<xml::XmlResource> xmlToFlatten;
299 std::string dstPath;
300 };
301
302 uint32_t getCompressionFlags(const StringPiece& str);
303
304 std::unique_ptr<xml::XmlResource> linkAndVersionXmlFile(const ResourceEntry* entry,
305 const ResourceFile& fileDesc,
306 io::IFile* file,
307 ResourceTable* table);
308
309 ResourceFileFlattenerOptions mOptions;
310 IAaptContext* mContext;
311 proguard::KeepSet* mKeepSet;
312};
313
314uint32_t ResourceFileFlattener::getCompressionFlags(const StringPiece& str) {
315 if (mOptions.doNotCompressAnything) {
316 return 0;
317 }
318
319 for (const std::string& extension : mOptions.extensionsToNotCompress) {
320 if (util::stringEndsWith<char>(str, extension)) {
321 return 0;
322 }
323 }
324 return ArchiveEntry::kCompress;
325}
326
327std::unique_ptr<xml::XmlResource> ResourceFileFlattener::linkAndVersionXmlFile(
328 const ResourceEntry* entry,
329 const ResourceFile& fileDesc,
330 io::IFile* file,
331 ResourceTable* table) {
332 const StringPiece srcPath = file->getSource().path;
333 if (mContext->verbose()) {
334 mContext->getDiagnostics()->note(DiagMessage() << "linking " << srcPath);
335 }
336
337 std::unique_ptr<io::IData> data = file->openAsData();
338 if (!data) {
339 mContext->getDiagnostics()->error(DiagMessage(file->getSource()) << "failed to open file");
340 return {};
341 }
342
343 std::unique_ptr<xml::XmlResource> xmlRes;
344 if (util::stringEndsWith<char>(srcPath, ".flat")) {
345 xmlRes = loadBinaryXmlSkipFileExport(file->getSource(), data->data(), data->size(),
346 mContext->getDiagnostics());
347 } else {
348 xmlRes = xml::inflate(data->data(), data->size(), mContext->getDiagnostics(),
349 file->getSource());
350 }
351
352 if (!xmlRes) {
353 return {};
354 }
355
356 // Copy the the file description header.
357 xmlRes->file = fileDesc;
358
359 XmlReferenceLinker xmlLinker;
360 if (!xmlLinker.consume(mContext, xmlRes.get())) {
361 return {};
362 }
363
364 if (!proguard::collectProguardRules(xmlRes->file.source, xmlRes.get(), mKeepSet)) {
365 return {};
366 }
367
368 if (!mOptions.noAutoVersion) {
369 // Find the first SDK level used that is higher than this defined config and
370 // not superseded by a lower or equal SDK level resource.
371 for (int sdkLevel : xmlLinker.getSdkLevels()) {
372 if (sdkLevel > xmlRes->file.config.sdkVersion) {
373 if (!shouldGenerateVersionedResource(entry, xmlRes->file.config, sdkLevel)) {
374 // If we shouldn't generate a versioned resource, stop checking.
375 break;
376 }
377
378 ResourceFile versionedFileDesc = xmlRes->file;
Adam Lesinski64587af2016-02-18 18:33:06 -0800379 versionedFileDesc.config.sdkVersion = (uint16_t) sdkLevel;
Adam Lesinski355f2852016-02-13 20:26:45 -0800380
381 if (mContext->verbose()) {
382 mContext->getDiagnostics()->note(DiagMessage(versionedFileDesc.source)
383 << "auto-versioning resource from config '"
384 << xmlRes->file.config << "' -> '"
385 << versionedFileDesc.config << "'");
386 }
387
388 std::u16string genPath = util::utf8ToUtf16(ResourceUtils::buildResourceFileName(
389 versionedFileDesc, mContext->getNameMangler()));
390
391 bool added = table->addFileReferenceAllowMangled(versionedFileDesc.name,
392 versionedFileDesc.config,
393 versionedFileDesc.source,
394 genPath,
395 file,
396 mContext->getDiagnostics());
397 if (!added) {
398 return {};
399 }
400 break;
401 }
402 }
403 }
404 return xmlRes;
405}
406
407/**
408 * Do not insert or remove any resources while executing in this function. It will
409 * corrupt the iteration order.
410 */
411bool ResourceFileFlattener::flatten(ResourceTable* table, IArchiveWriter* archiveWriter) {
412 bool error = false;
413 std::map<std::pair<ConfigDescription, StringPiece16>, FileOperation> configSortedFiles;
414
415 for (auto& pkg : table->packages) {
416 for (auto& type : pkg->types) {
417 // Sort by config and name, so that we get better locality in the zip file.
418 configSortedFiles.clear();
419 for (auto& entry : type->entries) {
420 // Iterate via indices because auto generated values can be inserted ahead of
421 // the value being processed.
422 for (size_t i = 0; i < entry->values.size(); i++) {
423 ResourceConfigValue* configValue = entry->values[i].get();
424
425 FileReference* fileRef = valueCast<FileReference>(configValue->value.get());
426 if (!fileRef) {
427 continue;
428 }
429
430 io::IFile* file = fileRef->file;
431 if (!file) {
432 mContext->getDiagnostics()->error(DiagMessage(fileRef->getSource())
433 << "file not found");
434 return false;
435 }
436
437 FileOperation fileOp;
438 fileOp.dstPath = util::utf16ToUtf8(*fileRef->path);
439
440 const StringPiece srcPath = file->getSource().path;
441 if (type->type != ResourceType::kRaw &&
442 (util::stringEndsWith<char>(srcPath, ".xml.flat") ||
443 util::stringEndsWith<char>(srcPath, ".xml"))) {
444 ResourceFile fileDesc;
445 fileDesc.config = configValue->config;
446 fileDesc.name = ResourceName(pkg->name, type->type, entry->name);
447 fileDesc.source = fileRef->getSource();
448 fileOp.xmlToFlatten = linkAndVersionXmlFile(entry.get(), fileDesc,
449 file, table);
450 if (!fileOp.xmlToFlatten) {
451 error = true;
452 continue;
453 }
454
455 } else {
456 fileOp.fileToCopy = file;
457 }
458
459 // NOTE(adamlesinski): Explicitly construct a StringPiece16 here, or else
460 // we end up copying the string in the std::make_pair() method, then creating
461 // a StringPiece16 from the copy, which would cause us to end up referencing
462 // garbage in the map.
463 const StringPiece16 entryName(entry->name);
464 configSortedFiles[std::make_pair(configValue->config, entryName)] =
465 std::move(fileOp);
466 }
467 }
468
469 if (error) {
470 return false;
471 }
472
473 // Now flatten the sorted values.
474 for (auto& mapEntry : configSortedFiles) {
475 const ConfigDescription& config = mapEntry.first.first;
476 const FileOperation& fileOp = mapEntry.second;
477
478 if (fileOp.xmlToFlatten) {
479 Maybe<size_t> maxSdkLevel;
480 if (!mOptions.noAutoVersion) {
481 maxSdkLevel = std::max<size_t>(config.sdkVersion, 1u);
482 }
483
484 bool result = flattenXml(fileOp.xmlToFlatten.get(), fileOp.dstPath, maxSdkLevel,
485 mOptions.keepRawValues,
486 archiveWriter, mContext);
487 if (!result) {
488 error = true;
489 }
490 } else {
491 bool result = copyFileToArchive(fileOp.fileToCopy, fileOp.dstPath,
492 getCompressionFlags(fileOp.dstPath),
493 archiveWriter, mContext);
494 if (!result) {
495 error = true;
496 }
497 }
498 }
499 }
500 }
501 return !error;
502}
503
Adam Lesinskifb48d292015-11-07 15:52:13 -0800504class LinkCommand {
505public:
Adam Lesinski6a008172016-02-02 17:02:58 -0800506 LinkCommand(LinkContext* context, const LinkOptions& options) :
Adam Lesinski64587af2016-02-18 18:33:06 -0800507 mOptions(options), mContext(context), mFinalTable(),
508 mFileCollection(util::make_unique<io::FileCollection>()) {
Adam Lesinskifb48d292015-11-07 15:52:13 -0800509 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700510
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700511 /**
512 * Creates a SymbolTable that loads symbols from the various APKs and caches the
513 * results for faster lookup.
514 */
Adam Lesinski64587af2016-02-18 18:33:06 -0800515 bool loadSymbolsFromIncludePaths() {
516 std::unique_ptr<AssetManagerSymbolSource> assetSource =
517 util::make_unique<AssetManagerSymbolSource>();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700518 for (const std::string& path : mOptions.includePaths) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800519 if (mContext->verbose()) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800520 mContext->getDiagnostics()->note(DiagMessage(path) << "loading include path");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700521 }
522
Adam Lesinski64587af2016-02-18 18:33:06 -0800523 // First try to load the file as a static lib.
524 std::string errorStr;
525 std::unique_ptr<ResourceTable> staticInclude = loadStaticLibrary(path, &errorStr);
526 if (staticInclude) {
527 if (!mOptions.staticLib) {
528 // Can't include static libraries when not building a static library.
529 mContext->getDiagnostics()->error(
530 DiagMessage(path) << "can't include static library when building app");
531 return false;
532 }
533
534 // If we are using --no-static-lib-packages, we need to rename the package of this
535 // table to our compilation package.
536 if (mOptions.noStaticLibPackages) {
537 if (ResourceTablePackage* pkg = staticInclude->findPackageById(0x7f)) {
538 pkg->name = mContext->getCompilationPackage();
539 }
540 }
541
542 mContext->getExternalSymbols()->appendSource(
543 util::make_unique<ResourceTableSymbolSource>(staticInclude.get()));
544
545 mStaticTableIncludes.push_back(std::move(staticInclude));
546
547 } else if (!errorStr.empty()) {
548 // We had an error with reading, so fail.
549 mContext->getDiagnostics()->error(DiagMessage(path) << errorStr);
550 return false;
551 }
552
553 if (!assetSource->addAssetPath(path)) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800554 mContext->getDiagnostics()->error(
Adam Lesinskifb48d292015-11-07 15:52:13 -0800555 DiagMessage(path) << "failed to load include path");
Adam Lesinski64587af2016-02-18 18:33:06 -0800556 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700557 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700558 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800559
560 mContext->getExternalSymbols()->appendSource(std::move(assetSource));
561 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700562 }
563
Adam Lesinski467f1712015-11-16 17:35:44 -0800564 Maybe<AppInfo> extractAppInfoFromManifest(xml::XmlResource* xmlRes) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700565 // Make sure the first element is <manifest> with package attribute.
Adam Lesinski2ae4a872015-11-02 16:10:55 -0800566 if (xml::Element* manifestEl = xml::findRootElement(xmlRes->root.get())) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700567 if (manifestEl->namespaceUri.empty() && manifestEl->name == u"manifest") {
568 if (xml::Attribute* packageAttr = manifestEl->findAttribute({}, u"package")) {
569 return AppInfo{ packageAttr->value };
570 }
571 }
572 }
573 return {};
574 }
575
Adam Lesinski979ccb22016-01-11 10:42:19 -0800576 /**
577 * Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
578 * Postcondition: ResourceTable has only one package left. All others are stripped, or there
579 * is an error and false is returned.
580 */
Adam Lesinskifb48d292015-11-07 15:52:13 -0800581 bool verifyNoExternalPackages() {
Adam Lesinski979ccb22016-01-11 10:42:19 -0800582 auto isExtPackageFunc = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinski6a008172016-02-02 17:02:58 -0800583 return mContext->getCompilationPackage() != pkg->name ||
Adam Lesinski979ccb22016-01-11 10:42:19 -0800584 !pkg->id ||
Adam Lesinski6a008172016-02-02 17:02:58 -0800585 pkg->id.value() != mContext->getPackageId();
Adam Lesinski979ccb22016-01-11 10:42:19 -0800586 };
587
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700588 bool error = false;
Adam Lesinskifb48d292015-11-07 15:52:13 -0800589 for (const auto& package : mFinalTable.packages) {
Adam Lesinski979ccb22016-01-11 10:42:19 -0800590 if (isExtPackageFunc(package)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700591 // We have a package that is not related to the one we're building!
592 for (const auto& type : package->types) {
593 for (const auto& entry : type->entries) {
Adam Lesinski979ccb22016-01-11 10:42:19 -0800594 ResourceNameRef resName(package->name, type->type, entry->name);
595
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700596 for (const auto& configValue : entry->values) {
Adam Lesinski979ccb22016-01-11 10:42:19 -0800597 // Special case the occurrence of an ID that is being generated for the
598 // 'android' package. This is due to legacy reasons.
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -0800599 if (valueCast<Id>(configValue->value.get()) &&
Adam Lesinski979ccb22016-01-11 10:42:19 -0800600 package->name == u"android") {
Adam Lesinski6a008172016-02-02 17:02:58 -0800601 mContext->getDiagnostics()->warn(
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -0800602 DiagMessage(configValue->value->getSource())
Adam Lesinski979ccb22016-01-11 10:42:19 -0800603 << "generated id '" << resName
604 << "' for external package '" << package->name
605 << "'");
606 } else {
Adam Lesinski6a008172016-02-02 17:02:58 -0800607 mContext->getDiagnostics()->error(
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -0800608 DiagMessage(configValue->value->getSource())
Adam Lesinski979ccb22016-01-11 10:42:19 -0800609 << "defined resource '" << resName
610 << "' for external package '" << package->name
611 << "'");
612 error = true;
613 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700614 }
615 }
616 }
617 }
618 }
Adam Lesinski979ccb22016-01-11 10:42:19 -0800619
620 auto newEndIter = std::remove_if(mFinalTable.packages.begin(), mFinalTable.packages.end(),
621 isExtPackageFunc);
622 mFinalTable.packages.erase(newEndIter, mFinalTable.packages.end());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700623 return !error;
624 }
625
Adam Lesinski64587af2016-02-18 18:33:06 -0800626 /**
627 * Returns true if no IDs have been set, false otherwise.
628 */
629 bool verifyNoIdsSet() {
630 for (const auto& package : mFinalTable.packages) {
631 for (const auto& type : package->types) {
632 if (type->id) {
633 mContext->getDiagnostics()->error(DiagMessage() << "type " << type->type
634 << " has ID " << std::hex
635 << (int) type->id.value()
636 << std::dec << " assigned");
637 return false;
638 }
639
640 for (const auto& entry : type->entries) {
641 if (entry->id) {
642 ResourceNameRef resName(package->name, type->type, entry->name);
643 mContext->getDiagnostics()->error(DiagMessage() << "entry " << resName
644 << " has ID " << std::hex
645 << (int) entry->id.value()
646 << std::dec << " assigned");
647 return false;
648 }
649 }
650 }
651 }
652 return true;
653 }
654
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700655 std::unique_ptr<IArchiveWriter> makeArchiveWriter() {
656 if (mOptions.outputToDirectory) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800657 return createDirectoryArchiveWriter(mContext->getDiagnostics(), mOptions.outputPath);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700658 } else {
Adam Lesinski6a008172016-02-02 17:02:58 -0800659 return createZipFileArchiveWriter(mContext->getDiagnostics(), mOptions.outputPath);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700660 }
661 }
662
663 bool flattenTable(ResourceTable* table, IArchiveWriter* writer) {
664 BigBuffer buffer(1024);
Adam Lesinski59e04c62016-02-04 15:59:23 -0800665 TableFlattener flattener(&buffer);
Adam Lesinski6a008172016-02-02 17:02:58 -0800666 if (!flattener.consume(mContext, table)) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700667 return false;
668 }
669
Adam Lesinskia40e9722015-11-24 19:11:46 -0800670 if (writer->startEntry("resources.arsc", ArchiveEntry::kAlign)) {
671 if (writer->writeEntry(buffer)) {
672 if (writer->finishEntry()) {
673 return true;
674 }
675 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700676 }
Adam Lesinskia40e9722015-11-24 19:11:46 -0800677
Adam Lesinski6a008172016-02-02 17:02:58 -0800678 mContext->getDiagnostics()->error(
Adam Lesinskia40e9722015-11-24 19:11:46 -0800679 DiagMessage() << "failed to write resources.arsc to archive");
680 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700681 }
682
Adam Lesinski64587af2016-02-18 18:33:06 -0800683 bool flattenTableToPb(ResourceTable* table, IArchiveWriter* writer) {
684 // Create the file/zip entry.
685 if (!writer->startEntry("resources.arsc.flat", 0)) {
686 mContext->getDiagnostics()->error(DiagMessage() << "failed to open");
687 return false;
688 }
689
690 std::unique_ptr<pb::ResourceTable> pbTable = serializeTableToPb(table);
691
692 // Wrap our IArchiveWriter with an adaptor that implements the ZeroCopyOutputStream
693 // interface.
694 {
695 google::protobuf::io::CopyingOutputStreamAdaptor adaptor(writer);
696
697 if (!pbTable->SerializeToZeroCopyStream(&adaptor)) {
698 mContext->getDiagnostics()->error(DiagMessage() << "failed to write");
699 return false;
700 }
701 }
702
703 if (!writer->finishEntry()) {
704 mContext->getDiagnostics()->error(DiagMessage() << "failed to finish entry");
705 return false;
706 }
707 return true;
708 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700709
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700710 bool writeJavaFile(ResourceTable* table, const StringPiece16& packageNameToGenerate,
711 const StringPiece16& outPackage, JavaClassGeneratorOptions javaOptions) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700712 if (!mOptions.generateJavaClassPath) {
713 return true;
714 }
715
716 std::string outPath = mOptions.generateJavaClassPath.value();
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700717 file::appendPath(&outPath, file::packageToPath(util::utf16ToUtf8(outPackage)));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700718 file::mkdirs(outPath);
719 file::appendPath(&outPath, "R.java");
720
721 std::ofstream fout(outPath, std::ofstream::binary);
722 if (!fout) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800723 mContext->getDiagnostics()->error(DiagMessage() << strerror(errno));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700724 return false;
725 }
726
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700727 JavaClassGenerator generator(table, javaOptions);
Adam Lesinski9e10ac72015-10-16 14:37:48 -0700728 if (!generator.generate(packageNameToGenerate, outPackage, &fout)) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800729 mContext->getDiagnostics()->error(DiagMessage(outPath) << generator.getError());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700730 return false;
731 }
732 return true;
733 }
734
Adam Lesinski467f1712015-11-16 17:35:44 -0800735 bool writeManifestJavaFile(xml::XmlResource* manifestXml) {
Adam Lesinskica5638f2015-10-21 14:42:43 -0700736 if (!mOptions.generateJavaClassPath) {
737 return true;
738 }
739
740 std::string outPath = mOptions.generateJavaClassPath.value();
741 file::appendPath(&outPath,
Adam Lesinski6a008172016-02-02 17:02:58 -0800742 file::packageToPath(util::utf16ToUtf8(mContext->getCompilationPackage())));
Adam Lesinskica5638f2015-10-21 14:42:43 -0700743 file::mkdirs(outPath);
744 file::appendPath(&outPath, "Manifest.java");
745
746 std::ofstream fout(outPath, std::ofstream::binary);
747 if (!fout) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800748 mContext->getDiagnostics()->error(DiagMessage() << strerror(errno));
Adam Lesinskica5638f2015-10-21 14:42:43 -0700749 return false;
750 }
751
752 ManifestClassGenerator generator;
Adam Lesinski6a008172016-02-02 17:02:58 -0800753 if (!generator.generate(mContext->getDiagnostics(), mContext->getCompilationPackage(),
Adam Lesinskica5638f2015-10-21 14:42:43 -0700754 manifestXml, &fout)) {
755 return false;
756 }
757
758 if (!fout) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800759 mContext->getDiagnostics()->error(DiagMessage() << strerror(errno));
Adam Lesinskica5638f2015-10-21 14:42:43 -0700760 return false;
761 }
762 return true;
763 }
764
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700765 bool writeProguardFile(const proguard::KeepSet& keepSet) {
766 if (!mOptions.generateProguardRulesPath) {
767 return true;
768 }
769
770 std::ofstream fout(mOptions.generateProguardRulesPath.value(), std::ofstream::binary);
771 if (!fout) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800772 mContext->getDiagnostics()->error(DiagMessage() << strerror(errno));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700773 return false;
774 }
775
776 proguard::writeKeepSet(&fout, keepSet);
777 if (!fout) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800778 mContext->getDiagnostics()->error(DiagMessage() << strerror(errno));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700779 return false;
780 }
781 return true;
782 }
783
Adam Lesinski64587af2016-02-18 18:33:06 -0800784 std::unique_ptr<ResourceTable> loadStaticLibrary(const std::string& input,
785 std::string* outError) {
786 std::unique_ptr<io::ZipFileCollection> collection = io::ZipFileCollection::create(
787 input, outError);
788 if (!collection) {
789 return {};
790 }
791 return loadTablePbFromCollection(collection.get());
792 }
793
794 std::unique_ptr<ResourceTable> loadTablePbFromCollection(io::IFileCollection* collection) {
795 io::IFile* file = collection->findFile("resources.arsc.flat");
796 if (!file) {
797 return {};
798 }
799
800 std::unique_ptr<io::IData> data = file->openAsData();
801 return loadTableFromPb(file->getSource(), data->data(), data->size(),
802 mContext->getDiagnostics());
803 }
804
805 bool mergeStaticLibrary(const std::string& input, bool override) {
806 if (mContext->verbose()) {
807 mContext->getDiagnostics()->note(DiagMessage() << "merging static library " << input);
808 }
809
810 std::string errorStr;
811 std::unique_ptr<io::ZipFileCollection> collection =
812 io::ZipFileCollection::create(input, &errorStr);
813 if (!collection) {
814 mContext->getDiagnostics()->error(DiagMessage(input) << errorStr);
815 return false;
816 }
817
818 std::unique_ptr<ResourceTable> table = loadTablePbFromCollection(collection.get());
819 if (!table) {
820 mContext->getDiagnostics()->error(DiagMessage(input) << "invalid static library");
821 return false;
822 }
823
824 ResourceTablePackage* pkg = table->findPackageById(0x7f);
825 if (!pkg) {
826 mContext->getDiagnostics()->error(DiagMessage(input)
827 << "static library has no package");
828 return false;
829 }
830
831 bool result;
832 if (mOptions.noStaticLibPackages) {
833 // Merge all resources as if they were in the compilation package. This is the old
834 // behaviour of aapt.
835
836 // Add the package to the set of --extra-packages so we emit an R.java for each
837 // library package.
838 if (!pkg->name.empty()) {
839 mOptions.extraJavaPackages.insert(pkg->name);
840 }
841
842 pkg->name = u"";
843 if (override) {
844 result = mTableMerger->mergeOverlay(Source(input), table.get(), collection.get());
845 } else {
846 result = mTableMerger->merge(Source(input), table.get(), collection.get());
847 }
848
849 } else {
850 // This is the proper way to merge libraries, where the package name is preserved
851 // and resource names are mangled.
852 result = mTableMerger->mergeAndMangle(Source(input), pkg->name, table.get(),
853 collection.get());
854 }
855
856 if (!result) {
857 return false;
858 }
859
860 // Make sure to move the collection into the set of IFileCollections.
861 mCollections.push_back(std::move(collection));
Adam Lesinskifb48d292015-11-07 15:52:13 -0800862 return true;
863 }
864
Adam Lesinskia40e9722015-11-24 19:11:46 -0800865 bool mergeResourceTable(io::IFile* file, bool override) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800866 if (mContext->verbose()) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800867 mContext->getDiagnostics()->note(DiagMessage() << "merging resource table "
868 << file->getSource());
Adam Lesinskifb48d292015-11-07 15:52:13 -0800869 }
870
Adam Lesinskia40e9722015-11-24 19:11:46 -0800871 std::unique_ptr<io::IData> data = file->openAsData();
872 if (!data) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800873 mContext->getDiagnostics()->error(DiagMessage(file->getSource())
Adam Lesinskia40e9722015-11-24 19:11:46 -0800874 << "failed to open file");
875 return false;
876 }
877
Adam Lesinski355f2852016-02-13 20:26:45 -0800878 std::unique_ptr<ResourceTable> table = loadTableFromPb(file->getSource(),
879 data->data(), data->size(),
880 mContext->getDiagnostics());
Adam Lesinskifb48d292015-11-07 15:52:13 -0800881 if (!table) {
882 return false;
883 }
884
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800885 bool result = false;
886 if (override) {
887 result = mTableMerger->mergeOverlay(file->getSource(), table.get());
888 } else {
889 result = mTableMerger->merge(file->getSource(), table.get());
Adam Lesinskifb48d292015-11-07 15:52:13 -0800890 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800891 return result;
Adam Lesinskifb48d292015-11-07 15:52:13 -0800892 }
893
Adam Lesinski64587af2016-02-18 18:33:06 -0800894 bool mergeCompiledFile(io::IFile* file, ResourceFile* fileDesc, bool override) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800895 if (mContext->verbose()) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800896 mContext->getDiagnostics()->note(DiagMessage() << "merging compiled file "
897 << file->getSource());
Adam Lesinskifb48d292015-11-07 15:52:13 -0800898 }
899
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800900 bool result = false;
Adam Lesinski64587af2016-02-18 18:33:06 -0800901 if (override) {
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800902 result = mTableMerger->mergeFileOverlay(*fileDesc, file);
Adam Lesinskifb48d292015-11-07 15:52:13 -0800903 } else {
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800904 result = mTableMerger->mergeFile(*fileDesc, file);
Adam Lesinskifb48d292015-11-07 15:52:13 -0800905 }
906
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800907 if (!result) {
Adam Lesinskifb48d292015-11-07 15:52:13 -0800908 return false;
909 }
910
911 // Add the exports of this file to the table.
Adam Lesinskia40e9722015-11-24 19:11:46 -0800912 for (SourcedResourceName& exportedSymbol : fileDesc->exportedSymbols) {
Adam Lesinskifb48d292015-11-07 15:52:13 -0800913 if (exportedSymbol.name.package.empty()) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800914 exportedSymbol.name.package = mContext->getCompilationPackage();
Adam Lesinskifb48d292015-11-07 15:52:13 -0800915 }
916
917 ResourceNameRef resName = exportedSymbol.name;
918
Adam Lesinski6a008172016-02-02 17:02:58 -0800919 Maybe<ResourceName> mangledName = mContext->getNameMangler()->mangleName(
Adam Lesinskifb48d292015-11-07 15:52:13 -0800920 exportedSymbol.name);
921 if (mangledName) {
922 resName = mangledName.value();
923 }
924
925 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinskia40e9722015-11-24 19:11:46 -0800926 id->setSource(fileDesc->source.withLine(exportedSymbol.line));
Adam Lesinski64587af2016-02-18 18:33:06 -0800927 bool result = mFinalTable.addResourceAllowMangled(
928 resName, ConfigDescription::defaultConfig(), std::string(), std::move(id),
929 mContext->getDiagnostics());
Adam Lesinskifb48d292015-11-07 15:52:13 -0800930 if (!result) {
931 return false;
932 }
933 }
Adam Lesinskifb48d292015-11-07 15:52:13 -0800934 return true;
935 }
936
Adam Lesinskia40e9722015-11-24 19:11:46 -0800937 /**
Adam Lesinski64587af2016-02-18 18:33:06 -0800938 * Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
939 * If override is true, conflicting resources are allowed to override each other, in order of
940 * last seen.
941 *
942 * An io::IFileCollection is created from the ZIP file and added to the set of
943 * io::IFileCollections that are open.
Adam Lesinskia40e9722015-11-24 19:11:46 -0800944 */
945 bool mergeArchive(const std::string& input, bool override) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800946 if (mContext->verbose()) {
947 mContext->getDiagnostics()->note(DiagMessage() << "merging archive " << input);
948 }
949
Adam Lesinskia40e9722015-11-24 19:11:46 -0800950 std::string errorStr;
Adam Lesinski64587af2016-02-18 18:33:06 -0800951 std::unique_ptr<io::ZipFileCollection> collection =
952 io::ZipFileCollection::create(input, &errorStr);
Adam Lesinskia40e9722015-11-24 19:11:46 -0800953 if (!collection) {
Adam Lesinski6a008172016-02-02 17:02:58 -0800954 mContext->getDiagnostics()->error(DiagMessage(input) << errorStr);
Adam Lesinskia40e9722015-11-24 19:11:46 -0800955 return false;
956 }
957
958 bool error = false;
Adam Lesinskia6fe3452015-12-09 15:20:52 -0800959 for (auto iter = collection->iterator(); iter->hasNext(); ) {
Adam Lesinski64587af2016-02-18 18:33:06 -0800960 if (!mergeFile(iter->next(), override)) {
Adam Lesinskia40e9722015-11-24 19:11:46 -0800961 error = true;
962 }
963 }
964
965 // Make sure to move the collection into the set of IFileCollections.
966 mCollections.push_back(std::move(collection));
967 return !error;
968 }
969
Adam Lesinski64587af2016-02-18 18:33:06 -0800970 /**
971 * Takes a path to load and merge into the master ResourceTable. If override is true,
972 * conflicting resources are allowed to override each other, in order of last seen.
973 *
974 * If the file path ends with .flata, .jar, .jack, or .zip the file is treated as ZIP archive
975 * and the files within are merged individually.
976 *
977 * Otherwise the files is processed on its own.
978 */
979 bool mergePath(const std::string& path, bool override) {
Adam Lesinski656a5772016-01-14 15:17:41 -0800980 if (util::stringEndsWith<char>(path, ".flata") ||
981 util::stringEndsWith<char>(path, ".jar") ||
982 util::stringEndsWith<char>(path, ".jack") ||
983 util::stringEndsWith<char>(path, ".zip")) {
Adam Lesinskia40e9722015-11-24 19:11:46 -0800984 return mergeArchive(path, override);
Adam Lesinski64587af2016-02-18 18:33:06 -0800985 } else if (util::stringEndsWith<char>(path, ".apk")) {
986 return mergeStaticLibrary(path, override);
Adam Lesinskia40e9722015-11-24 19:11:46 -0800987 }
988
989 io::IFile* file = mFileCollection->insertFile(path);
Adam Lesinski64587af2016-02-18 18:33:06 -0800990 return mergeFile(file, override);
Adam Lesinskia40e9722015-11-24 19:11:46 -0800991 }
992
Adam Lesinski64587af2016-02-18 18:33:06 -0800993 /**
994 * Takes a file to load and merge into the master ResourceTable. If override is true,
995 * conflicting resources are allowed to override each other, in order of last seen.
996 *
997 * If the file ends with .arsc.flat, then it is loaded as a ResourceTable and merged into the
998 * master ResourceTable. If the file ends with .flat, then it is treated like a compiled file
999 * and the header data is read and merged into the final ResourceTable.
1000 *
1001 * All other file types are ignored. This is because these files could be coming from a zip,
1002 * where we could have other files like classes.dex.
1003 */
1004 bool mergeFile(io::IFile* file, bool override) {
Adam Lesinskia40e9722015-11-24 19:11:46 -08001005 const Source& src = file->getSource();
1006 if (util::stringEndsWith<char>(src.path, ".arsc.flat")) {
1007 return mergeResourceTable(file, override);
Adam Lesinski64587af2016-02-18 18:33:06 -08001008
Adam Lesinski52364f72016-01-11 13:10:24 -08001009 } else if (util::stringEndsWith<char>(src.path, ".flat")){
Adam Lesinskia40e9722015-11-24 19:11:46 -08001010 // Try opening the file and looking for an Export header.
1011 std::unique_ptr<io::IData> data = file->openAsData();
1012 if (!data) {
Adam Lesinski6a008172016-02-02 17:02:58 -08001013 mContext->getDiagnostics()->error(DiagMessage(src) << "failed to open");
Adam Lesinskia40e9722015-11-24 19:11:46 -08001014 return false;
1015 }
1016
1017 std::unique_ptr<ResourceFile> resourceFile = loadFileExportHeader(
Adam Lesinski6a008172016-02-02 17:02:58 -08001018 src, data->data(), data->size(), mContext->getDiagnostics());
Adam Lesinskia40e9722015-11-24 19:11:46 -08001019 if (resourceFile) {
Adam Lesinski64587af2016-02-18 18:33:06 -08001020 return mergeCompiledFile(file, resourceFile.get(), override);
Adam Lesinskia40e9722015-11-24 19:11:46 -08001021 }
Adam Lesinskic446a732016-01-21 11:04:46 -08001022 return false;
Adam Lesinskifb48d292015-11-07 15:52:13 -08001023 }
Adam Lesinski52364f72016-01-11 13:10:24 -08001024
Adam Lesinskic446a732016-01-21 11:04:46 -08001025 // Ignore non .flat files. This could be classes.dex or something else that happens
1026 // to be in an archive.
1027 return true;
Adam Lesinskifb48d292015-11-07 15:52:13 -08001028 }
1029
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001030 int run(const std::vector<std::string>& inputFiles) {
1031 // Load the AndroidManifest.xml
Adam Lesinskia40e9722015-11-24 19:11:46 -08001032 std::unique_ptr<xml::XmlResource> manifestXml = loadXml(mOptions.manifestPath,
Adam Lesinski6a008172016-02-02 17:02:58 -08001033 mContext->getDiagnostics());
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001034 if (!manifestXml) {
1035 return 1;
1036 }
1037
1038 if (Maybe<AppInfo> maybeAppInfo = extractAppInfoFromManifest(manifestXml.get())) {
Adam Lesinski64587af2016-02-18 18:33:06 -08001039 mContext->setCompilationPackage(maybeAppInfo.value().package);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001040 } else {
Adam Lesinski6a008172016-02-02 17:02:58 -08001041 mContext->getDiagnostics()->error(DiagMessage(mOptions.manifestPath)
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001042 << "no package specified in <manifest> tag");
1043 return 1;
1044 }
1045
Adam Lesinski64587af2016-02-18 18:33:06 -08001046 if (!util::isJavaPackageName(mContext->getCompilationPackage())) {
Adam Lesinski6a008172016-02-02 17:02:58 -08001047 mContext->getDiagnostics()->error(DiagMessage(mOptions.manifestPath)
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001048 << "invalid package name '"
Adam Lesinski64587af2016-02-18 18:33:06 -08001049 << mContext->getCompilationPackage()
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001050 << "'");
1051 return 1;
1052 }
1053
Adam Lesinski64587af2016-02-18 18:33:06 -08001054 mContext->setNameManglerPolicy(NameManglerPolicy{ mContext->getCompilationPackage() });
Adam Lesinski9ba47d82015-10-13 11:37:10 -07001055
Adam Lesinski64587af2016-02-18 18:33:06 -08001056 if (mContext->getCompilationPackage() == u"android") {
1057 mContext->setPackageId(0x01);
Adam Lesinski9ba47d82015-10-13 11:37:10 -07001058 } else {
Adam Lesinski64587af2016-02-18 18:33:06 -08001059 mContext->setPackageId(0x7f);
Adam Lesinski9ba47d82015-10-13 11:37:10 -07001060 }
1061
Adam Lesinski64587af2016-02-18 18:33:06 -08001062 if (!loadSymbolsFromIncludePaths()) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001063 return 1;
1064 }
1065
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001066 TableMergerOptions tableMergerOptions;
1067 tableMergerOptions.autoAddOverlay = mOptions.autoAddOverlay;
Adam Lesinski6a008172016-02-02 17:02:58 -08001068 mTableMerger = util::make_unique<TableMerger>(mContext, &mFinalTable, tableMergerOptions);
Adam Lesinskifb48d292015-11-07 15:52:13 -08001069
Adam Lesinski355f2852016-02-13 20:26:45 -08001070 if (mContext->verbose()) {
Adam Lesinski6a008172016-02-02 17:02:58 -08001071 mContext->getDiagnostics()->note(
Adam Lesinski64587af2016-02-18 18:33:06 -08001072 DiagMessage() << "linking package '" << mContext->getCompilationPackage()
1073 << "' with package ID " << std::hex
1074 << (int) mContext->getPackageId());
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001075 }
1076
Adam Lesinskifb48d292015-11-07 15:52:13 -08001077
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001078 for (const std::string& input : inputFiles) {
Adam Lesinski64587af2016-02-18 18:33:06 -08001079 if (!mergePath(input, false)) {
Adam Lesinski6a008172016-02-02 17:02:58 -08001080 mContext->getDiagnostics()->error(DiagMessage() << "failed parsing input");
Adam Lesinski467f1712015-11-16 17:35:44 -08001081 return 1;
Adam Lesinskifb48d292015-11-07 15:52:13 -08001082 }
1083 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001084
Adam Lesinskifb48d292015-11-07 15:52:13 -08001085 for (const std::string& input : mOptions.overlayFiles) {
Adam Lesinski64587af2016-02-18 18:33:06 -08001086 if (!mergePath(input, true)) {
Adam Lesinski6a008172016-02-02 17:02:58 -08001087 mContext->getDiagnostics()->error(DiagMessage() << "failed parsing overlays");
Adam Lesinski467f1712015-11-16 17:35:44 -08001088 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001089 }
1090 }
1091
Adam Lesinskifb48d292015-11-07 15:52:13 -08001092 if (!verifyNoExternalPackages()) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001093 return 1;
1094 }
1095
1096 if (!mOptions.staticLib) {
1097 PrivateAttributeMover mover;
Adam Lesinski6a008172016-02-02 17:02:58 -08001098 if (!mover.consume(mContext, &mFinalTable)) {
1099 mContext->getDiagnostics()->error(
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001100 DiagMessage() << "failed moving private attributes");
1101 return 1;
1102 }
1103 }
1104
Adam Lesinski64587af2016-02-18 18:33:06 -08001105 if (!mOptions.staticLib) {
1106 // Assign IDs if we are building a regular app.
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001107 IdAssigner idAssigner;
Adam Lesinski6a008172016-02-02 17:02:58 -08001108 if (!idAssigner.consume(mContext, &mFinalTable)) {
1109 mContext->getDiagnostics()->error(DiagMessage() << "failed assigning IDs");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001110 return 1;
1111 }
Adam Lesinski64587af2016-02-18 18:33:06 -08001112 } else {
1113 // Static libs are merged with other apps, and ID collisions are bad, so verify that
1114 // no IDs have been set.
1115 if (!verifyNoIdsSet()) {
1116 return 1;
1117 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001118 }
1119
Adam Lesinski64587af2016-02-18 18:33:06 -08001120 // Add the names to mangle based on our source merge earlier.
1121 mContext->setNameManglerPolicy(NameManglerPolicy{
1122 mContext->getCompilationPackage(), mTableMerger->getMergedPackages() });
1123
1124 // Add our table to the symbol table.
1125 mContext->getExternalSymbols()->prependSource(
1126 util::make_unique<ResourceTableSymbolSource>(&mFinalTable));
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001127
1128 {
1129 ReferenceLinker linker;
Adam Lesinski6a008172016-02-02 17:02:58 -08001130 if (!linker.consume(mContext, &mFinalTable)) {
1131 mContext->getDiagnostics()->error(DiagMessage() << "failed linking references");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001132 return 1;
1133 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08001134
Adam Lesinski64587af2016-02-18 18:33:06 -08001135 if (mOptions.staticLib) {
1136 if (!mOptions.products.empty()) {
1137 mContext->getDiagnostics()->warn(
1138 DiagMessage() << "can't select products when building static library");
1139 }
Adam Lesinski355f2852016-02-13 20:26:45 -08001140
Adam Lesinski64587af2016-02-18 18:33:06 -08001141 if (mOptions.tableSplitterOptions.configFilter != nullptr ||
1142 mOptions.tableSplitterOptions.preferredDensity) {
1143 mContext->getDiagnostics()->warn(
1144 DiagMessage() << "can't strip resources when building static library");
1145 }
1146 } else {
1147 ProductFilter productFilter(mOptions.products);
1148 if (!productFilter.consume(mContext, &mFinalTable)) {
1149 mContext->getDiagnostics()->error(DiagMessage() << "failed stripping products");
1150 return 1;
1151 }
Adam Lesinski355f2852016-02-13 20:26:45 -08001152
Adam Lesinski64587af2016-02-18 18:33:06 -08001153 // TODO(adamlesinski): Actually pass in split constraints and handle splits at the file
1154 // level.
1155 TableSplitter tableSplitter({}, mOptions.tableSplitterOptions);
1156 if (!tableSplitter.verifySplitConstraints(mContext)) {
1157 return 1;
1158 }
1159 tableSplitter.splitTable(&mFinalTable);
1160 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001161 }
1162
1163 proguard::KeepSet proguardKeepSet;
1164
1165 std::unique_ptr<IArchiveWriter> archiveWriter = makeArchiveWriter();
1166 if (!archiveWriter) {
Adam Lesinski6a008172016-02-02 17:02:58 -08001167 mContext->getDiagnostics()->error(DiagMessage() << "failed to create archive");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001168 return 1;
1169 }
1170
Adam Lesinski467f1712015-11-16 17:35:44 -08001171 bool error = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001172 {
Adam Lesinski52364f72016-01-11 13:10:24 -08001173 ManifestFixer manifestFixer(mOptions.manifestFixerOptions);
Adam Lesinski6a008172016-02-02 17:02:58 -08001174 if (!manifestFixer.consume(mContext, manifestXml.get())) {
Adam Lesinski2ae4a872015-11-02 16:10:55 -08001175 error = true;
1176 }
1177
Adam Lesinski467f1712015-11-16 17:35:44 -08001178 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
1179 // (aka, which package the AndroidManifest.xml is coming from).
1180 // So we give it a package name so it can see local resources.
Adam Lesinski64587af2016-02-18 18:33:06 -08001181 manifestXml->file.name.package = mContext->getCompilationPackage();
Adam Lesinski467f1712015-11-16 17:35:44 -08001182
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001183 XmlReferenceLinker manifestLinker;
Adam Lesinski6a008172016-02-02 17:02:58 -08001184 if (manifestLinker.consume(mContext, manifestXml.get())) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001185 if (!proguard::collectProguardRulesForManifest(Source(mOptions.manifestPath),
1186 manifestXml.get(),
1187 &proguardKeepSet)) {
1188 error = true;
1189 }
1190
Adam Lesinskica5638f2015-10-21 14:42:43 -07001191 if (mOptions.generateJavaClassPath) {
1192 if (!writeManifestJavaFile(manifestXml.get())) {
1193 error = true;
1194 }
1195 }
1196
Adam Lesinski355f2852016-02-13 20:26:45 -08001197 const bool keepRawValues = mOptions.staticLib;
1198 bool result = flattenXml(manifestXml.get(), "AndroidManifest.xml", {},
1199 keepRawValues, archiveWriter.get(), mContext);
1200 if (!result) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001201 error = true;
1202 }
1203 } else {
1204 error = true;
1205 }
1206 }
1207
Adam Lesinski467f1712015-11-16 17:35:44 -08001208 if (error) {
Adam Lesinski6a008172016-02-02 17:02:58 -08001209 mContext->getDiagnostics()->error(DiagMessage() << "failed processing manifest");
Adam Lesinski467f1712015-11-16 17:35:44 -08001210 return 1;
1211 }
1212
Adam Lesinski355f2852016-02-13 20:26:45 -08001213 ResourceFileFlattenerOptions fileFlattenerOptions;
1214 fileFlattenerOptions.keepRawValues = mOptions.staticLib;
1215 fileFlattenerOptions.doNotCompressAnything = mOptions.doNotCompressAnything;
1216 fileFlattenerOptions.extensionsToNotCompress = mOptions.extensionsToNotCompress;
1217 fileFlattenerOptions.noAutoVersion = mOptions.noAutoVersion;
1218 ResourceFileFlattener fileFlattener(fileFlattenerOptions, mContext, &proguardKeepSet);
Adam Lesinskia40e9722015-11-24 19:11:46 -08001219
Adam Lesinski355f2852016-02-13 20:26:45 -08001220 if (!fileFlattener.flatten(&mFinalTable, archiveWriter.get())) {
Adam Lesinski6a008172016-02-02 17:02:58 -08001221 mContext->getDiagnostics()->error(DiagMessage() << "failed linking file resources");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001222 return 1;
1223 }
1224
Adam Lesinski64587af2016-02-18 18:33:06 -08001225 if (!mOptions.staticLib && !mOptions.noAutoVersion) {
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001226 AutoVersioner versioner;
Adam Lesinski6a008172016-02-02 17:02:58 -08001227 if (!versioner.consume(mContext, &mFinalTable)) {
1228 mContext->getDiagnostics()->error(DiagMessage() << "failed versioning styles");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001229 return 1;
1230 }
1231 }
1232
Adam Lesinski64587af2016-02-18 18:33:06 -08001233 if (mOptions.staticLib) {
1234 if (!flattenTableToPb(&mFinalTable, archiveWriter.get())) {
1235 mContext->getDiagnostics()->error(DiagMessage()
1236 << "failed to write resources.arsc.flat");
1237 return 1;
1238 }
1239 } else {
1240 if (!flattenTable(&mFinalTable, archiveWriter.get())) {
1241 mContext->getDiagnostics()->error(DiagMessage()
1242 << "failed to write resources.arsc");
1243 return 1;
1244 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001245 }
1246
1247 if (mOptions.generateJavaClassPath) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001248 JavaClassGeneratorOptions options;
Adam Lesinski52364f72016-01-11 13:10:24 -08001249 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1250
Adam Lesinskief9c5012016-01-22 14:09:53 -08001251 if (mOptions.staticLib || mOptions.generateNonFinalIds) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001252 options.useFinal = false;
1253 }
1254
Adam Lesinski6a008172016-02-02 17:02:58 -08001255 const StringPiece16 actualPackage = mContext->getCompilationPackage();
1256 StringPiece16 outputPackage = mContext->getCompilationPackage();
Adam Lesinski52364f72016-01-11 13:10:24 -08001257 if (mOptions.customJavaPackage) {
1258 // Override the output java package to the custom one.
1259 outputPackage = mOptions.customJavaPackage.value();
1260 }
Adam Lesinski83f22552015-11-07 11:51:23 -08001261
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001262 if (mOptions.privateSymbols) {
1263 // If we defined a private symbols package, we only emit Public symbols
1264 // to the original package, and private and public symbols to the private package.
1265
1266 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
Adam Lesinski6a008172016-02-02 17:02:58 -08001267 if (!writeJavaFile(&mFinalTable, mContext->getCompilationPackage(),
Adam Lesinski52364f72016-01-11 13:10:24 -08001268 outputPackage, options)) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001269 return 1;
1270 }
1271
1272 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
Adam Lesinski83f22552015-11-07 11:51:23 -08001273 outputPackage = mOptions.privateSymbols.value();
1274 }
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001275
Adam Lesinskifb48d292015-11-07 15:52:13 -08001276 if (!writeJavaFile(&mFinalTable, actualPackage, outputPackage, options)) {
Adam Lesinski83f22552015-11-07 11:51:23 -08001277 return 1;
1278 }
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001279
Adam Lesinski52364f72016-01-11 13:10:24 -08001280 for (const std::u16string& extraPackage : mOptions.extraJavaPackages) {
1281 if (!writeJavaFile(&mFinalTable, actualPackage, extraPackage, options)) {
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001282 return 1;
1283 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001284 }
1285 }
1286
1287 if (mOptions.generateProguardRulesPath) {
1288 if (!writeProguardFile(proguardKeepSet)) {
1289 return 1;
1290 }
1291 }
1292
Adam Lesinski355f2852016-02-13 20:26:45 -08001293 if (mContext->verbose()) {
1294 DebugPrintTableOptions debugPrintTableOptions;
1295 debugPrintTableOptions.showSources = true;
1296 Debug::printTable(&mFinalTable, debugPrintTableOptions);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001297 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001298 return 0;
1299 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001300
1301private:
1302 LinkOptions mOptions;
Adam Lesinski6a008172016-02-02 17:02:58 -08001303 LinkContext* mContext;
Adam Lesinskifb48d292015-11-07 15:52:13 -08001304 ResourceTable mFinalTable;
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001305
Adam Lesinskifb48d292015-11-07 15:52:13 -08001306 std::unique_ptr<TableMerger> mTableMerger;
1307
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001308 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinski64587af2016-02-18 18:33:06 -08001309 std::unique_ptr<io::FileCollection> mFileCollection;
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001310
1311 // A vector of IFileCollections. This is mainly here to keep ownership of the collections.
Adam Lesinskia40e9722015-11-24 19:11:46 -08001312 std::vector<std::unique_ptr<io::IFileCollection>> mCollections;
Adam Lesinski64587af2016-02-18 18:33:06 -08001313
1314 // A vector of ResourceTables. This is here to retain ownership, so that the SymbolTable
1315 // can use these.
1316 std::vector<std::unique_ptr<ResourceTable>> mStaticTableIncludes;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001317};
1318
1319int link(const std::vector<StringPiece>& args) {
Adam Lesinski355f2852016-02-13 20:26:45 -08001320 LinkContext context;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001321 LinkOptions options;
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001322 Maybe<std::string> privateSymbolsPackage;
Adam Lesinski2ae4a872015-11-02 16:10:55 -08001323 Maybe<std::string> minSdkVersion, targetSdkVersion;
Adam Lesinski52364f72016-01-11 13:10:24 -08001324 Maybe<std::string> renameManifestPackage, renameInstrumentationTargetPackage;
1325 Maybe<std::string> versionCode, versionName;
1326 Maybe<std::string> customJavaPackage;
Adam Lesinskifc9570e62015-11-16 15:07:54 -08001327 std::vector<std::string> extraJavaPackages;
Adam Lesinski6a008172016-02-02 17:02:58 -08001328 Maybe<std::string> configs;
Adam Lesinski355f2852016-02-13 20:26:45 -08001329 Maybe<std::string> preferredDensity;
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08001330 Maybe<std::string> productList;
Adam Lesinski8900aa82016-01-25 22:48:15 -08001331 bool legacyXFlag = false;
1332 bool requireLocalization = false;
Adam Lesinski64587af2016-02-18 18:33:06 -08001333 bool verbose = false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001334 Flags flags = Flags()
1335 .requiredFlag("-o", "Output path", &options.outputPath)
1336 .requiredFlag("--manifest", "Path to the Android manifest to build",
1337 &options.manifestPath)
1338 .optionalFlagList("-I", "Adds an Android APK to link against", &options.includePaths)
Adam Lesinski52364f72016-01-11 13:10:24 -08001339 .optionalFlagList("-R", "Compilation unit to link, using `overlay` semantics.\n"
Adam Lesinskifb48d292015-11-07 15:52:13 -08001340 "The last conflicting resource given takes precedence.",
1341 &options.overlayFiles)
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001342 .optionalFlag("--java", "Directory in which to generate R.java",
1343 &options.generateJavaClassPath)
1344 .optionalFlag("--proguard", "Output file for generated Proguard rules",
1345 &options.generateProguardRulesPath)
1346 .optionalSwitch("--no-auto-version",
1347 "Disables automatic style and layout SDK versioning",
1348 &options.noAutoVersion)
Adam Lesinski64587af2016-02-18 18:33:06 -08001349 .optionalSwitch("--no-version-vectors",
1350 "Disables automatic versioning of vector drawables. Use this only\n"
1351 "when building with vector drawable support library",
1352 &options.noVersionVectors)
Adam Lesinski8900aa82016-01-25 22:48:15 -08001353 .optionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01",
1354 &legacyXFlag)
1355 .optionalSwitch("-z", "Require localization of strings marked 'suggested'",
1356 &requireLocalization)
Adam Lesinski6a008172016-02-02 17:02:58 -08001357 .optionalFlag("-c", "Comma separated list of configurations to include. The default\n"
1358 "is all configurations", &configs)
Adam Lesinski355f2852016-02-13 20:26:45 -08001359 .optionalFlag("--preferred-density",
1360 "Selects the closest matching density and strips out all others.",
1361 &preferredDensity)
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08001362 .optionalFlag("--product", "Comma separated list of product names to keep",
1363 &productList)
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001364 .optionalSwitch("--output-to-dir", "Outputs the APK contents to a directory specified "
1365 "by -o",
1366 &options.outputToDirectory)
Adam Lesinski2ae4a872015-11-02 16:10:55 -08001367 .optionalFlag("--min-sdk-version", "Default minimum SDK version to use for "
1368 "AndroidManifest.xml", &minSdkVersion)
1369 .optionalFlag("--target-sdk-version", "Default target SDK version to use for "
1370 "AndroidManifest.xml", &targetSdkVersion)
Adam Lesinski52364f72016-01-11 13:10:24 -08001371 .optionalFlag("--version-code", "Version code (integer) to inject into the "
1372 "AndroidManifest.xml if none is present", &versionCode)
1373 .optionalFlag("--version-name", "Version name to inject into the AndroidManifest.xml "
1374 "if none is present", &versionName)
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001375 .optionalSwitch("--static-lib", "Generate a static Android library", &options.staticLib)
Adam Lesinski64587af2016-02-18 18:33:06 -08001376 .optionalSwitch("--no-static-lib-packages",
1377 "Merge all library resources under the app's package",
1378 &options.noStaticLibPackages)
Adam Lesinskief9c5012016-01-22 14:09:53 -08001379 .optionalSwitch("--non-final-ids", "Generates R.java without the final modifier.\n"
1380 "This is implied when --static-lib is specified.",
1381 &options.generateNonFinalIds)
Adam Lesinski9ba47d82015-10-13 11:37:10 -07001382 .optionalFlag("--private-symbols", "Package name to use when generating R.java for "
Adam Lesinski2ae4a872015-11-02 16:10:55 -08001383 "private symbols.\n"
1384 "If not specified, public and private symbols will use the application's "
1385 "package name", &privateSymbolsPackage)
Adam Lesinski52364f72016-01-11 13:10:24 -08001386 .optionalFlag("--custom-package", "Custom Java package under which to generate R.java",
1387 &customJavaPackage)
Adam Lesinski83f22552015-11-07 11:51:23 -08001388 .optionalFlagList("--extra-packages", "Generate the same R.java but with different "
Adam Lesinskifc9570e62015-11-16 15:07:54 -08001389 "package names", &extraJavaPackages)
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001390 .optionalSwitch("--auto-add-overlay", "Allows the addition of new resources in "
1391 "overlays without <add-resource> tags", &options.autoAddOverlay)
Adam Lesinski52364f72016-01-11 13:10:24 -08001392 .optionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml",
1393 &renameManifestPackage)
1394 .optionalFlag("--rename-instrumentation-target-package",
1395 "Changes the name of the target package for instrumentation. Most useful "
1396 "when used\nin conjunction with --rename-manifest-package",
1397 &renameInstrumentationTargetPackage)
1398 .optionalFlagList("-0", "File extensions not to compress",
1399 &options.extensionsToNotCompress)
Adam Lesinski64587af2016-02-18 18:33:06 -08001400 .optionalSwitch("-v", "Enables verbose logging", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001401
1402 if (!flags.parse("aapt2 link", args, &std::cerr)) {
1403 return 1;
1404 }
1405
Adam Lesinski64587af2016-02-18 18:33:06 -08001406 if (verbose) {
1407 context.setVerbose(verbose);
1408 }
1409
Adam Lesinski9e10ac72015-10-16 14:37:48 -07001410 if (privateSymbolsPackage) {
1411 options.privateSymbols = util::utf8ToUtf16(privateSymbolsPackage.value());
1412 }
1413
Adam Lesinski2ae4a872015-11-02 16:10:55 -08001414 if (minSdkVersion) {
Adam Lesinski52364f72016-01-11 13:10:24 -08001415 options.manifestFixerOptions.minSdkVersionDefault =
1416 util::utf8ToUtf16(minSdkVersion.value());
Adam Lesinski2ae4a872015-11-02 16:10:55 -08001417 }
1418
1419 if (targetSdkVersion) {
Adam Lesinski52364f72016-01-11 13:10:24 -08001420 options.manifestFixerOptions.targetSdkVersionDefault =
1421 util::utf8ToUtf16(targetSdkVersion.value());
1422 }
1423
1424 if (renameManifestPackage) {
1425 options.manifestFixerOptions.renameManifestPackage =
1426 util::utf8ToUtf16(renameManifestPackage.value());
1427 }
1428
1429 if (renameInstrumentationTargetPackage) {
1430 options.manifestFixerOptions.renameInstrumentationTargetPackage =
1431 util::utf8ToUtf16(renameInstrumentationTargetPackage.value());
1432 }
1433
1434 if (versionCode) {
1435 options.manifestFixerOptions.versionCodeDefault = util::utf8ToUtf16(versionCode.value());
1436 }
1437
1438 if (versionName) {
1439 options.manifestFixerOptions.versionNameDefault = util::utf8ToUtf16(versionName.value());
1440 }
1441
1442 if (customJavaPackage) {
1443 options.customJavaPackage = util::utf8ToUtf16(customJavaPackage.value());
Adam Lesinski2ae4a872015-11-02 16:10:55 -08001444 }
1445
Adam Lesinskifc9570e62015-11-16 15:07:54 -08001446 // Populate the set of extra packages for which to generate R.java.
1447 for (std::string& extraPackage : extraJavaPackages) {
1448 // A given package can actually be a colon separated list of packages.
1449 for (StringPiece package : util::split(extraPackage, ':')) {
Adam Lesinski52364f72016-01-11 13:10:24 -08001450 options.extraJavaPackages.insert(util::utf8ToUtf16(package));
Adam Lesinskifc9570e62015-11-16 15:07:54 -08001451 }
1452 }
1453
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08001454 if (productList) {
1455 for (StringPiece product : util::tokenize<char>(productList.value(), ',')) {
1456 if (product != "" && product != "default") {
1457 options.products.insert(product.toString());
1458 }
1459 }
1460 }
1461
Adam Lesinski6a008172016-02-02 17:02:58 -08001462 AxisConfigFilter filter;
1463 if (configs) {
1464 for (const StringPiece& configStr : util::tokenize<char>(configs.value(), ',')) {
1465 ConfigDescription config;
1466 LocaleValue lv;
1467 if (lv.initFromFilterString(configStr)) {
1468 lv.writeTo(&config);
1469 } else if (!ConfigDescription::parse(configStr, &config)) {
1470 context.getDiagnostics()->error(
1471 DiagMessage() << "invalid config '" << configStr << "' for -c option");
1472 return 1;
1473 }
1474
1475 if (config.density != 0) {
1476 context.getDiagnostics()->warn(
1477 DiagMessage() << "ignoring density '" << config << "' for -c option");
1478 } else {
1479 filter.addConfig(config);
1480 }
1481 }
1482
Adam Lesinski355f2852016-02-13 20:26:45 -08001483 options.tableSplitterOptions.configFilter = &filter;
1484 }
1485
1486 if (preferredDensity) {
1487 ConfigDescription preferredDensityConfig;
1488 if (!ConfigDescription::parse(preferredDensity.value(), &preferredDensityConfig)) {
1489 context.getDiagnostics()->error(DiagMessage() << "invalid density '"
1490 << preferredDensity.value()
1491 << "' for --preferred-density option");
1492 return 1;
1493 }
1494
1495 // Clear the version that can be automatically added.
1496 preferredDensityConfig.sdkVersion = 0;
1497
1498 if (preferredDensityConfig.diff(ConfigDescription::defaultConfig())
1499 != ConfigDescription::CONFIG_DENSITY) {
1500 context.getDiagnostics()->error(DiagMessage() << "invalid preferred density '"
1501 << preferredDensity.value() << "'. "
1502 << "Preferred density must only be a density value");
1503 return 1;
1504 }
1505 options.tableSplitterOptions.preferredDensity = preferredDensityConfig.density;
Adam Lesinski6a008172016-02-02 17:02:58 -08001506 }
1507
1508 LinkCommand cmd(&context, options);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001509 return cmd.run(flags.getArgs());
1510}
1511
1512} // namespace aapt