1 /*
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 "Compile.h"
18
19 #include <dirent.h>
20
21 #include <string>
22
23 #include "ResourceParser.h"
24 #include "ResourceTable.h"
25 #include "android-base/errors.h"
26 #include "android-base/file.h"
27 #include "android-base/utf8.h"
28 #include "androidfw/ConfigDescription.h"
29 #include "androidfw/IDiagnostics.h"
30 #include "androidfw/StringPiece.h"
31 #include "cmd/Util.h"
32 #include "compile/IdAssigner.h"
33 #include "compile/InlineXmlFormatParser.h"
34 #include "compile/Png.h"
35 #include "compile/PseudolocaleGenerator.h"
36 #include "compile/XmlIdCollector.h"
37 #include "format/Archive.h"
38 #include "format/Container.h"
39 #include "format/proto/ProtoSerialize.h"
40 #include "google/protobuf/io/coded_stream.h"
41 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
42 #include "io/BigBufferStream.h"
43 #include "io/FileStream.h"
44 #include "io/FileSystem.h"
45 #include "io/StringStream.h"
46 #include "io/Util.h"
47 #include "io/ZipArchive.h"
48 #include "trace/TraceBuffer.h"
49 #include "util/Files.h"
50 #include "util/Util.h"
51 #include "xml/XmlDom.h"
52 #include "xml/XmlPullParser.h"
53
54 using ::aapt::io::FileInputStream;
55 using ::aapt::text::Printer;
56 using ::android::ConfigDescription;
57 using ::android::StringPiece;
58 using ::android::base::SystemErrorCodeToString;
59 using ::google::protobuf::io::CopyingOutputStreamAdaptor;
60
61 namespace aapt {
62
63 struct ResourcePathData {
64 android::Source source;
65 std::string resource_dir;
66 std::string name;
67 std::string extension;
68
69 // Original config str. We keep this because when we parse the config, we may add on
70 // version qualifiers. We want to preserve the original input so the output is easily
71 // computed before hand.
72 std::string config_str;
73 ConfigDescription config;
74 };
75
76 // Resource file paths are expected to look like: [--/res/]type[-config]/name
ExtractResourcePathData(const std::string & path,const char dir_sep,std::string * out_error,const CompileOptions & options)77 static std::optional<ResourcePathData> ExtractResourcePathData(const std::string& path,
78 const char dir_sep,
79 std::string* out_error,
80 const CompileOptions& options) {
81 std::vector<std::string> parts = util::Split(path, dir_sep);
82 if (parts.size() < 2) {
83 if (out_error) *out_error = "bad resource path";
84 return {};
85 }
86
87 std::string& dir = parts[parts.size() - 2];
88 StringPiece dir_str = dir;
89
90 StringPiece config_str;
91 ConfigDescription config;
92 size_t dash_pos = dir.find('-');
93 if (dash_pos != std::string::npos) {
94 config_str = dir_str.substr(dash_pos + 1, dir.size() - (dash_pos + 1));
95 if (!ConfigDescription::Parse(config_str, &config)) {
96 if (out_error) {
97 std::stringstream err_str;
98 err_str << "invalid configuration '" << config_str << "'";
99 *out_error = err_str.str();
100 }
101 return {};
102 }
103 dir_str = dir_str.substr(0, dash_pos);
104 }
105
106 std::string& filename = parts[parts.size() - 1];
107 StringPiece name = filename;
108 StringPiece extension;
109
110 const std::string kNinePng = ".9.png";
111 if (filename.size() > kNinePng.size()
112 && std::equal(kNinePng.rbegin(), kNinePng.rend(), filename.rbegin())) {
113 // Split on .9.png if this extension is present at the end of the file path
114 name = name.substr(0, filename.size() - kNinePng.size());
115 extension = "9.png";
116 } else {
117 // Split on the last period occurrence
118 size_t dot_pos = filename.rfind('.');
119 if (dot_pos != std::string::npos) {
120 extension = name.substr(dot_pos + 1, filename.size() - (dot_pos + 1));
121 name = name.substr(0, dot_pos);
122 }
123 }
124
125 const android::Source res_path =
126 options.source_path ? StringPiece(options.source_path.value()) : StringPiece(path);
127
128 return ResourcePathData{res_path,
129 std::string(dir_str),
130 std::string(name),
131 std::string(extension),
132 std::string(config_str),
133 config};
134 }
135
BuildIntermediateContainerFilename(const ResourcePathData & data)136 static std::string BuildIntermediateContainerFilename(const ResourcePathData& data) {
137 std::stringstream name;
138 name << data.resource_dir;
139 if (!data.config_str.empty()) {
140 name << "-" << data.config_str;
141 }
142 name << "_" << data.name;
143 if (!data.extension.empty()) {
144 name << "." << data.extension;
145 }
146 name << ".flat";
147 return name.str();
148 }
149
CompileTable(IAaptContext * context,const CompileOptions & options,const ResourcePathData & path_data,io::IFile * file,IArchiveWriter * writer,const std::string & output_path)150 static bool CompileTable(IAaptContext* context, const CompileOptions& options,
151 const ResourcePathData& path_data, io::IFile* file, IArchiveWriter* writer,
152 const std::string& output_path) {
153 TRACE_CALL();
154 // Filenames starting with "donottranslate" are not localizable
155 bool translatable_file = path_data.name.find("donottranslate") != 0;
156 ResourceTable table;
157 {
158 auto fin = file->OpenInputStream();
159 if (fin->HadError()) {
160 context->GetDiagnostics()->Error(android::DiagMessage(path_data.source)
161 << "failed to open file: " << fin->GetError());
162 return false;
163 }
164
165 // Parse the values file from XML.
166 xml::XmlPullParser xml_parser(fin.get());
167
168 ResourceParserOptions parser_options;
169 parser_options.error_on_positional_arguments = !options.legacy_mode;
170 parser_options.preserve_visibility_of_styleables = options.preserve_visibility_of_styleables;
171 parser_options.translatable = translatable_file;
172
173 // If visibility was forced, we need to use it when creating a new resource and also error if
174 // we try to parse the <public>, <public-group>, <java-symbol> or <symbol> tags.
175 parser_options.visibility = options.visibility;
176
177 ResourceParser res_parser(context->GetDiagnostics(), &table, path_data.source, path_data.config,
178 parser_options);
179 if (!res_parser.Parse(&xml_parser)) {
180 return false;
181 }
182 }
183
184 if (options.pseudolocalize && translatable_file) {
185 // Generate pseudo-localized strings (en-XA and ar-XB).
186 // These are created as weak symbols, and are only generated from default
187 // configuration
188 // strings and plurals.
189 PseudolocaleGenerator pseudolocale_generator;
190 if (!pseudolocale_generator.Consume(context, &table)) {
191 return false;
192 }
193 }
194
195 // Create the file/zip entry.
196 if (!writer->StartEntry(output_path, 0)) {
197 context->GetDiagnostics()->Error(android::DiagMessage(output_path) << "failed to open");
198 return false;
199 }
200
201 // Make sure CopyingOutputStreamAdaptor is deleted before we call writer->FinishEntry().
202 {
203 // Wrap our IArchiveWriter with an adaptor that implements the ZeroCopyOutputStream interface.
204 CopyingOutputStreamAdaptor copying_adaptor(writer);
205 ContainerWriter container_writer(©ing_adaptor, 1u);
206
207 pb::ResourceTable pb_table;
208 SerializeTableToPb(table, &pb_table, context->GetDiagnostics());
209 if (!container_writer.AddResTableEntry(pb_table)) {
210 context->GetDiagnostics()->Error(android::DiagMessage(output_path) << "failed to write");
211 return false;
212 }
213 }
214
215 if (!writer->FinishEntry()) {
216 context->GetDiagnostics()->Error(android::DiagMessage(output_path) << "failed to finish entry");
217 return false;
218 }
219
220 if (options.generate_text_symbols_path) {
221 io::FileOutputStream fout_text(options.generate_text_symbols_path.value());
222
223 if (fout_text.HadError()) {
224 context->GetDiagnostics()->Error(android::DiagMessage()
225 << "failed writing to'"
226 << options.generate_text_symbols_path.value()
227 << "': " << fout_text.GetError());
228 return false;
229 }
230
231 Printer r_txt_printer(&fout_text);
232 for (const auto& package : table.packages) {
233 // Only print resources defined locally, e.g. don't write android attributes.
234 if (package->name.empty()) {
235 for (const auto& type : package->types) {
236 for (const auto& entry : type->entries) {
237 // Check access modifiers.
238 switch (entry->visibility.level) {
239 case Visibility::Level::kUndefined :
240 r_txt_printer.Print("default ");
241 break;
242 case Visibility::Level::kPublic :
243 r_txt_printer.Print("public ");
244 break;
245 case Visibility::Level::kPrivate :
246 r_txt_printer.Print("private ");
247 }
248
249 if (type->named_type.type != ResourceType::kStyleable) {
250 r_txt_printer.Print("int ");
251 r_txt_printer.Print(type->named_type.to_string());
252 r_txt_printer.Print(" ");
253 r_txt_printer.Println(entry->name);
254 } else {
255 r_txt_printer.Print("int[] styleable ");
256 r_txt_printer.Println(entry->name);
257
258 if (!entry->values.empty()) {
259 auto styleable =
260 static_cast<const Styleable*>(entry->values.front()->value.get());
261 for (const auto& attr : styleable->entries) {
262 // The visibility of the children under the styleable does not matter as they are
263 // nested under their parent and use its visibility.
264 r_txt_printer.Print("default int styleable ");
265 r_txt_printer.Print(entry->name);
266 // If the package name is present, also include it in the mangled name (e.g.
267 // "android")
268 if (!attr.name.value().package.empty()) {
269 r_txt_printer.Print("_");
270 r_txt_printer.Print(MakePackageSafeName(attr.name.value().package));
271 }
272 r_txt_printer.Print("_");
273 r_txt_printer.Println(attr.name.value().entry);
274 }
275 }
276 }
277 }
278 }
279 }
280 }
281 }
282
283 return true;
284 }
285
WriteHeaderAndDataToWriter(StringPiece output_path,const ResourceFile & file,io::KnownSizeInputStream * in,IArchiveWriter * writer,android::IDiagnostics * diag)286 static bool WriteHeaderAndDataToWriter(StringPiece output_path, const ResourceFile& file,
287 io::KnownSizeInputStream* in, IArchiveWriter* writer,
288 android::IDiagnostics* diag) {
289 TRACE_CALL();
290 // Start the entry so we can write the header.
291 if (!writer->StartEntry(output_path, 0)) {
292 diag->Error(android::DiagMessage(output_path) << "failed to open file");
293 return false;
294 }
295
296 // Make sure CopyingOutputStreamAdaptor is deleted before we call writer->FinishEntry().
297 {
298 // Wrap our IArchiveWriter with an adaptor that implements the ZeroCopyOutputStream interface.
299 CopyingOutputStreamAdaptor copying_adaptor(writer);
300 ContainerWriter container_writer(©ing_adaptor, 1u);
301
302 pb::internal::CompiledFile pb_compiled_file;
303 SerializeCompiledFileToPb(file, &pb_compiled_file);
304
305 if (!container_writer.AddResFileEntry(pb_compiled_file, in)) {
306 diag->Error(android::DiagMessage(output_path) << "failed to write entry data");
307 return false;
308 }
309 }
310
311 if (!writer->FinishEntry()) {
312 diag->Error(android::DiagMessage(output_path) << "failed to finish writing data");
313 return false;
314 }
315 return true;
316 }
317
FlattenXmlToOutStream(StringPiece output_path,const xml::XmlResource & xmlres,ContainerWriter * container_writer,android::IDiagnostics * diag)318 static bool FlattenXmlToOutStream(StringPiece output_path, const xml::XmlResource& xmlres,
319 ContainerWriter* container_writer, android::IDiagnostics* diag) {
320 pb::internal::CompiledFile pb_compiled_file;
321 SerializeCompiledFileToPb(xmlres.file, &pb_compiled_file);
322
323 pb::XmlNode pb_xml_node;
324 SerializeXmlToPb(*xmlres.root, &pb_xml_node);
325
326 std::string serialized_xml = pb_xml_node.SerializeAsString();
327 io::StringInputStream serialized_in(serialized_xml);
328
329 if (!container_writer->AddResFileEntry(pb_compiled_file, &serialized_in)) {
330 diag->Error(android::DiagMessage(output_path) << "failed to write entry data");
331 return false;
332 }
333 return true;
334 }
335
IsValidFile(IAaptContext * context,const std::string & input_path)336 static bool IsValidFile(IAaptContext* context, const std::string& input_path) {
337 const file::FileType file_type = file::GetFileType(input_path);
338 if (file_type != file::FileType::kRegular && file_type != file::FileType::kSymlink) {
339 if (file_type == file::FileType::kDirectory) {
340 context->GetDiagnostics()->Error(android::DiagMessage(input_path)
341 << "resource file cannot be a directory");
342 } else if (file_type == file::FileType::kNonExistant) {
343 context->GetDiagnostics()->Error(android::DiagMessage(input_path) << "file not found");
344 } else {
345 context->GetDiagnostics()->Error(android::DiagMessage(input_path)
346 << "not a valid resource file");
347 }
348 return false;
349 }
350 return true;
351 }
352
CompileXml(IAaptContext * context,const CompileOptions & options,const ResourcePathData & path_data,io::IFile * file,IArchiveWriter * writer,const std::string & output_path)353 static bool CompileXml(IAaptContext* context, const CompileOptions& options,
354 const ResourcePathData& path_data, io::IFile* file, IArchiveWriter* writer,
355 const std::string& output_path) {
356 TRACE_CALL();
357 if (context->IsVerbose()) {
358 context->GetDiagnostics()->Note(android::DiagMessage(path_data.source) << "compiling XML");
359 }
360
361 std::unique_ptr<xml::XmlResource> xmlres;
362 {
363 auto fin = file->OpenInputStream();
364 if (fin->HadError()) {
365 context->GetDiagnostics()->Error(android::DiagMessage(path_data.source)
366 << "failed to open file: " << fin->GetError());
367 return false;
368 }
369
370 xmlres = xml::Inflate(fin.get(), context->GetDiagnostics(), path_data.source);
371 if (!xmlres) {
372 return false;
373 }
374 }
375
376 xmlres->file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
377 xmlres->file.config = path_data.config;
378 xmlres->file.source = path_data.source;
379 xmlres->file.type = ResourceFile::Type::kProtoXml;
380
381 // Collect IDs that are defined here.
382 XmlIdCollector collector;
383 if (!collector.Consume(context, xmlres.get())) {
384 return false;
385 }
386
387 // Look for and process any <aapt:attr> tags and create sub-documents.
388 InlineXmlFormatParser inline_xml_format_parser;
389 if (!inline_xml_format_parser.Consume(context, xmlres.get())) {
390 return false;
391 }
392
393 // Start the entry so we can write the header.
394 if (!writer->StartEntry(output_path, 0)) {
395 context->GetDiagnostics()->Error(android::DiagMessage(output_path) << "failed to open file");
396 return false;
397 }
398
399 std::vector<std::unique_ptr<xml::XmlResource>>& inline_documents =
400 inline_xml_format_parser.GetExtractedInlineXmlDocuments();
401
402 // Make sure CopyingOutputStreamAdaptor is deleted before we call writer->FinishEntry().
403 {
404 // Wrap our IArchiveWriter with an adaptor that implements the ZeroCopyOutputStream interface.
405 CopyingOutputStreamAdaptor copying_adaptor(writer);
406 ContainerWriter container_writer(©ing_adaptor, 1u + inline_documents.size());
407
408 if (!FlattenXmlToOutStream(output_path, *xmlres, &container_writer,
409 context->GetDiagnostics())) {
410 return false;
411 }
412
413 for (const std::unique_ptr<xml::XmlResource>& inline_xml_doc : inline_documents) {
414 if (!FlattenXmlToOutStream(output_path, *inline_xml_doc, &container_writer,
415 context->GetDiagnostics())) {
416 return false;
417 }
418 }
419 }
420
421 if (!writer->FinishEntry()) {
422 context->GetDiagnostics()->Error(android::DiagMessage(output_path)
423 << "failed to finish writing data");
424 return false;
425 }
426
427 if (options.generate_text_symbols_path) {
428 io::FileOutputStream fout_text(options.generate_text_symbols_path.value());
429
430 if (fout_text.HadError()) {
431 context->GetDiagnostics()->Error(android::DiagMessage()
432 << "failed writing to'"
433 << options.generate_text_symbols_path.value()
434 << "': " << fout_text.GetError());
435 return false;
436 }
437
438 Printer r_txt_printer(&fout_text);
439 for (const auto& res : xmlres->file.exported_symbols) {
440 r_txt_printer.Print("default int id ");
441 r_txt_printer.Println(res.name.entry);
442 }
443
444 // And print ourselves.
445 r_txt_printer.Print("default int ");
446 r_txt_printer.Print(path_data.resource_dir);
447 r_txt_printer.Print(" ");
448 r_txt_printer.Println(path_data.name);
449 }
450
451 return true;
452 }
453
CompilePng(IAaptContext * context,const CompileOptions & options,const ResourcePathData & path_data,io::IFile * file,IArchiveWriter * writer,const std::string & output_path)454 static bool CompilePng(IAaptContext* context, const CompileOptions& options,
455 const ResourcePathData& path_data, io::IFile* file, IArchiveWriter* writer,
456 const std::string& output_path) {
457 TRACE_CALL();
458 if (context->IsVerbose()) {
459 context->GetDiagnostics()->Note(android::DiagMessage(path_data.source) << "compiling PNG");
460 }
461
462 android::BigBuffer buffer(4096);
463 ResourceFile res_file;
464 res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
465 res_file.config = path_data.config;
466 res_file.source = path_data.source;
467 res_file.type = ResourceFile::Type::kPng;
468
469 {
470 auto data = file->OpenAsData();
471 if (!data) {
472 context->GetDiagnostics()->Error(android::DiagMessage(path_data.source)
473 << "failed to open file ");
474 return false;
475 }
476
477 android::BigBuffer crunched_png_buffer(4096);
478 io::BigBufferOutputStream crunched_png_buffer_out(&crunched_png_buffer);
479
480 // Ensure that we only keep the chunks we care about if we end up
481 // using the original PNG instead of the crunched one.
482 const StringPiece content(reinterpret_cast<const char*>(data->data()), data->size());
483 PngChunkFilter png_chunk_filter(content);
484 std::unique_ptr<Image> image = ReadPng(context, path_data.source, &png_chunk_filter);
485 if (!image) {
486 return false;
487 }
488
489 std::unique_ptr<NinePatch> nine_patch;
490 if (path_data.extension == "9.png") {
491 std::string err;
492 nine_patch = NinePatch::Create(image->rows.get(), image->width, image->height, &err);
493 if (!nine_patch) {
494 context->GetDiagnostics()->Error(android::DiagMessage() << err);
495 return false;
496 }
497
498 // Remove the 1px border around the NinePatch.
499 // Basically the row array is shifted up by 1, and the length is treated
500 // as height - 2.
501 // For each row, shift the array to the left by 1, and treat the length as
502 // width - 2.
503 image->width -= 2;
504 image->height -= 2;
505 memmove(image->rows.get(), image->rows.get() + 1, image->height * sizeof(uint8_t**));
506 for (int32_t h = 0; h < image->height; h++) {
507 memmove(image->rows[h], image->rows[h] + 4, image->width * 4);
508 }
509
510 if (context->IsVerbose()) {
511 context->GetDiagnostics()->Note(android::DiagMessage(path_data.source)
512 << "9-patch: " << *nine_patch);
513 }
514 }
515
516 // Write the crunched PNG.
517 if (!WritePng(context, image.get(), nine_patch.get(), &crunched_png_buffer_out, {})) {
518 return false;
519 }
520
521 if (nine_patch != nullptr ||
522 crunched_png_buffer_out.ByteCount() <= png_chunk_filter.ByteCount()) {
523 // No matter what, we must use the re-encoded PNG, even if it is larger.
524 // 9-patch images must be re-encoded since their borders are stripped.
525 buffer.AppendBuffer(std::move(crunched_png_buffer));
526 } else {
527 // The re-encoded PNG is larger than the original, and there is
528 // no mandatory transformation. Use the original.
529 if (context->IsVerbose()) {
530 context->GetDiagnostics()->Note(android::DiagMessage(path_data.source)
531 << "original PNG is smaller than crunched PNG"
532 << ", using original");
533 }
534
535 png_chunk_filter.Rewind();
536 android::BigBuffer filtered_png_buffer(4096);
537 io::BigBufferOutputStream filtered_png_buffer_out(&filtered_png_buffer);
538 io::Copy(&filtered_png_buffer_out, &png_chunk_filter);
539 buffer.AppendBuffer(std::move(filtered_png_buffer));
540 }
541
542 if (context->IsVerbose()) {
543 // For debugging only, use the legacy PNG cruncher and compare the resulting file sizes.
544 // This will help catch exotic cases where the new code may generate larger PNGs.
545 std::stringstream legacy_stream{std::string(content)};
546 android::BigBuffer legacy_buffer(4096);
547 Png png(context->GetDiagnostics());
548 if (!png.process(path_data.source, &legacy_stream, &legacy_buffer, {})) {
549 return false;
550 }
551
552 context->GetDiagnostics()->Note(android::DiagMessage(path_data.source)
553 << "legacy=" << legacy_buffer.size()
554 << " new=" << buffer.size());
555 }
556 }
557
558 io::BigBufferInputStream buffer_in(&buffer);
559 return WriteHeaderAndDataToWriter(output_path, res_file, &buffer_in, writer,
560 context->GetDiagnostics());
561 }
562
CompileFile(IAaptContext * context,const CompileOptions & options,const ResourcePathData & path_data,io::IFile * file,IArchiveWriter * writer,const std::string & output_path)563 static bool CompileFile(IAaptContext* context, const CompileOptions& options,
564 const ResourcePathData& path_data, io::IFile* file, IArchiveWriter* writer,
565 const std::string& output_path) {
566 TRACE_CALL();
567 if (context->IsVerbose()) {
568 context->GetDiagnostics()->Note(android::DiagMessage(path_data.source) << "compiling file");
569 }
570
571 ResourceFile res_file;
572 res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
573 res_file.config = path_data.config;
574 res_file.source = path_data.source;
575 res_file.type = ResourceFile::Type::kUnknown;
576
577 auto data = file->OpenAsData();
578 if (!data) {
579 context->GetDiagnostics()->Error(android::DiagMessage(path_data.source)
580 << "failed to open file ");
581 return false;
582 }
583
584 return WriteHeaderAndDataToWriter(output_path, res_file, data.get(), writer,
585 context->GetDiagnostics());
586 }
587
588 class CompileContext : public IAaptContext {
589 public:
CompileContext(android::IDiagnostics * diagnostics)590 explicit CompileContext(android::IDiagnostics* diagnostics) : diagnostics_(diagnostics) {
591 }
592
GetPackageType()593 PackageType GetPackageType() override {
594 // Every compilation unit starts as an app and then gets linked as potentially something else.
595 return PackageType::kApp;
596 }
597
SetVerbose(bool val)598 void SetVerbose(bool val) {
599 verbose_ = val;
600 }
601
IsVerbose()602 bool IsVerbose() override {
603 return verbose_;
604 }
605
GetDiagnostics()606 android::IDiagnostics* GetDiagnostics() override {
607 return diagnostics_;
608 }
609
GetNameMangler()610 NameMangler* GetNameMangler() override {
611 UNIMPLEMENTED(FATAL) << "No name mangling should be needed in compile phase";
612 return nullptr;
613 }
614
GetCompilationPackage()615 const std::string& GetCompilationPackage() override {
616 static std::string empty;
617 return empty;
618 }
619
GetPackageId()620 uint8_t GetPackageId() override {
621 return 0x0;
622 }
623
GetExternalSymbols()624 SymbolTable* GetExternalSymbols() override {
625 UNIMPLEMENTED(FATAL) << "No symbols should be needed in compile phase";
626 return nullptr;
627 }
628
GetMinSdkVersion()629 int GetMinSdkVersion() override {
630 return 0;
631 }
632
GetSplitNameDependencies()633 const std::set<std::string>& GetSplitNameDependencies() override {
634 UNIMPLEMENTED(FATAL) << "No Split Name Dependencies be needed in compile phase";
635 static std::set<std::string> empty;
636 return empty;
637 }
638
639 private:
640 DISALLOW_COPY_AND_ASSIGN(CompileContext);
641
642 android::IDiagnostics* diagnostics_;
643 bool verbose_ = false;
644 };
645
Compile(IAaptContext * context,io::IFileCollection * inputs,IArchiveWriter * output_writer,CompileOptions & options)646 int Compile(IAaptContext* context, io::IFileCollection* inputs, IArchiveWriter* output_writer,
647 CompileOptions& options) {
648 TRACE_CALL();
649 bool error = false;
650
651 // Iterate over the input files in a stable, platform-independent manner
652 auto file_iterator = inputs->Iterator();
653 while (file_iterator->HasNext()) {
654 auto file = file_iterator->Next();
655 std::string path = file->GetSource().path;
656
657 // Skip hidden input files
658 if (file::IsHidden(path)) {
659 continue;
660 }
661
662 if (!options.res_zip && !IsValidFile(context, path)) {
663 error = true;
664 continue;
665 }
666
667 // Extract resource type information from the full path
668 std::string err_str;
669 ResourcePathData path_data;
670 if (auto maybe_path_data = ExtractResourcePathData(
671 path, inputs->GetDirSeparator(), &err_str, options)) {
672 path_data = maybe_path_data.value();
673 } else {
674 context->GetDiagnostics()->Error(android::DiagMessage(file->GetSource()) << err_str);
675 error = true;
676 continue;
677 }
678
679 // Determine how to compile the file based on its type.
680 auto compile_func = &CompileFile;
681 if (path_data.resource_dir == "values" && path_data.extension == "xml") {
682 compile_func = &CompileTable;
683 // We use a different extension (not necessary anymore, but avoids altering the existing
684 // build system logic).
685 path_data.extension = "arsc";
686
687 } else if (const ResourceType* type = ParseResourceType(path_data.resource_dir)) {
688 if (*type != ResourceType::kRaw) {
689 if (*type == ResourceType::kXml || path_data.extension == "xml") {
690 compile_func = &CompileXml;
691 } else if ((!options.no_png_crunch && path_data.extension == "png")
692 || path_data.extension == "9.png") {
693 compile_func = &CompilePng;
694 }
695 }
696 } else {
697 context->GetDiagnostics()->Error(android::DiagMessage()
698 << "invalid file path '" << path_data.source << "'");
699 error = true;
700 continue;
701 }
702
703 // Treat periods as a reserved character that should not be present in a file name
704 // Legacy support for AAPT which did not reserve periods
705 if (compile_func != &CompileFile && !options.legacy_mode
706 && std::count(path_data.name.begin(), path_data.name.end(), '.') != 0) {
707 error = true;
708 context->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
709 << "file name cannot contain '.' other than for"
710 << " specifying the extension");
711 continue;
712 }
713
714 const std::string out_path = BuildIntermediateContainerFilename(path_data);
715 if (!compile_func(context, options, path_data, file, output_writer, out_path)) {
716 context->GetDiagnostics()->Error(android::DiagMessage(file->GetSource())
717 << "file failed to compile");
718 error = true;
719 }
720 }
721
722 return error ? 1 : 0;
723 }
724
Action(const std::vector<std::string> & args)725 int CompileCommand::Action(const std::vector<std::string>& args) {
726 TRACE_FLUSH(trace_folder_? trace_folder_.value() : "", "CompileCommand::Action");
727 CompileContext context(diagnostic_);
728 context.SetVerbose(options_.verbose);
729
730 if (visibility_) {
731 if (visibility_.value() == "public") {
732 options_.visibility = Visibility::Level::kPublic;
733 } else if (visibility_.value() == "private") {
734 options_.visibility = Visibility::Level::kPrivate;
735 } else if (visibility_.value() == "default") {
736 options_.visibility = Visibility::Level::kUndefined;
737 } else {
738 context.GetDiagnostics()->Error(android::DiagMessage()
739 << "Unrecognized visibility level passes to --visibility: '"
740 << visibility_.value()
741 << "'. Accepted levels: public, private, default");
742 return 1;
743 }
744 }
745
746 std::unique_ptr<io::IFileCollection> file_collection;
747
748 // Collect the resources files to compile
749 if (options_.res_dir && options_.res_zip) {
750 context.GetDiagnostics()->Error(android::DiagMessage()
751 << "only one of --dir and --zip can be specified");
752 return 1;
753 } else if ((options_.res_dir || options_.res_zip) &&
754 options_.source_path && args.size() > 1) {
755 context.GetDiagnostics()->Error(android::DiagMessage(kPath)
756 << "Cannot use an overriding source path with multiple files.");
757 return 1;
758 } else if (options_.res_dir) {
759 if (!args.empty()) {
760 context.GetDiagnostics()->Error(android::DiagMessage() << "files given but --dir specified");
761 Usage(&std::cerr);
762 return 1;
763 }
764
765 // Load the files from the res directory
766 std::string err;
767 file_collection = io::FileCollection::Create(options_.res_dir.value(), &err);
768 if (!file_collection) {
769 context.GetDiagnostics()->Error(android::DiagMessage(options_.res_dir.value()) << err);
770 return 1;
771 }
772 } else if (options_.res_zip) {
773 if (!args.empty()) {
774 context.GetDiagnostics()->Error(android::DiagMessage() << "files given but --zip specified");
775 Usage(&std::cerr);
776 return 1;
777 }
778
779 // Load a zip file containing a res directory
780 std::string err;
781 file_collection = io::ZipFileCollection::Create(options_.res_zip.value(), &err);
782 if (!file_collection) {
783 context.GetDiagnostics()->Error(android::DiagMessage(options_.res_zip.value()) << err);
784 return 1;
785 }
786 } else {
787 auto collection = util::make_unique<io::FileCollection>();
788
789 // Collect data from the path for each input file.
790 std::vector<std::string> sorted_args = args;
791 std::sort(sorted_args.begin(), sorted_args.end());
792
793 for (const std::string& arg : sorted_args) {
794 collection->InsertFile(arg);
795 }
796
797 file_collection = std::move(collection);
798 }
799
800 std::unique_ptr<IArchiveWriter> archive_writer;
801 file::FileType output_file_type = file::GetFileType(options_.output_path);
802 if (output_file_type == file::FileType::kDirectory) {
803 archive_writer = CreateDirectoryArchiveWriter(context.GetDiagnostics(), options_.output_path);
804 } else {
805 archive_writer = CreateZipFileArchiveWriter(context.GetDiagnostics(), options_.output_path);
806 }
807
808 if (!archive_writer) {
809 return 1;
810 }
811
812 return Compile(&context, file_collection.get(), archive_writer.get(), options_);
813 }
814
815 } // namespace aapt
816