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