AAPT2: Rename to match new style
Use Google3 naming style to match new
projects' and open source google projects' style.
Preferred to do this in a massive CL so as to avoid
style inconsistencies that plague legacy code bases.
This is a relatively NEW code base, may as well keep
it up to date.
Test: name/style refactor - existing tests pass
Change-Id: Ie80ecb78d46ec53efdfca2336bb57d96cbb7fb87
diff --git a/tools/aapt2/flatten/Archive.cpp b/tools/aapt2/flatten/Archive.cpp
index ae08f65..47de0a3 100644
--- a/tools/aapt2/flatten/Archive.cpp
+++ b/tools/aapt2/flatten/Archive.cpp
@@ -15,131 +15,139 @@
*/
#include "flatten/Archive.h"
-#include "util/Files.h"
-#include "util/StringPiece.h"
-#include <ziparchive/zip_writer.h>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
+#include "android-base/macros.h"
+#include "ziparchive/zip_writer.h"
+
+#include "util/Files.h"
+#include "util/StringPiece.h"
+
namespace aapt {
namespace {
-struct DirectoryWriter : public IArchiveWriter {
- std::string mOutDir;
- std::unique_ptr<FILE, decltype(fclose)*> mFile = {nullptr, fclose};
+class DirectoryWriter : public IArchiveWriter {
+ public:
+ DirectoryWriter() = default;
- bool open(IDiagnostics* diag, const StringPiece& outDir) {
- mOutDir = outDir.toString();
- file::FileType type = file::getFileType(mOutDir);
+ bool Open(IDiagnostics* diag, const StringPiece& out_dir) {
+ dir_ = out_dir.ToString();
+ file::FileType type = file::GetFileType(dir_);
if (type == file::FileType::kNonexistant) {
- diag->error(DiagMessage() << "directory " << mOutDir
- << " does not exist");
+ diag->Error(DiagMessage() << "directory " << dir_ << " does not exist");
return false;
} else if (type != file::FileType::kDirectory) {
- diag->error(DiagMessage() << mOutDir << " is not a directory");
+ diag->Error(DiagMessage() << dir_ << " is not a directory");
return false;
}
return true;
}
- bool startEntry(const StringPiece& path, uint32_t flags) override {
- if (mFile) {
+ bool StartEntry(const StringPiece& path, uint32_t flags) override {
+ if (file_) {
return false;
}
- std::string fullPath = mOutDir;
- file::appendPath(&fullPath, path);
- file::mkdirs(file::getStem(fullPath));
+ std::string full_path = dir_;
+ file::AppendPath(&full_path, path);
+ file::mkdirs(file::GetStem(full_path));
- mFile = {fopen(fullPath.data(), "wb"), fclose};
- if (!mFile) {
+ file_ = {fopen(full_path.data(), "wb"), fclose};
+ if (!file_) {
return false;
}
return true;
}
- bool writeEntry(const BigBuffer& buffer) override {
- if (!mFile) {
+ bool WriteEntry(const BigBuffer& buffer) override {
+ if (!file_) {
return false;
}
for (const BigBuffer::Block& b : buffer) {
- if (fwrite(b.buffer.get(), 1, b.size, mFile.get()) != b.size) {
- mFile.reset(nullptr);
+ if (fwrite(b.buffer.get(), 1, b.size, file_.get()) != b.size) {
+ file_.reset(nullptr);
return false;
}
}
return true;
}
- bool writeEntry(const void* data, size_t len) override {
- if (fwrite(data, 1, len, mFile.get()) != len) {
- mFile.reset(nullptr);
+ bool WriteEntry(const void* data, size_t len) override {
+ if (fwrite(data, 1, len, file_.get()) != len) {
+ file_.reset(nullptr);
return false;
}
return true;
}
- bool finishEntry() override {
- if (!mFile) {
+ bool FinishEntry() override {
+ if (!file_) {
return false;
}
- mFile.reset(nullptr);
+ file_.reset(nullptr);
return true;
}
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(DirectoryWriter);
+
+ std::string dir_;
+ std::unique_ptr<FILE, decltype(fclose)*> file_ = {nullptr, fclose};
};
-struct ZipFileWriter : public IArchiveWriter {
- std::unique_ptr<FILE, decltype(fclose)*> mFile = {nullptr, fclose};
- std::unique_ptr<ZipWriter> mWriter;
+class ZipFileWriter : public IArchiveWriter {
+ public:
+ ZipFileWriter() = default;
- bool open(IDiagnostics* diag, const StringPiece& path) {
- mFile = {fopen(path.data(), "w+b"), fclose};
- if (!mFile) {
- diag->error(DiagMessage() << "failed to open " << path << ": "
+ bool Open(IDiagnostics* diag, const StringPiece& path) {
+ file_ = {fopen(path.data(), "w+b"), fclose};
+ if (!file_) {
+ diag->Error(DiagMessage() << "failed to Open " << path << ": "
<< strerror(errno));
return false;
}
- mWriter = util::make_unique<ZipWriter>(mFile.get());
+ writer_ = util::make_unique<ZipWriter>(file_.get());
return true;
}
- bool startEntry(const StringPiece& path, uint32_t flags) override {
- if (!mWriter) {
+ bool StartEntry(const StringPiece& path, uint32_t flags) override {
+ if (!writer_) {
return false;
}
- size_t zipFlags = 0;
+ size_t zip_flags = 0;
if (flags & ArchiveEntry::kCompress) {
- zipFlags |= ZipWriter::kCompress;
+ zip_flags |= ZipWriter::kCompress;
}
if (flags & ArchiveEntry::kAlign) {
- zipFlags |= ZipWriter::kAlign32;
+ zip_flags |= ZipWriter::kAlign32;
}
- int32_t result = mWriter->StartEntry(path.data(), zipFlags);
+ int32_t result = writer_->StartEntry(path.data(), zip_flags);
if (result != 0) {
return false;
}
return true;
}
- bool writeEntry(const void* data, size_t len) override {
- int32_t result = mWriter->WriteBytes(data, len);
+ bool WriteEntry(const void* data, size_t len) override {
+ int32_t result = writer_->WriteBytes(data, len);
if (result != 0) {
return false;
}
return true;
}
- bool writeEntry(const BigBuffer& buffer) override {
+ bool WriteEntry(const BigBuffer& buffer) override {
for (const BigBuffer::Block& b : buffer) {
- int32_t result = mWriter->WriteBytes(b.buffer.get(), b.size);
+ int32_t result = writer_->WriteBytes(b.buffer.get(), b.size);
if (result != 0) {
return false;
}
@@ -147,8 +155,8 @@
return true;
}
- bool finishEntry() override {
- int32_t result = mWriter->FinishEntry();
+ bool FinishEntry() override {
+ int32_t result = writer_->FinishEntry();
if (result != 0) {
return false;
}
@@ -156,28 +164,34 @@
}
virtual ~ZipFileWriter() {
- if (mWriter) {
- mWriter->Finish();
+ if (writer_) {
+ writer_->Finish();
}
}
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ZipFileWriter);
+
+ std::unique_ptr<FILE, decltype(fclose)*> file_ = {nullptr, fclose};
+ std::unique_ptr<ZipWriter> writer_;
};
} // namespace
-std::unique_ptr<IArchiveWriter> createDirectoryArchiveWriter(
+std::unique_ptr<IArchiveWriter> CreateDirectoryArchiveWriter(
IDiagnostics* diag, const StringPiece& path) {
std::unique_ptr<DirectoryWriter> writer =
util::make_unique<DirectoryWriter>();
- if (!writer->open(diag, path)) {
+ if (!writer->Open(diag, path)) {
return {};
}
return std::move(writer);
}
-std::unique_ptr<IArchiveWriter> createZipFileArchiveWriter(
+std::unique_ptr<IArchiveWriter> CreateZipFileArchiveWriter(
IDiagnostics* diag, const StringPiece& path) {
std::unique_ptr<ZipFileWriter> writer = util::make_unique<ZipFileWriter>();
- if (!writer->open(diag, path)) {
+ if (!writer->Open(diag, path)) {
return {};
}
return std::move(writer);
diff --git a/tools/aapt2/flatten/Archive.h b/tools/aapt2/flatten/Archive.h
index 46cd0ac..4fcb3ffa 100644
--- a/tools/aapt2/flatten/Archive.h
+++ b/tools/aapt2/flatten/Archive.h
@@ -17,17 +17,18 @@
#ifndef AAPT_FLATTEN_ARCHIVE_H
#define AAPT_FLATTEN_ARCHIVE_H
-#include "Diagnostics.h"
-#include "util/BigBuffer.h"
-#include "util/Files.h"
-#include "util/StringPiece.h"
-
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
+#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
+
+#include "Diagnostics.h"
+#include "util/BigBuffer.h"
+#include "util/Files.h"
+#include "util/StringPiece.h"
+
namespace aapt {
struct ArchiveEntry {
@@ -38,28 +39,28 @@
std::string path;
uint32_t flags;
- size_t uncompressedSize;
+ size_t uncompressed_size;
};
class IArchiveWriter : public google::protobuf::io::CopyingOutputStream {
public:
virtual ~IArchiveWriter() = default;
- virtual bool startEntry(const StringPiece& path, uint32_t flags) = 0;
- virtual bool writeEntry(const BigBuffer& buffer) = 0;
- virtual bool writeEntry(const void* data, size_t len) = 0;
- virtual bool finishEntry() = 0;
+ virtual bool StartEntry(const StringPiece& path, uint32_t flags) = 0;
+ virtual bool WriteEntry(const BigBuffer& buffer) = 0;
+ virtual bool WriteEntry(const void* data, size_t len) = 0;
+ virtual bool FinishEntry() = 0;
// CopyingOutputStream implementations.
bool Write(const void* buffer, int size) override {
- return writeEntry(buffer, size);
+ return WriteEntry(buffer, size);
}
};
-std::unique_ptr<IArchiveWriter> createDirectoryArchiveWriter(
+std::unique_ptr<IArchiveWriter> CreateDirectoryArchiveWriter(
IDiagnostics* diag, const StringPiece& path);
-std::unique_ptr<IArchiveWriter> createZipFileArchiveWriter(
+std::unique_ptr<IArchiveWriter> CreateZipFileArchiveWriter(
IDiagnostics* diag, const StringPiece& path);
} // namespace aapt
diff --git a/tools/aapt2/flatten/ChunkWriter.h b/tools/aapt2/flatten/ChunkWriter.h
index 852afd4..968d3ee 100644
--- a/tools/aapt2/flatten/ChunkWriter.h
+++ b/tools/aapt2/flatten/ChunkWriter.h
@@ -17,62 +17,62 @@
#ifndef AAPT_FLATTEN_CHUNKWRITER_H
#define AAPT_FLATTEN_CHUNKWRITER_H
+#include "android-base/macros.h"
+#include "androidfw/ResourceTypes.h"
+
#include "util/BigBuffer.h"
#include "util/Util.h"
-#include <androidfw/ResourceTypes.h>
-
namespace aapt {
class ChunkWriter {
- private:
- BigBuffer* mBuffer;
- size_t mStartSize = 0;
- android::ResChunk_header* mHeader = nullptr;
-
public:
- explicit inline ChunkWriter(BigBuffer* buffer) : mBuffer(buffer) {}
-
- ChunkWriter(const ChunkWriter&) = delete;
- ChunkWriter& operator=(const ChunkWriter&) = delete;
+ explicit inline ChunkWriter(BigBuffer* buffer) : buffer_(buffer) {}
ChunkWriter(ChunkWriter&&) = default;
ChunkWriter& operator=(ChunkWriter&&) = default;
template <typename T>
- inline T* startChunk(uint16_t type) {
- mStartSize = mBuffer->size();
- T* chunk = mBuffer->nextBlock<T>();
- mHeader = &chunk->header;
- mHeader->type = util::hostToDevice16(type);
- mHeader->headerSize = util::hostToDevice16(sizeof(T));
+ inline T* StartChunk(uint16_t type) {
+ start_size_ = buffer_->size();
+ T* chunk = buffer_->NextBlock<T>();
+ header_ = &chunk->header;
+ header_->type = util::HostToDevice16(type);
+ header_->headerSize = util::HostToDevice16(sizeof(T));
return chunk;
}
template <typename T>
- inline T* nextBlock(size_t count = 1) {
- return mBuffer->nextBlock<T>(count);
+ inline T* NextBlock(size_t count = 1) {
+ return buffer_->NextBlock<T>(count);
}
- inline BigBuffer* getBuffer() { return mBuffer; }
+ inline BigBuffer* buffer() { return buffer_; }
- inline android::ResChunk_header* getChunkHeader() { return mHeader; }
+ inline android::ResChunk_header* chunk_header() { return header_; }
- inline size_t size() { return mBuffer->size() - mStartSize; }
+ inline size_t size() { return buffer_->size() - start_size_; }
- inline android::ResChunk_header* finish() {
- mBuffer->align4();
- mHeader->size = util::hostToDevice32(mBuffer->size() - mStartSize);
- return mHeader;
+ inline android::ResChunk_header* Finish() {
+ buffer_->Align4();
+ header_->size = util::HostToDevice32(buffer_->size() - start_size_);
+ return header_;
}
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ChunkWriter);
+
+ BigBuffer* buffer_;
+ size_t start_size_ = 0;
+ android::ResChunk_header* header_ = nullptr;
};
template <>
-inline android::ResChunk_header* ChunkWriter::startChunk(uint16_t type) {
- mStartSize = mBuffer->size();
- mHeader = mBuffer->nextBlock<android::ResChunk_header>();
- mHeader->type = util::hostToDevice16(type);
- mHeader->headerSize = util::hostToDevice16(sizeof(android::ResChunk_header));
- return mHeader;
+inline android::ResChunk_header* ChunkWriter::StartChunk(uint16_t type) {
+ start_size_ = buffer_->size();
+ header_ = buffer_->NextBlock<android::ResChunk_header>();
+ header_->type = util::HostToDevice16(type);
+ header_->headerSize = util::HostToDevice16(sizeof(android::ResChunk_header));
+ return header_;
}
} // namespace aapt
diff --git a/tools/aapt2/flatten/ResourceTypeExtensions.h b/tools/aapt2/flatten/ResourceTypeExtensions.h
index 0b19240..6359b41 100644
--- a/tools/aapt2/flatten/ResourceTypeExtensions.h
+++ b/tools/aapt2/flatten/ResourceTypeExtensions.h
@@ -17,7 +17,7 @@
#ifndef AAPT_RESOURCE_TYPE_EXTENSIONS_H
#define AAPT_RESOURCE_TYPE_EXTENSIONS_H
-#include <androidfw/ResourceTypes.h>
+#include "androidfw/ResourceTypes.h"
namespace aapt {
diff --git a/tools/aapt2/flatten/TableFlattener.cpp b/tools/aapt2/flatten/TableFlattener.cpp
index d4ea6c0..19d030e 100644
--- a/tools/aapt2/flatten/TableFlattener.cpp
+++ b/tools/aapt2/flatten/TableFlattener.cpp
@@ -14,21 +14,23 @@
* limitations under the License.
*/
-#include "ResourceTable.h"
-#include "ResourceValues.h"
-#include "ValueVisitor.h"
-
-#include "flatten/ChunkWriter.h"
-#include "flatten/ResourceTypeExtensions.h"
#include "flatten/TableFlattener.h"
-#include "util/BigBuffer.h"
-#include <android-base/macros.h>
#include <algorithm>
#include <numeric>
#include <sstream>
#include <type_traits>
+#include "android-base/logging.h"
+#include "android-base/macros.h"
+
+#include "ResourceTable.h"
+#include "ResourceValues.h"
+#include "ValueVisitor.h"
+#include "flatten/ChunkWriter.h"
+#include "flatten/ResourceTypeExtensions.h"
+#include "util/BigBuffer.h"
+
using namespace android;
namespace aapt {
@@ -36,7 +38,7 @@
namespace {
template <typename T>
-static bool cmpIds(const T* a, const T* b) {
+static bool cmp_ids(const T* a, const T* b) {
return a->id.value() < b->id.value();
}
@@ -46,14 +48,14 @@
}
size_t i;
- const char16_t* srcData = src.data();
+ const char16_t* src_data = src.data();
for (i = 0; i < len - 1 && i < src.size(); i++) {
- dst[i] = util::hostToDevice16((uint16_t)srcData[i]);
+ dst[i] = util::HostToDevice16((uint16_t)src_data[i]);
}
dst[i] = 0;
}
-static bool cmpStyleEntries(const Style::Entry& a, const Style::Entry& b) {
+static bool cmp_style_entries(const Style::Entry& a, const Style::Entry& b) {
if (a.key.id) {
if (b.key.id) {
return a.key.id.value() < b.key.id.value();
@@ -70,75 +72,75 @@
Value* value;
// The entry string pool index to the entry's name.
- uint32_t entryKey;
+ uint32_t entry_key;
};
class MapFlattenVisitor : public RawValueVisitor {
public:
- using RawValueVisitor::visit;
+ using RawValueVisitor::Visit;
- MapFlattenVisitor(ResTable_entry_ext* outEntry, BigBuffer* buffer)
- : mOutEntry(outEntry), mBuffer(buffer) {}
+ MapFlattenVisitor(ResTable_entry_ext* out_entry, BigBuffer* buffer)
+ : out_entry_(out_entry), buffer_(buffer) {}
- void visit(Attribute* attr) override {
+ void Visit(Attribute* attr) override {
{
Reference key = Reference(ResourceId(ResTable_map::ATTR_TYPE));
- BinaryPrimitive val(Res_value::TYPE_INT_DEC, attr->typeMask);
- flattenEntry(&key, &val);
+ BinaryPrimitive val(Res_value::TYPE_INT_DEC, attr->type_mask);
+ FlattenEntry(&key, &val);
}
- if (attr->minInt != std::numeric_limits<int32_t>::min()) {
+ if (attr->min_int != std::numeric_limits<int32_t>::min()) {
Reference key = Reference(ResourceId(ResTable_map::ATTR_MIN));
BinaryPrimitive val(Res_value::TYPE_INT_DEC,
- static_cast<uint32_t>(attr->minInt));
- flattenEntry(&key, &val);
+ static_cast<uint32_t>(attr->min_int));
+ FlattenEntry(&key, &val);
}
- if (attr->maxInt != std::numeric_limits<int32_t>::max()) {
+ if (attr->max_int != std::numeric_limits<int32_t>::max()) {
Reference key = Reference(ResourceId(ResTable_map::ATTR_MAX));
BinaryPrimitive val(Res_value::TYPE_INT_DEC,
- static_cast<uint32_t>(attr->maxInt));
- flattenEntry(&key, &val);
+ static_cast<uint32_t>(attr->max_int));
+ FlattenEntry(&key, &val);
}
for (Attribute::Symbol& s : attr->symbols) {
BinaryPrimitive val(Res_value::TYPE_INT_DEC, s.value);
- flattenEntry(&s.symbol, &val);
+ FlattenEntry(&s.symbol, &val);
}
}
- void visit(Style* style) override {
+ void Visit(Style* style) override {
if (style->parent) {
- const Reference& parentRef = style->parent.value();
- assert(parentRef.id && "parent has no ID");
- mOutEntry->parent.ident = util::hostToDevice32(parentRef.id.value().id);
+ const Reference& parent_ref = style->parent.value();
+ CHECK(bool(parent_ref.id)) << "parent has no ID";
+ out_entry_->parent.ident = util::HostToDevice32(parent_ref.id.value().id);
}
// Sort the style.
- std::sort(style->entries.begin(), style->entries.end(), cmpStyleEntries);
+ std::sort(style->entries.begin(), style->entries.end(), cmp_style_entries);
for (Style::Entry& entry : style->entries) {
- flattenEntry(&entry.key, entry.value.get());
+ FlattenEntry(&entry.key, entry.value.get());
}
}
- void visit(Styleable* styleable) override {
- for (auto& attrRef : styleable->entries) {
+ void Visit(Styleable* styleable) override {
+ for (auto& attr_ref : styleable->entries) {
BinaryPrimitive val(Res_value{});
- flattenEntry(&attrRef, &val);
+ FlattenEntry(&attr_ref, &val);
}
}
- void visit(Array* array) override {
+ void Visit(Array* array) override {
for (auto& item : array->items) {
- ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
- flattenValue(item.get(), outEntry);
- outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
- mEntryCount++;
+ ResTable_map* out_entry = buffer_->NextBlock<ResTable_map>();
+ FlattenValue(item.get(), out_entry);
+ out_entry->value.size = util::HostToDevice16(sizeof(out_entry->value));
+ entry_count_++;
}
}
- void visit(Plural* plural) override {
+ void Visit(Plural* plural) override {
const size_t count = plural->values.size();
for (size_t i = 0; i < count; i++) {
if (!plural->values[i]) {
@@ -172,12 +174,12 @@
break;
default:
- assert(false);
+ LOG(FATAL) << "unhandled plural type";
break;
}
Reference key(q);
- flattenEntry(&key, plural->values[i].get());
+ FlattenEntry(&key, plural->values[i].get());
}
}
@@ -185,267 +187,264 @@
* Call this after visiting a Value. This will finish any work that
* needs to be done to prepare the entry.
*/
- void finish() { mOutEntry->count = util::hostToDevice32(mEntryCount); }
+ void Finish() { out_entry_->count = util::HostToDevice32(entry_count_); }
private:
- void flattenKey(Reference* key, ResTable_map* outEntry) {
- assert(key->id && "key has no ID");
- outEntry->name.ident = util::hostToDevice32(key->id.value().id);
+ DISALLOW_COPY_AND_ASSIGN(MapFlattenVisitor);
+
+ void FlattenKey(Reference* key, ResTable_map* out_entry) {
+ CHECK(bool(key->id)) << "key has no ID";
+ out_entry->name.ident = util::HostToDevice32(key->id.value().id);
}
- void flattenValue(Item* value, ResTable_map* outEntry) {
- bool result = value->flatten(&outEntry->value);
- assert(result && "flatten failed");
+ void FlattenValue(Item* value, ResTable_map* out_entry) {
+ CHECK(value->Flatten(&out_entry->value)) << "flatten failed";
}
- void flattenEntry(Reference* key, Item* value) {
- ResTable_map* outEntry = mBuffer->nextBlock<ResTable_map>();
- flattenKey(key, outEntry);
- flattenValue(value, outEntry);
- outEntry->value.size = util::hostToDevice16(sizeof(outEntry->value));
- mEntryCount++;
+ void FlattenEntry(Reference* key, Item* value) {
+ ResTable_map* out_entry = buffer_->NextBlock<ResTable_map>();
+ FlattenKey(key, out_entry);
+ FlattenValue(value, out_entry);
+ out_entry->value.size = util::HostToDevice16(sizeof(out_entry->value));
+ entry_count_++;
}
- ResTable_entry_ext* mOutEntry;
- BigBuffer* mBuffer;
- size_t mEntryCount = 0;
+ ResTable_entry_ext* out_entry_;
+ BigBuffer* buffer_;
+ size_t entry_count_ = 0;
};
class PackageFlattener {
public:
PackageFlattener(IDiagnostics* diag, ResourceTablePackage* package)
- : mDiag(diag), mPackage(package) {}
+ : diag_(diag), package_(package) {}
- bool flattenPackage(BigBuffer* buffer) {
- ChunkWriter pkgWriter(buffer);
- ResTable_package* pkgHeader =
- pkgWriter.startChunk<ResTable_package>(RES_TABLE_PACKAGE_TYPE);
- pkgHeader->id = util::hostToDevice32(mPackage->id.value());
+ bool FlattenPackage(BigBuffer* buffer) {
+ ChunkWriter pkg_writer(buffer);
+ ResTable_package* pkg_header =
+ pkg_writer.StartChunk<ResTable_package>(RES_TABLE_PACKAGE_TYPE);
+ pkg_header->id = util::HostToDevice32(package_->id.value());
- if (mPackage->name.size() >= arraysize(pkgHeader->name)) {
- mDiag->error(DiagMessage() << "package name '" << mPackage->name
+ if (package_->name.size() >= arraysize(pkg_header->name)) {
+ diag_->Error(DiagMessage() << "package name '" << package_->name
<< "' is too long");
return false;
}
// Copy the package name in device endianness.
- strcpy16_htod(pkgHeader->name, arraysize(pkgHeader->name),
- util::utf8ToUtf16(mPackage->name));
+ strcpy16_htod(pkg_header->name, arraysize(pkg_header->name),
+ util::Utf8ToUtf16(package_->name));
// Serialize the types. We do this now so that our type and key strings
// are populated. We write those first.
- BigBuffer typeBuffer(1024);
- flattenTypes(&typeBuffer);
+ BigBuffer type_buffer(1024);
+ FlattenTypes(&type_buffer);
- pkgHeader->typeStrings = util::hostToDevice32(pkgWriter.size());
- StringPool::flattenUtf16(pkgWriter.getBuffer(), mTypePool);
+ pkg_header->typeStrings = util::HostToDevice32(pkg_writer.size());
+ StringPool::FlattenUtf16(pkg_writer.buffer(), type_pool_);
- pkgHeader->keyStrings = util::hostToDevice32(pkgWriter.size());
- StringPool::flattenUtf8(pkgWriter.getBuffer(), mKeyPool);
+ pkg_header->keyStrings = util::HostToDevice32(pkg_writer.size());
+ StringPool::FlattenUtf8(pkg_writer.buffer(), key_pool_);
// Append the types.
- buffer->appendBuffer(std::move(typeBuffer));
+ buffer->AppendBuffer(std::move(type_buffer));
- pkgWriter.finish();
+ pkg_writer.Finish();
return true;
}
private:
- IDiagnostics* mDiag;
- ResourceTablePackage* mPackage;
- StringPool mTypePool;
- StringPool mKeyPool;
+ DISALLOW_COPY_AND_ASSIGN(PackageFlattener);
template <typename T, bool IsItem>
- T* writeEntry(FlatEntry* entry, BigBuffer* buffer) {
+ T* WriteEntry(FlatEntry* entry, BigBuffer* buffer) {
static_assert(std::is_same<ResTable_entry, T>::value ||
std::is_same<ResTable_entry_ext, T>::value,
"T must be ResTable_entry or ResTable_entry_ext");
- T* result = buffer->nextBlock<T>();
- ResTable_entry* outEntry = (ResTable_entry*)(result);
- if (entry->entry->symbolStatus.state == SymbolState::kPublic) {
- outEntry->flags |= ResTable_entry::FLAG_PUBLIC;
+ T* result = buffer->NextBlock<T>();
+ ResTable_entry* out_entry = (ResTable_entry*)result;
+ if (entry->entry->symbol_status.state == SymbolState::kPublic) {
+ out_entry->flags |= ResTable_entry::FLAG_PUBLIC;
}
- if (entry->value->isWeak()) {
- outEntry->flags |= ResTable_entry::FLAG_WEAK;
+ if (entry->value->IsWeak()) {
+ out_entry->flags |= ResTable_entry::FLAG_WEAK;
}
if (!IsItem) {
- outEntry->flags |= ResTable_entry::FLAG_COMPLEX;
+ out_entry->flags |= ResTable_entry::FLAG_COMPLEX;
}
- outEntry->flags = util::hostToDevice16(outEntry->flags);
- outEntry->key.index = util::hostToDevice32(entry->entryKey);
- outEntry->size = util::hostToDevice16(sizeof(T));
+ out_entry->flags = util::HostToDevice16(out_entry->flags);
+ out_entry->key.index = util::HostToDevice32(entry->entry_key);
+ out_entry->size = util::HostToDevice16(sizeof(T));
return result;
}
- bool flattenValue(FlatEntry* entry, BigBuffer* buffer) {
- if (Item* item = valueCast<Item>(entry->value)) {
- writeEntry<ResTable_entry, true>(entry, buffer);
- Res_value* outValue = buffer->nextBlock<Res_value>();
- bool result = item->flatten(outValue);
- assert(result && "flatten failed");
- outValue->size = util::hostToDevice16(sizeof(*outValue));
+ bool FlattenValue(FlatEntry* entry, BigBuffer* buffer) {
+ if (Item* item = ValueCast<Item>(entry->value)) {
+ WriteEntry<ResTable_entry, true>(entry, buffer);
+ Res_value* outValue = buffer->NextBlock<Res_value>();
+ CHECK(item->Flatten(outValue)) << "flatten failed";
+ outValue->size = util::HostToDevice16(sizeof(*outValue));
} else {
- ResTable_entry_ext* outEntry =
- writeEntry<ResTable_entry_ext, false>(entry, buffer);
- MapFlattenVisitor visitor(outEntry, buffer);
- entry->value->accept(&visitor);
- visitor.finish();
+ ResTable_entry_ext* out_entry =
+ WriteEntry<ResTable_entry_ext, false>(entry, buffer);
+ MapFlattenVisitor visitor(out_entry, buffer);
+ entry->value->Accept(&visitor);
+ visitor.Finish();
}
return true;
}
- bool flattenConfig(const ResourceTableType* type,
+ bool FlattenConfig(const ResourceTableType* type,
const ConfigDescription& config,
std::vector<FlatEntry>* entries, BigBuffer* buffer) {
- ChunkWriter typeWriter(buffer);
- ResTable_type* typeHeader =
- typeWriter.startChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
- typeHeader->id = type->id.value();
- typeHeader->config = config;
- typeHeader->config.swapHtoD();
+ ChunkWriter type_writer(buffer);
+ ResTable_type* type_header =
+ type_writer.StartChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
+ type_header->id = type->id.value();
+ type_header->config = config;
+ type_header->config.swapHtoD();
- auto maxAccum = [](uint32_t max,
- const std::unique_ptr<ResourceEntry>& a) -> uint32_t {
+ auto max_accum = [](uint32_t max,
+ const std::unique_ptr<ResourceEntry>& a) -> uint32_t {
return std::max(max, (uint32_t)a->id.value());
};
// Find the largest entry ID. That is how many entries we will have.
- const uint32_t entryCount =
+ const uint32_t entry_count =
std::accumulate(type->entries.begin(), type->entries.end(), 0,
- maxAccum) +
+ max_accum) +
1;
- typeHeader->entryCount = util::hostToDevice32(entryCount);
- uint32_t* indices = typeWriter.nextBlock<uint32_t>(entryCount);
+ type_header->entryCount = util::HostToDevice32(entry_count);
+ uint32_t* indices = type_writer.NextBlock<uint32_t>(entry_count);
- assert((size_t)entryCount <= std::numeric_limits<uint16_t>::max() + 1);
- memset(indices, 0xff, entryCount * sizeof(uint32_t));
+ CHECK((size_t)entry_count <= std::numeric_limits<uint16_t>::max());
+ memset(indices, 0xff, entry_count * sizeof(uint32_t));
- typeHeader->entriesStart = util::hostToDevice32(typeWriter.size());
+ type_header->entriesStart = util::HostToDevice32(type_writer.size());
- const size_t entryStart = typeWriter.getBuffer()->size();
- for (FlatEntry& flatEntry : *entries) {
- assert(flatEntry.entry->id.value() < entryCount);
- indices[flatEntry.entry->id.value()] =
- util::hostToDevice32(typeWriter.getBuffer()->size() - entryStart);
- if (!flattenValue(&flatEntry, typeWriter.getBuffer())) {
- mDiag->error(DiagMessage()
+ const size_t entry_start = type_writer.buffer()->size();
+ for (FlatEntry& flat_entry : *entries) {
+ CHECK(flat_entry.entry->id.value() < entry_count);
+ indices[flat_entry.entry->id.value()] =
+ util::HostToDevice32(type_writer.buffer()->size() - entry_start);
+ if (!FlattenValue(&flat_entry, type_writer.buffer())) {
+ diag_->Error(DiagMessage()
<< "failed to flatten resource '"
- << ResourceNameRef(mPackage->name, type->type,
- flatEntry.entry->name)
+ << ResourceNameRef(package_->name, type->type,
+ flat_entry.entry->name)
<< "' for configuration '" << config << "'");
return false;
}
}
- typeWriter.finish();
+ type_writer.Finish();
return true;
}
- std::vector<ResourceTableType*> collectAndSortTypes() {
- std::vector<ResourceTableType*> sortedTypes;
- for (auto& type : mPackage->types) {
+ std::vector<ResourceTableType*> CollectAndSortTypes() {
+ std::vector<ResourceTableType*> sorted_types;
+ for (auto& type : package_->types) {
if (type->type == ResourceType::kStyleable) {
// Styleables aren't real Resource Types, they are represented in the
- // R.java
- // file.
+ // R.java file.
continue;
}
- assert(type->id && "type must have an ID set");
+ CHECK(bool(type->id)) << "type must have an ID set";
- sortedTypes.push_back(type.get());
+ sorted_types.push_back(type.get());
}
- std::sort(sortedTypes.begin(), sortedTypes.end(),
- cmpIds<ResourceTableType>);
- return sortedTypes;
+ std::sort(sorted_types.begin(), sorted_types.end(),
+ cmp_ids<ResourceTableType>);
+ return sorted_types;
}
- std::vector<ResourceEntry*> collectAndSortEntries(ResourceTableType* type) {
+ std::vector<ResourceEntry*> CollectAndSortEntries(ResourceTableType* type) {
// Sort the entries by entry ID.
- std::vector<ResourceEntry*> sortedEntries;
+ std::vector<ResourceEntry*> sorted_entries;
for (auto& entry : type->entries) {
- assert(entry->id && "entry must have an ID set");
- sortedEntries.push_back(entry.get());
+ CHECK(bool(entry->id)) << "entry must have an ID set";
+ sorted_entries.push_back(entry.get());
}
- std::sort(sortedEntries.begin(), sortedEntries.end(),
- cmpIds<ResourceEntry>);
- return sortedEntries;
+ std::sort(sorted_entries.begin(), sorted_entries.end(),
+ cmp_ids<ResourceEntry>);
+ return sorted_entries;
}
- bool flattenTypeSpec(ResourceTableType* type,
- std::vector<ResourceEntry*>* sortedEntries,
+ bool FlattenTypeSpec(ResourceTableType* type,
+ std::vector<ResourceEntry*>* sorted_entries,
BigBuffer* buffer) {
- ChunkWriter typeSpecWriter(buffer);
- ResTable_typeSpec* specHeader =
- typeSpecWriter.startChunk<ResTable_typeSpec>(RES_TABLE_TYPE_SPEC_TYPE);
- specHeader->id = type->id.value();
+ ChunkWriter type_spec_writer(buffer);
+ ResTable_typeSpec* spec_header =
+ type_spec_writer.StartChunk<ResTable_typeSpec>(
+ RES_TABLE_TYPE_SPEC_TYPE);
+ spec_header->id = type->id.value();
- if (sortedEntries->empty()) {
- typeSpecWriter.finish();
+ if (sorted_entries->empty()) {
+ type_spec_writer.Finish();
return true;
}
// We can't just take the size of the vector. There may be holes in the
// entry ID space.
// Since the entries are sorted by ID, the last one will be the biggest.
- const size_t numEntries = sortedEntries->back()->id.value() + 1;
+ const size_t num_entries = sorted_entries->back()->id.value() + 1;
- specHeader->entryCount = util::hostToDevice32(numEntries);
+ spec_header->entryCount = util::HostToDevice32(num_entries);
// Reserve space for the masks of each resource in this type. These
// show for which configuration axis the resource changes.
- uint32_t* configMasks = typeSpecWriter.nextBlock<uint32_t>(numEntries);
+ uint32_t* config_masks = type_spec_writer.NextBlock<uint32_t>(num_entries);
- const size_t actualNumEntries = sortedEntries->size();
- for (size_t entryIndex = 0; entryIndex < actualNumEntries; entryIndex++) {
- ResourceEntry* entry = sortedEntries->at(entryIndex);
+ const size_t actual_num_entries = sorted_entries->size();
+ for (size_t entryIndex = 0; entryIndex < actual_num_entries; entryIndex++) {
+ ResourceEntry* entry = sorted_entries->at(entryIndex);
// Populate the config masks for this entry.
- if (entry->symbolStatus.state == SymbolState::kPublic) {
- configMasks[entry->id.value()] |=
- util::hostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
+ if (entry->symbol_status.state == SymbolState::kPublic) {
+ config_masks[entry->id.value()] |=
+ util::HostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
}
- const size_t configCount = entry->values.size();
- for (size_t i = 0; i < configCount; i++) {
+ const size_t config_count = entry->values.size();
+ for (size_t i = 0; i < config_count; i++) {
const ConfigDescription& config = entry->values[i]->config;
- for (size_t j = i + 1; j < configCount; j++) {
- configMasks[entry->id.value()] |=
- util::hostToDevice32(config.diff(entry->values[j]->config));
+ for (size_t j = i + 1; j < config_count; j++) {
+ config_masks[entry->id.value()] |=
+ util::HostToDevice32(config.diff(entry->values[j]->config));
}
}
}
- typeSpecWriter.finish();
+ type_spec_writer.Finish();
return true;
}
- bool flattenTypes(BigBuffer* buffer) {
+ bool FlattenTypes(BigBuffer* buffer) {
// Sort the types by their IDs. They will be inserted into the StringPool in
// this order.
- std::vector<ResourceTableType*> sortedTypes = collectAndSortTypes();
+ std::vector<ResourceTableType*> sorted_types = CollectAndSortTypes();
- size_t expectedTypeId = 1;
- for (ResourceTableType* type : sortedTypes) {
+ size_t expected_type_id = 1;
+ for (ResourceTableType* type : sorted_types) {
// If there is a gap in the type IDs, fill in the StringPool
// with empty values until we reach the ID we expect.
- while (type->id.value() > expectedTypeId) {
- std::stringstream typeName;
- typeName << "?" << expectedTypeId;
- mTypePool.makeRef(typeName.str());
- expectedTypeId++;
+ while (type->id.value() > expected_type_id) {
+ std::stringstream type_name;
+ type_name << "?" << expected_type_id;
+ type_pool_.MakeRef(type_name.str());
+ expected_type_id++;
}
- expectedTypeId++;
- mTypePool.makeRef(toString(type->type));
+ expected_type_id++;
+ type_pool_.MakeRef(ToString(type->type));
- std::vector<ResourceEntry*> sortedEntries = collectAndSortEntries(type);
+ std::vector<ResourceEntry*> sorted_entries = CollectAndSortEntries(type);
- if (!flattenTypeSpec(type, &sortedEntries, buffer)) {
+ if (!FlattenTypeSpec(type, &sorted_entries, buffer)) {
return false;
}
@@ -455,35 +454,41 @@
// each
// configuration available. Here we reverse this to match the binary
// table.
- std::map<ConfigDescription, std::vector<FlatEntry>> configToEntryListMap;
- for (ResourceEntry* entry : sortedEntries) {
- const uint32_t keyIndex =
- (uint32_t)mKeyPool.makeRef(entry->name).getIndex();
+ std::map<ConfigDescription, std::vector<FlatEntry>>
+ config_to_entry_list_map;
+ for (ResourceEntry* entry : sorted_entries) {
+ const uint32_t key_index =
+ (uint32_t)key_pool_.MakeRef(entry->name).index();
// Group values by configuration.
- for (auto& configValue : entry->values) {
- configToEntryListMap[configValue->config].push_back(
- FlatEntry{entry, configValue->value.get(), keyIndex});
+ for (auto& config_value : entry->values) {
+ config_to_entry_list_map[config_value->config].push_back(
+ FlatEntry{entry, config_value->value.get(), key_index});
}
}
// Flatten a configuration value.
- for (auto& entry : configToEntryListMap) {
- if (!flattenConfig(type, entry.first, &entry.second, buffer)) {
+ for (auto& entry : config_to_entry_list_map) {
+ if (!FlattenConfig(type, entry.first, &entry.second, buffer)) {
return false;
}
}
}
return true;
}
+
+ IDiagnostics* diag_;
+ ResourceTablePackage* package_;
+ StringPool type_pool_;
+ StringPool key_pool_;
};
} // namespace
-bool TableFlattener::consume(IAaptContext* context, ResourceTable* table) {
+bool TableFlattener::Consume(IAaptContext* context, ResourceTable* table) {
// We must do this before writing the resources, since the string pool IDs may
// change.
- table->stringPool.sort(
+ table->string_pool.Sort(
[](const StringPool::Entry& a, const StringPool::Entry& b) -> bool {
int diff = a.context.priority - b.context.priority;
if (diff < 0) return true;
@@ -493,30 +498,30 @@
if (diff > 0) return false;
return a.value < b.value;
});
- table->stringPool.prune();
+ table->string_pool.Prune();
// Write the ResTable header.
- ChunkWriter tableWriter(mBuffer);
- ResTable_header* tableHeader =
- tableWriter.startChunk<ResTable_header>(RES_TABLE_TYPE);
- tableHeader->packageCount = util::hostToDevice32(table->packages.size());
+ ChunkWriter table_writer(buffer_);
+ ResTable_header* table_header =
+ table_writer.StartChunk<ResTable_header>(RES_TABLE_TYPE);
+ table_header->packageCount = util::HostToDevice32(table->packages.size());
// Flatten the values string pool.
- StringPool::flattenUtf8(tableWriter.getBuffer(), table->stringPool);
+ StringPool::FlattenUtf8(table_writer.buffer(), table->string_pool);
- BigBuffer packageBuffer(1024);
+ BigBuffer package_buffer(1024);
// Flatten each package.
for (auto& package : table->packages) {
- PackageFlattener flattener(context->getDiagnostics(), package.get());
- if (!flattener.flattenPackage(&packageBuffer)) {
+ PackageFlattener flattener(context->GetDiagnostics(), package.get());
+ if (!flattener.FlattenPackage(&package_buffer)) {
return false;
}
}
// Finally merge all the packages into the main buffer.
- tableWriter.getBuffer()->appendBuffer(std::move(packageBuffer));
- tableWriter.finish();
+ table_writer.buffer()->AppendBuffer(std::move(package_buffer));
+ table_writer.Finish();
return true;
}
diff --git a/tools/aapt2/flatten/TableFlattener.h b/tools/aapt2/flatten/TableFlattener.h
index 91f9654..53f52c2 100644
--- a/tools/aapt2/flatten/TableFlattener.h
+++ b/tools/aapt2/flatten/TableFlattener.h
@@ -17,21 +17,24 @@
#ifndef AAPT_FLATTEN_TABLEFLATTENER_H
#define AAPT_FLATTEN_TABLEFLATTENER_H
+#include "android-base/macros.h"
+
+#include "ResourceTable.h"
#include "process/IResourceTableConsumer.h"
+#include "util/BigBuffer.h"
namespace aapt {
-class BigBuffer;
-class ResourceTable;
-
class TableFlattener : public IResourceTableConsumer {
public:
- explicit TableFlattener(BigBuffer* buffer) : mBuffer(buffer) {}
+ explicit TableFlattener(BigBuffer* buffer) : buffer_(buffer) {}
- bool consume(IAaptContext* context, ResourceTable* table) override;
+ bool Consume(IAaptContext* context, ResourceTable* table) override;
private:
- BigBuffer* mBuffer;
+ DISALLOW_COPY_AND_ASSIGN(TableFlattener);
+
+ BigBuffer* buffer_;
};
} // namespace aapt
diff --git a/tools/aapt2/flatten/TableFlattener_test.cpp b/tools/aapt2/flatten/TableFlattener_test.cpp
index a7706bd..c726240 100644
--- a/tools/aapt2/flatten/TableFlattener_test.cpp
+++ b/tools/aapt2/flatten/TableFlattener_test.cpp
@@ -15,6 +15,7 @@
*/
#include "flatten/TableFlattener.h"
+
#include "ResourceUtils.h"
#include "test/Test.h"
#include "unflatten/BinaryResourceParser.h"
@@ -27,162 +28,165 @@
class TableFlattenerTest : public ::testing::Test {
public:
void SetUp() override {
- mContext = test::ContextBuilder()
- .setCompilationPackage("com.app.test")
- .setPackageId(0x7f)
- .build();
+ context_ = test::ContextBuilder()
+ .SetCompilationPackage("com.app.test")
+ .SetPackageId(0x7f)
+ .Build();
}
- ::testing::AssertionResult flatten(ResourceTable* table, ResTable* outTable) {
+ ::testing::AssertionResult Flatten(ResourceTable* table,
+ ResTable* out_table) {
BigBuffer buffer(1024);
TableFlattener flattener(&buffer);
- if (!flattener.consume(mContext.get(), table)) {
+ if (!flattener.Consume(context_.get(), table)) {
return ::testing::AssertionFailure() << "failed to flatten ResourceTable";
}
- std::unique_ptr<uint8_t[]> data = util::copy(buffer);
- if (outTable->add(data.get(), buffer.size(), -1, true) != NO_ERROR) {
+ std::unique_ptr<uint8_t[]> data = util::Copy(buffer);
+ if (out_table->add(data.get(), buffer.size(), -1, true) != NO_ERROR) {
return ::testing::AssertionFailure() << "flattened ResTable is corrupt";
}
return ::testing::AssertionSuccess();
}
- ::testing::AssertionResult flatten(ResourceTable* table,
- ResourceTable* outTable) {
+ ::testing::AssertionResult Flatten(ResourceTable* table,
+ ResourceTable* out_table) {
BigBuffer buffer(1024);
TableFlattener flattener(&buffer);
- if (!flattener.consume(mContext.get(), table)) {
+ if (!flattener.Consume(context_.get(), table)) {
return ::testing::AssertionFailure() << "failed to flatten ResourceTable";
}
- std::unique_ptr<uint8_t[]> data = util::copy(buffer);
- BinaryResourceParser parser(mContext.get(), outTable, {}, data.get(),
+ std::unique_ptr<uint8_t[]> data = util::Copy(buffer);
+ BinaryResourceParser parser(context_.get(), out_table, {}, data.get(),
buffer.size());
- if (!parser.parse()) {
+ if (!parser.Parse()) {
return ::testing::AssertionFailure() << "flattened ResTable is corrupt";
}
return ::testing::AssertionSuccess();
}
- ::testing::AssertionResult exists(ResTable* table,
- const StringPiece& expectedName,
- const ResourceId& expectedId,
- const ConfigDescription& expectedConfig,
- const uint8_t expectedDataType,
- const uint32_t expectedData,
- const uint32_t expectedSpecFlags) {
- const ResourceName expectedResName = test::parseNameOrDie(expectedName);
+ ::testing::AssertionResult Exists(ResTable* table,
+ const StringPiece& expected_name,
+ const ResourceId& expected_id,
+ const ConfigDescription& expected_config,
+ const uint8_t expected_data_type,
+ const uint32_t expected_data,
+ const uint32_t expected_spec_flags) {
+ const ResourceName expected_res_name = test::ParseNameOrDie(expected_name);
- table->setParameters(&expectedConfig);
+ table->setParameters(&expected_config);
ResTable_config config;
Res_value val;
- uint32_t specFlags;
- if (table->getResource(expectedId.id, &val, false, 0, &specFlags, &config) <
- 0) {
+ uint32_t spec_flags;
+ if (table->getResource(expected_id.id, &val, false, 0, &spec_flags,
+ &config) < 0) {
return ::testing::AssertionFailure() << "could not find resource with";
}
- if (expectedDataType != val.dataType) {
+ if (expected_data_type != val.dataType) {
return ::testing::AssertionFailure()
- << "expected data type " << std::hex << (int)expectedDataType
+ << "expected data type " << std::hex << (int)expected_data_type
<< " but got data type " << (int)val.dataType << std::dec
<< " instead";
}
- if (expectedData != val.data) {
+ if (expected_data != val.data) {
return ::testing::AssertionFailure()
- << "expected data " << std::hex << expectedData << " but got data "
- << val.data << std::dec << " instead";
+ << "expected data " << std::hex << expected_data
+ << " but got data " << val.data << std::dec << " instead";
}
- if (expectedSpecFlags != specFlags) {
+ if (expected_spec_flags != spec_flags) {
return ::testing::AssertionFailure()
- << "expected specFlags " << std::hex << expectedSpecFlags
- << " but got specFlags " << specFlags << std::dec << " instead";
+ << "expected specFlags " << std::hex << expected_spec_flags
+ << " but got specFlags " << spec_flags << std::dec << " instead";
}
- ResTable::resource_name actualName;
- if (!table->getResourceName(expectedId.id, false, &actualName)) {
+ ResTable::resource_name actual_name;
+ if (!table->getResourceName(expected_id.id, false, &actual_name)) {
return ::testing::AssertionFailure() << "failed to find resource name";
}
- Maybe<ResourceName> resName = ResourceUtils::toResourceName(actualName);
+ Maybe<ResourceName> resName = ResourceUtils::ToResourceName(actual_name);
if (!resName) {
return ::testing::AssertionFailure()
- << "expected name '" << expectedResName << "' but got '"
- << StringPiece16(actualName.package, actualName.packageLen) << ":"
- << StringPiece16(actualName.type, actualName.typeLen) << "/"
- << StringPiece16(actualName.name, actualName.nameLen) << "'";
+ << "expected name '" << expected_res_name << "' but got '"
+ << StringPiece16(actual_name.package, actual_name.packageLen)
+ << ":" << StringPiece16(actual_name.type, actual_name.typeLen)
+ << "/" << StringPiece16(actual_name.name, actual_name.nameLen)
+ << "'";
}
- if (expectedConfig != config) {
+ if (expected_config != config) {
return ::testing::AssertionFailure() << "expected config '"
- << expectedConfig << "' but got '"
+ << expected_config << "' but got '"
<< ConfigDescription(config) << "'";
}
return ::testing::AssertionSuccess();
}
private:
- std::unique_ptr<IAaptContext> mContext;
+ std::unique_ptr<IAaptContext> context_;
};
TEST_F(TableFlattenerTest, FlattenFullyLinkedTable) {
std::unique_ptr<ResourceTable> table =
test::ResourceTableBuilder()
- .setPackageId("com.app.test", 0x7f)
- .addSimple("com.app.test:id/one", ResourceId(0x7f020000))
- .addSimple("com.app.test:id/two", ResourceId(0x7f020001))
- .addValue("com.app.test:id/three", ResourceId(0x7f020002),
- test::buildReference("com.app.test:id/one",
+ .SetPackageId("com.app.test", 0x7f)
+ .AddSimple("com.app.test:id/one", ResourceId(0x7f020000))
+ .AddSimple("com.app.test:id/two", ResourceId(0x7f020001))
+ .AddValue("com.app.test:id/three", ResourceId(0x7f020002),
+ test::BuildReference("com.app.test:id/one",
ResourceId(0x7f020000)))
- .addValue("com.app.test:integer/one", ResourceId(0x7f030000),
+ .AddValue("com.app.test:integer/one", ResourceId(0x7f030000),
util::make_unique<BinaryPrimitive>(
uint8_t(Res_value::TYPE_INT_DEC), 1u))
- .addValue("com.app.test:integer/one", test::parseConfigOrDie("v1"),
+ .AddValue("com.app.test:integer/one", test::ParseConfigOrDie("v1"),
ResourceId(0x7f030000),
util::make_unique<BinaryPrimitive>(
uint8_t(Res_value::TYPE_INT_DEC), 2u))
- .addString("com.app.test:string/test", ResourceId(0x7f040000), "foo")
- .addString("com.app.test:layout/bar", ResourceId(0x7f050000),
+ .AddString("com.app.test:string/test", ResourceId(0x7f040000), "foo")
+ .AddString("com.app.test:layout/bar", ResourceId(0x7f050000),
"res/layout/bar.xml")
- .build();
+ .Build();
- ResTable resTable;
- ASSERT_TRUE(flatten(table.get(), &resTable));
+ ResTable res_table;
+ ASSERT_TRUE(Flatten(table.get(), &res_table));
- EXPECT_TRUE(exists(&resTable, "com.app.test:id/one", ResourceId(0x7f020000),
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:id/one", ResourceId(0x7f020000),
{}, Res_value::TYPE_INT_BOOLEAN, 0u, 0u));
- EXPECT_TRUE(exists(&resTable, "com.app.test:id/two", ResourceId(0x7f020001),
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:id/two", ResourceId(0x7f020001),
{}, Res_value::TYPE_INT_BOOLEAN, 0u, 0u));
- EXPECT_TRUE(exists(&resTable, "com.app.test:id/three", ResourceId(0x7f020002),
- {}, Res_value::TYPE_REFERENCE, 0x7f020000u, 0u));
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:id/three",
+ ResourceId(0x7f020002), {}, Res_value::TYPE_REFERENCE,
+ 0x7f020000u, 0u));
- EXPECT_TRUE(exists(&resTable, "com.app.test:integer/one",
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:integer/one",
ResourceId(0x7f030000), {}, Res_value::TYPE_INT_DEC, 1u,
ResTable_config::CONFIG_VERSION));
- EXPECT_TRUE(exists(&resTable, "com.app.test:integer/one",
- ResourceId(0x7f030000), test::parseConfigOrDie("v1"),
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:integer/one",
+ ResourceId(0x7f030000), test::ParseConfigOrDie("v1"),
Res_value::TYPE_INT_DEC, 2u,
ResTable_config::CONFIG_VERSION));
- std::u16string fooStr = u"foo";
- ssize_t idx = resTable.getTableStringBlock(0)->indexOfString(fooStr.data(),
- fooStr.size());
+ std::u16string foo_str = u"foo";
+ ssize_t idx = res_table.getTableStringBlock(0)->indexOfString(foo_str.data(),
+ foo_str.size());
ASSERT_GE(idx, 0);
- EXPECT_TRUE(exists(&resTable, "com.app.test:string/test",
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:string/test",
ResourceId(0x7f040000), {}, Res_value::TYPE_STRING,
(uint32_t)idx, 0u));
- std::u16string barPath = u"res/layout/bar.xml";
- idx = resTable.getTableStringBlock(0)->indexOfString(barPath.data(),
- barPath.size());
+ std::u16string bar_path = u"res/layout/bar.xml";
+ idx = res_table.getTableStringBlock(0)->indexOfString(bar_path.data(),
+ bar_path.size());
ASSERT_GE(idx, 0);
- EXPECT_TRUE(exists(&resTable, "com.app.test:layout/bar",
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:layout/bar",
ResourceId(0x7f050000), {}, Res_value::TYPE_STRING,
(uint32_t)idx, 0u));
}
@@ -190,42 +194,43 @@
TEST_F(TableFlattenerTest, FlattenEntriesWithGapsInIds) {
std::unique_ptr<ResourceTable> table =
test::ResourceTableBuilder()
- .setPackageId("com.app.test", 0x7f)
- .addSimple("com.app.test:id/one", ResourceId(0x7f020001))
- .addSimple("com.app.test:id/three", ResourceId(0x7f020003))
- .build();
+ .SetPackageId("com.app.test", 0x7f)
+ .AddSimple("com.app.test:id/one", ResourceId(0x7f020001))
+ .AddSimple("com.app.test:id/three", ResourceId(0x7f020003))
+ .Build();
- ResTable resTable;
- ASSERT_TRUE(flatten(table.get(), &resTable));
+ ResTable res_table;
+ ASSERT_TRUE(Flatten(table.get(), &res_table));
- EXPECT_TRUE(exists(&resTable, "com.app.test:id/one", ResourceId(0x7f020001),
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:id/one", ResourceId(0x7f020001),
{}, Res_value::TYPE_INT_BOOLEAN, 0u, 0u));
- EXPECT_TRUE(exists(&resTable, "com.app.test:id/three", ResourceId(0x7f020003),
- {}, Res_value::TYPE_INT_BOOLEAN, 0u, 0u));
+ EXPECT_TRUE(Exists(&res_table, "com.app.test:id/three",
+ ResourceId(0x7f020003), {}, Res_value::TYPE_INT_BOOLEAN,
+ 0u, 0u));
}
TEST_F(TableFlattenerTest, FlattenMinMaxAttributes) {
Attribute attr(false);
- attr.typeMask = android::ResTable_map::TYPE_INTEGER;
- attr.minInt = 10;
- attr.maxInt = 23;
+ attr.type_mask = android::ResTable_map::TYPE_INTEGER;
+ attr.min_int = 10;
+ attr.max_int = 23;
std::unique_ptr<ResourceTable> table =
test::ResourceTableBuilder()
- .setPackageId("android", 0x01)
- .addValue("android:attr/foo", ResourceId(0x01010000),
+ .SetPackageId("android", 0x01)
+ .AddValue("android:attr/foo", ResourceId(0x01010000),
util::make_unique<Attribute>(attr))
- .build();
+ .Build();
ResourceTable result;
- ASSERT_TRUE(flatten(table.get(), &result));
+ ASSERT_TRUE(Flatten(table.get(), &result));
Attribute* actualAttr =
- test::getValue<Attribute>(&result, "android:attr/foo");
+ test::GetValue<Attribute>(&result, "android:attr/foo");
ASSERT_NE(nullptr, actualAttr);
- EXPECT_EQ(attr.isWeak(), actualAttr->isWeak());
- EXPECT_EQ(attr.typeMask, actualAttr->typeMask);
- EXPECT_EQ(attr.minInt, actualAttr->minInt);
- EXPECT_EQ(attr.maxInt, actualAttr->maxInt);
+ EXPECT_EQ(attr.IsWeak(), actualAttr->IsWeak());
+ EXPECT_EQ(attr.type_mask, actualAttr->type_mask);
+ EXPECT_EQ(attr.min_int, actualAttr->min_int);
+ EXPECT_EQ(attr.max_int, actualAttr->max_int);
}
} // namespace aapt
diff --git a/tools/aapt2/flatten/XmlFlattener.cpp b/tools/aapt2/flatten/XmlFlattener.cpp
index b1536d5..366c373 100644
--- a/tools/aapt2/flatten/XmlFlattener.cpp
+++ b/tools/aapt2/flatten/XmlFlattener.cpp
@@ -15,17 +15,21 @@
*/
#include "flatten/XmlFlattener.h"
+
+#include <algorithm>
+#include <map>
+#include <vector>
+
+#include "android-base/logging.h"
+#include "android-base/macros.h"
+#include "androidfw/ResourceTypes.h"
+#include "utils/misc.h"
+
#include "SdkConstants.h"
#include "flatten/ChunkWriter.h"
#include "flatten/ResourceTypeExtensions.h"
#include "xml/XmlDom.h"
-#include <androidfw/ResourceTypes.h>
-#include <utils/misc.h>
-#include <algorithm>
-#include <map>
-#include <vector>
-
using namespace android;
namespace aapt {
@@ -34,216 +38,215 @@
constexpr uint32_t kLowPriority = 0xffffffffu;
-struct XmlFlattenerVisitor : public xml::Visitor {
- using xml::Visitor::visit;
+static bool cmp_xml_attribute_by_id(const xml::Attribute* a,
+ const xml::Attribute* b) {
+ if (a->compiled_attribute && a->compiled_attribute.value().id) {
+ if (b->compiled_attribute && b->compiled_attribute.value().id) {
+ return a->compiled_attribute.value().id.value() <
+ b->compiled_attribute.value().id.value();
+ }
+ return true;
+ } else if (!b->compiled_attribute) {
+ int diff = a->namespace_uri.compare(b->namespace_uri);
+ if (diff < 0) {
+ return true;
+ } else if (diff > 0) {
+ return false;
+ }
+ return a->name < b->name;
+ }
+ return false;
+}
- BigBuffer* mBuffer;
- XmlFlattenerOptions mOptions;
- StringPool mPool;
- std::map<uint8_t, StringPool> mPackagePools;
+class XmlFlattenerVisitor : public xml::Visitor {
+ public:
+ using xml::Visitor::Visit;
+
+ StringPool pool;
+ std::map<uint8_t, StringPool> package_pools;
struct StringFlattenDest {
StringPool::Ref ref;
ResStringPool_ref* dest;
};
- std::vector<StringFlattenDest> mStringRefs;
- // Scratch vector to filter attributes. We avoid allocations
- // making this a member.
- std::vector<xml::Attribute*> mFilteredAttrs;
+ std::vector<StringFlattenDest> string_refs;
XmlFlattenerVisitor(BigBuffer* buffer, XmlFlattenerOptions options)
- : mBuffer(buffer), mOptions(options) {}
+ : buffer_(buffer), options_(options) {}
- void addString(const StringPiece& str, uint32_t priority,
- android::ResStringPool_ref* dest,
- bool treatEmptyStringAsNull = false) {
- if (str.empty() && treatEmptyStringAsNull) {
- // Some parts of the runtime treat null differently than empty string.
- dest->index = util::deviceToHost32(-1);
- } else {
- mStringRefs.push_back(StringFlattenDest{
- mPool.makeRef(str, StringPool::Context(priority)), dest});
- }
- }
-
- void addString(const StringPool::Ref& ref, android::ResStringPool_ref* dest) {
- mStringRefs.push_back(StringFlattenDest{ref, dest});
- }
-
- void writeNamespace(xml::Namespace* node, uint16_t type) {
- ChunkWriter writer(mBuffer);
-
- ResXMLTree_node* flatNode = writer.startChunk<ResXMLTree_node>(type);
- flatNode->lineNumber = util::hostToDevice32(node->lineNumber);
- flatNode->comment.index = util::hostToDevice32(-1);
-
- ResXMLTree_namespaceExt* flatNs =
- writer.nextBlock<ResXMLTree_namespaceExt>();
- addString(node->namespacePrefix, kLowPriority, &flatNs->prefix);
- addString(node->namespaceUri, kLowPriority, &flatNs->uri);
-
- writer.finish();
- }
-
- void visit(xml::Namespace* node) override {
- if (node->namespaceUri == xml::kSchemaTools) {
+ void Visit(xml::Namespace* node) override {
+ if (node->namespace_uri == xml::kSchemaTools) {
// Skip dedicated tools namespace.
- xml::Visitor::visit(node);
+ xml::Visitor::Visit(node);
} else {
- writeNamespace(node, android::RES_XML_START_NAMESPACE_TYPE);
- xml::Visitor::visit(node);
- writeNamespace(node, android::RES_XML_END_NAMESPACE_TYPE);
+ WriteNamespace(node, android::RES_XML_START_NAMESPACE_TYPE);
+ xml::Visitor::Visit(node);
+ WriteNamespace(node, android::RES_XML_END_NAMESPACE_TYPE);
}
}
- void visit(xml::Text* node) override {
- if (util::trimWhitespace(node->text).empty()) {
+ void Visit(xml::Text* node) override {
+ if (util::TrimWhitespace(node->text).empty()) {
// Skip whitespace only text nodes.
return;
}
- ChunkWriter writer(mBuffer);
- ResXMLTree_node* flatNode =
- writer.startChunk<ResXMLTree_node>(RES_XML_CDATA_TYPE);
- flatNode->lineNumber = util::hostToDevice32(node->lineNumber);
- flatNode->comment.index = util::hostToDevice32(-1);
+ ChunkWriter writer(buffer_);
+ ResXMLTree_node* flat_node =
+ writer.StartChunk<ResXMLTree_node>(RES_XML_CDATA_TYPE);
+ flat_node->lineNumber = util::HostToDevice32(node->line_number);
+ flat_node->comment.index = util::HostToDevice32(-1);
- ResXMLTree_cdataExt* flatText = writer.nextBlock<ResXMLTree_cdataExt>();
- addString(node->text, kLowPriority, &flatText->data);
+ ResXMLTree_cdataExt* flat_text = writer.NextBlock<ResXMLTree_cdataExt>();
+ AddString(node->text, kLowPriority, &flat_text->data);
- writer.finish();
+ writer.Finish();
}
- void visit(xml::Element* node) override {
+ void Visit(xml::Element* node) override {
{
- ChunkWriter startWriter(mBuffer);
- ResXMLTree_node* flatNode =
- startWriter.startChunk<ResXMLTree_node>(RES_XML_START_ELEMENT_TYPE);
- flatNode->lineNumber = util::hostToDevice32(node->lineNumber);
- flatNode->comment.index = util::hostToDevice32(-1);
+ ChunkWriter start_writer(buffer_);
+ ResXMLTree_node* flat_node =
+ start_writer.StartChunk<ResXMLTree_node>(RES_XML_START_ELEMENT_TYPE);
+ flat_node->lineNumber = util::HostToDevice32(node->line_number);
+ flat_node->comment.index = util::HostToDevice32(-1);
- ResXMLTree_attrExt* flatElem =
- startWriter.nextBlock<ResXMLTree_attrExt>();
+ ResXMLTree_attrExt* flat_elem =
+ start_writer.NextBlock<ResXMLTree_attrExt>();
// A missing namespace must be null, not an empty string. Otherwise the
- // runtime
- // complains.
- addString(node->namespaceUri, kLowPriority, &flatElem->ns,
- true /* treatEmptyStringAsNull */);
- addString(node->name, kLowPriority, &flatElem->name,
- true /* treatEmptyStringAsNull */);
+ // runtime complains.
+ AddString(node->namespace_uri, kLowPriority, &flat_elem->ns,
+ true /* treat_empty_string_as_null */);
+ AddString(node->name, kLowPriority, &flat_elem->name,
+ true /* treat_empty_string_as_null */);
- flatElem->attributeStart = util::hostToDevice16(sizeof(*flatElem));
- flatElem->attributeSize =
- util::hostToDevice16(sizeof(ResXMLTree_attribute));
+ flat_elem->attributeStart = util::HostToDevice16(sizeof(*flat_elem));
+ flat_elem->attributeSize =
+ util::HostToDevice16(sizeof(ResXMLTree_attribute));
- writeAttributes(node, flatElem, &startWriter);
+ WriteAttributes(node, flat_elem, &start_writer);
- startWriter.finish();
+ start_writer.Finish();
}
- xml::Visitor::visit(node);
+ xml::Visitor::Visit(node);
{
- ChunkWriter endWriter(mBuffer);
- ResXMLTree_node* flatEndNode =
- endWriter.startChunk<ResXMLTree_node>(RES_XML_END_ELEMENT_TYPE);
- flatEndNode->lineNumber = util::hostToDevice32(node->lineNumber);
- flatEndNode->comment.index = util::hostToDevice32(-1);
+ ChunkWriter end_writer(buffer_);
+ ResXMLTree_node* flat_end_node =
+ end_writer.StartChunk<ResXMLTree_node>(RES_XML_END_ELEMENT_TYPE);
+ flat_end_node->lineNumber = util::HostToDevice32(node->line_number);
+ flat_end_node->comment.index = util::HostToDevice32(-1);
- ResXMLTree_endElementExt* flatEndElem =
- endWriter.nextBlock<ResXMLTree_endElementExt>();
- addString(node->namespaceUri, kLowPriority, &flatEndElem->ns,
- true /* treatEmptyStringAsNull */);
- addString(node->name, kLowPriority, &flatEndElem->name);
+ ResXMLTree_endElementExt* flat_end_elem =
+ end_writer.NextBlock<ResXMLTree_endElementExt>();
+ AddString(node->namespace_uri, kLowPriority, &flat_end_elem->ns,
+ true /* treat_empty_string_as_null */);
+ AddString(node->name, kLowPriority, &flat_end_elem->name);
- endWriter.finish();
+ end_writer.Finish();
}
}
- static bool cmpXmlAttributeById(const xml::Attribute* a,
- const xml::Attribute* b) {
- if (a->compiledAttribute && a->compiledAttribute.value().id) {
- if (b->compiledAttribute && b->compiledAttribute.value().id) {
- return a->compiledAttribute.value().id.value() <
- b->compiledAttribute.value().id.value();
- }
- return true;
- } else if (!b->compiledAttribute) {
- int diff = a->namespaceUri.compare(b->namespaceUri);
- if (diff < 0) {
- return true;
- } else if (diff > 0) {
- return false;
- }
- return a->name < b->name;
+ private:
+ DISALLOW_COPY_AND_ASSIGN(XmlFlattenerVisitor);
+
+ void AddString(const StringPiece& str, uint32_t priority,
+ android::ResStringPool_ref* dest,
+ bool treat_empty_string_as_null = false) {
+ if (str.empty() && treat_empty_string_as_null) {
+ // Some parts of the runtime treat null differently than empty string.
+ dest->index = util::DeviceToHost32(-1);
+ } else {
+ string_refs.push_back(StringFlattenDest{
+ pool.MakeRef(str, StringPool::Context(priority)), dest});
}
- return false;
}
- void writeAttributes(xml::Element* node, ResXMLTree_attrExt* flatElem,
+ void AddString(const StringPool::Ref& ref, android::ResStringPool_ref* dest) {
+ string_refs.push_back(StringFlattenDest{ref, dest});
+ }
+
+ void WriteNamespace(xml::Namespace* node, uint16_t type) {
+ ChunkWriter writer(buffer_);
+
+ ResXMLTree_node* flatNode = writer.StartChunk<ResXMLTree_node>(type);
+ flatNode->lineNumber = util::HostToDevice32(node->line_number);
+ flatNode->comment.index = util::HostToDevice32(-1);
+
+ ResXMLTree_namespaceExt* flat_ns =
+ writer.NextBlock<ResXMLTree_namespaceExt>();
+ AddString(node->namespace_prefix, kLowPriority, &flat_ns->prefix);
+ AddString(node->namespace_uri, kLowPriority, &flat_ns->uri);
+
+ writer.Finish();
+ }
+
+ void WriteAttributes(xml::Element* node, ResXMLTree_attrExt* flat_elem,
ChunkWriter* writer) {
- mFilteredAttrs.clear();
- mFilteredAttrs.reserve(node->attributes.size());
+ filtered_attrs_.clear();
+ filtered_attrs_.reserve(node->attributes.size());
// Filter the attributes.
for (xml::Attribute& attr : node->attributes) {
- if (mOptions.maxSdkLevel && attr.compiledAttribute &&
- attr.compiledAttribute.value().id) {
- size_t sdkLevel =
- findAttributeSdkLevel(attr.compiledAttribute.value().id.value());
- if (sdkLevel > mOptions.maxSdkLevel.value()) {
+ if (options_.max_sdk_level && attr.compiled_attribute &&
+ attr.compiled_attribute.value().id) {
+ size_t sdk_level =
+ FindAttributeSdkLevel(attr.compiled_attribute.value().id.value());
+ if (sdk_level > options_.max_sdk_level.value()) {
continue;
}
}
- if (attr.namespaceUri == xml::kSchemaTools) {
+ if (attr.namespace_uri == xml::kSchemaTools) {
continue;
}
- mFilteredAttrs.push_back(&attr);
+ filtered_attrs_.push_back(&attr);
}
- if (mFilteredAttrs.empty()) {
+ if (filtered_attrs_.empty()) {
return;
}
const ResourceId kIdAttr(0x010100d0);
- std::sort(mFilteredAttrs.begin(), mFilteredAttrs.end(),
- cmpXmlAttributeById);
+ std::sort(filtered_attrs_.begin(), filtered_attrs_.end(),
+ cmp_xml_attribute_by_id);
- flatElem->attributeCount = util::hostToDevice16(mFilteredAttrs.size());
+ flat_elem->attributeCount = util::HostToDevice16(filtered_attrs_.size());
- ResXMLTree_attribute* flatAttr =
- writer->nextBlock<ResXMLTree_attribute>(mFilteredAttrs.size());
- uint16_t attributeIndex = 1;
- for (const xml::Attribute* xmlAttr : mFilteredAttrs) {
+ ResXMLTree_attribute* flat_attr =
+ writer->NextBlock<ResXMLTree_attribute>(filtered_attrs_.size());
+ uint16_t attribute_index = 1;
+ for (const xml::Attribute* xml_attr : filtered_attrs_) {
// Assign the indices for specific attributes.
- if (xmlAttr->compiledAttribute && xmlAttr->compiledAttribute.value().id &&
- xmlAttr->compiledAttribute.value().id.value() == kIdAttr) {
- flatElem->idIndex = util::hostToDevice16(attributeIndex);
- } else if (xmlAttr->namespaceUri.empty()) {
- if (xmlAttr->name == "class") {
- flatElem->classIndex = util::hostToDevice16(attributeIndex);
- } else if (xmlAttr->name == "style") {
- flatElem->styleIndex = util::hostToDevice16(attributeIndex);
+ if (xml_attr->compiled_attribute &&
+ xml_attr->compiled_attribute.value().id &&
+ xml_attr->compiled_attribute.value().id.value() == kIdAttr) {
+ flat_elem->idIndex = util::HostToDevice16(attribute_index);
+ } else if (xml_attr->namespace_uri.empty()) {
+ if (xml_attr->name == "class") {
+ flat_elem->classIndex = util::HostToDevice16(attribute_index);
+ } else if (xml_attr->name == "style") {
+ flat_elem->styleIndex = util::HostToDevice16(attribute_index);
}
}
- attributeIndex++;
+ attribute_index++;
// Add the namespaceUri to the list of StringRefs to encode. Use null if
// the namespace
// is empty (doesn't exist).
- addString(xmlAttr->namespaceUri, kLowPriority, &flatAttr->ns,
- true /* treatEmptyStringAsNull */);
+ AddString(xml_attr->namespace_uri, kLowPriority, &flat_attr->ns,
+ true /* treat_empty_string_as_null */);
- flatAttr->rawValue.index = util::hostToDevice32(-1);
+ flat_attr->rawValue.index = util::HostToDevice32(-1);
- if (!xmlAttr->compiledAttribute ||
- !xmlAttr->compiledAttribute.value().id) {
+ if (!xml_attr->compiled_attribute ||
+ !xml_attr->compiled_attribute.value().id) {
// The attribute has no associated ResourceID, so the string order
// doesn't matter.
- addString(xmlAttr->name, kLowPriority, &flatAttr->name);
+ AddString(xml_attr->name, kLowPriority, &flat_attr->name);
} else {
// Attribute names are stored without packages, but we use
// their StringPool index to lookup their resource IDs.
@@ -252,99 +255,106 @@
// pools that we later combine.
//
// Lookup the StringPool for this package and make the reference there.
- const xml::AaptAttribute& aaptAttr = xmlAttr->compiledAttribute.value();
+ const xml::AaptAttribute& aapt_attr =
+ xml_attr->compiled_attribute.value();
- StringPool::Ref nameRef =
- mPackagePools[aaptAttr.id.value().packageId()].makeRef(
- xmlAttr->name, StringPool::Context(aaptAttr.id.value().id));
+ StringPool::Ref name_ref =
+ package_pools[aapt_attr.id.value().package_id()].MakeRef(
+ xml_attr->name, StringPool::Context(aapt_attr.id.value().id));
// Add it to the list of strings to flatten.
- addString(nameRef, &flatAttr->name);
+ AddString(name_ref, &flat_attr->name);
}
- if (mOptions.keepRawValues || !xmlAttr->compiledValue) {
+ if (options_.keep_raw_values || !xml_attr->compiled_value) {
// Keep raw values if the value is not compiled or
// if we're building a static library (need symbols).
- addString(xmlAttr->value, kLowPriority, &flatAttr->rawValue);
+ AddString(xml_attr->value, kLowPriority, &flat_attr->rawValue);
}
- if (xmlAttr->compiledValue) {
- bool result = xmlAttr->compiledValue->flatten(&flatAttr->typedValue);
- assert(result);
+ if (xml_attr->compiled_value) {
+ CHECK(xml_attr->compiled_value->Flatten(&flat_attr->typedValue));
} else {
// Flatten as a regular string type.
- flatAttr->typedValue.dataType = android::Res_value::TYPE_STRING;
- addString(xmlAttr->value, kLowPriority,
- (ResStringPool_ref*)&flatAttr->typedValue.data);
+ flat_attr->typedValue.dataType = android::Res_value::TYPE_STRING;
+ AddString(xml_attr->value, kLowPriority,
+ (ResStringPool_ref*)&flat_attr->typedValue.data);
}
- flatAttr->typedValue.size =
- util::hostToDevice16(sizeof(flatAttr->typedValue));
- flatAttr++;
+ flat_attr->typedValue.size =
+ util::HostToDevice16(sizeof(flat_attr->typedValue));
+ flat_attr++;
}
}
+
+ BigBuffer* buffer_;
+ XmlFlattenerOptions options_;
+
+ // Scratch vector to filter attributes. We avoid allocations
+ // making this a member.
+ std::vector<xml::Attribute*> filtered_attrs_;
};
} // namespace
-bool XmlFlattener::flatten(IAaptContext* context, xml::Node* node) {
- BigBuffer nodeBuffer(1024);
- XmlFlattenerVisitor visitor(&nodeBuffer, mOptions);
- node->accept(&visitor);
+bool XmlFlattener::Flatten(IAaptContext* context, xml::Node* node) {
+ BigBuffer node_buffer(1024);
+ XmlFlattenerVisitor visitor(&node_buffer, options_);
+ node->Accept(&visitor);
// Merge the package pools into the main pool.
- for (auto& packagePoolEntry : visitor.mPackagePools) {
- visitor.mPool.merge(std::move(packagePoolEntry.second));
+ for (auto& package_pool_entry : visitor.package_pools) {
+ visitor.pool.Merge(std::move(package_pool_entry.second));
}
// Sort the string pool so that attribute resource IDs show up first.
- visitor.mPool.sort(
+ visitor.pool.Sort(
[](const StringPool::Entry& a, const StringPool::Entry& b) -> bool {
return a.context.priority < b.context.priority;
});
// Now we flatten the string pool references into the correct places.
- for (const auto& refEntry : visitor.mStringRefs) {
- refEntry.dest->index = util::hostToDevice32(refEntry.ref.getIndex());
+ for (const auto& ref_entry : visitor.string_refs) {
+ ref_entry.dest->index = util::HostToDevice32(ref_entry.ref.index());
}
// Write the XML header.
- ChunkWriter xmlHeaderWriter(mBuffer);
- xmlHeaderWriter.startChunk<ResXMLTree_header>(RES_XML_TYPE);
+ ChunkWriter xml_header_writer(buffer_);
+ xml_header_writer.StartChunk<ResXMLTree_header>(RES_XML_TYPE);
// Flatten the StringPool.
- StringPool::flattenUtf8(mBuffer, visitor.mPool);
+ StringPool::FlattenUtf8(buffer_, visitor.pool);
{
// Write the array of resource IDs, indexed by StringPool order.
- ChunkWriter resIdMapWriter(mBuffer);
- resIdMapWriter.startChunk<ResChunk_header>(RES_XML_RESOURCE_MAP_TYPE);
- for (const auto& str : visitor.mPool) {
+ ChunkWriter res_id_map_writer(buffer_);
+ res_id_map_writer.StartChunk<ResChunk_header>(RES_XML_RESOURCE_MAP_TYPE);
+ for (const auto& str : visitor.pool) {
ResourceId id = {str->context.priority};
- if (id.id == kLowPriority || !id.isValid()) {
+ if (id.id == kLowPriority || !id.is_valid()) {
// When we see the first non-resource ID,
// we're done.
break;
}
- *resIdMapWriter.nextBlock<uint32_t>() = id.id;
+ *res_id_map_writer.NextBlock<uint32_t>() = id.id;
}
- resIdMapWriter.finish();
+ res_id_map_writer.Finish();
}
// Move the nodeBuffer and append it to the out buffer.
- mBuffer->appendBuffer(std::move(nodeBuffer));
+ buffer_->AppendBuffer(std::move(node_buffer));
// Finish the xml header.
- xmlHeaderWriter.finish();
+ xml_header_writer.Finish();
return true;
}
-bool XmlFlattener::consume(IAaptContext* context, xml::XmlResource* resource) {
+bool XmlFlattener::Consume(IAaptContext* context, xml::XmlResource* resource) {
if (!resource->root) {
return false;
}
- return flatten(context, resource->root.get());
+ return Flatten(context, resource->root.get());
}
} // namespace aapt
diff --git a/tools/aapt2/flatten/XmlFlattener.h b/tools/aapt2/flatten/XmlFlattener.h
index d8d592b..f5129fd 100644
--- a/tools/aapt2/flatten/XmlFlattener.h
+++ b/tools/aapt2/flatten/XmlFlattener.h
@@ -17,6 +17,8 @@
#ifndef AAPT_FLATTEN_XMLFLATTENER_H
#define AAPT_FLATTEN_XMLFLATTENER_H
+#include "android-base/macros.h"
+
#include "process/IResourceTableConsumer.h"
#include "util/BigBuffer.h"
#include "xml/XmlDom.h"
@@ -27,26 +29,28 @@
/**
* Keep attribute raw string values along with typed values.
*/
- bool keepRawValues = false;
+ bool keep_raw_values = false;
/**
* If set, the max SDK level of attribute to flatten. All others are ignored.
*/
- Maybe<size_t> maxSdkLevel;
+ Maybe<size_t> max_sdk_level;
};
class XmlFlattener : public IXmlResourceConsumer {
public:
XmlFlattener(BigBuffer* buffer, XmlFlattenerOptions options)
- : mBuffer(buffer), mOptions(options) {}
+ : buffer_(buffer), options_(options) {}
- bool consume(IAaptContext* context, xml::XmlResource* resource) override;
+ bool Consume(IAaptContext* context, xml::XmlResource* resource) override;
private:
- BigBuffer* mBuffer;
- XmlFlattenerOptions mOptions;
+ DISALLOW_COPY_AND_ASSIGN(XmlFlattener);
- bool flatten(IAaptContext* context, xml::Node* node);
+ bool Flatten(IAaptContext* context, xml::Node* node);
+
+ BigBuffer* buffer_;
+ XmlFlattenerOptions options_;
};
} // namespace aapt
diff --git a/tools/aapt2/flatten/XmlFlattener_test.cpp b/tools/aapt2/flatten/XmlFlattener_test.cpp
index e0159cb..2c83bb3 100644
--- a/tools/aapt2/flatten/XmlFlattener_test.cpp
+++ b/tools/aapt2/flatten/XmlFlattener_test.cpp
@@ -15,61 +15,62 @@
*/
#include "flatten/XmlFlattener.h"
+
+#include "androidfw/ResourceTypes.h"
+
#include "link/Linkers.h"
#include "test/Test.h"
#include "util/BigBuffer.h"
#include "util/Util.h"
-#include <androidfw/ResourceTypes.h>
-
namespace aapt {
class XmlFlattenerTest : public ::testing::Test {
public:
void SetUp() override {
- mContext =
+ context_ =
test::ContextBuilder()
- .setCompilationPackage("com.app.test")
- .setNameManglerPolicy(NameManglerPolicy{"com.app.test"})
- .addSymbolSource(
+ .SetCompilationPackage("com.app.test")
+ .SetNameManglerPolicy(NameManglerPolicy{"com.app.test"})
+ .AddSymbolSource(
test::StaticSymbolSourceBuilder()
- .addSymbol("android:attr/id", ResourceId(0x010100d0),
- test::AttributeBuilder().build())
- .addSymbol("com.app.test:id/id", ResourceId(0x7f020000))
- .addSymbol("android:attr/paddingStart",
+ .AddSymbol("android:attr/id", ResourceId(0x010100d0),
+ test::AttributeBuilder().Build())
+ .AddSymbol("com.app.test:id/id", ResourceId(0x7f020000))
+ .AddSymbol("android:attr/paddingStart",
ResourceId(0x010103b3),
- test::AttributeBuilder().build())
- .addSymbol("android:attr/colorAccent",
+ test::AttributeBuilder().Build())
+ .AddSymbol("android:attr/colorAccent",
ResourceId(0x01010435),
- test::AttributeBuilder().build())
- .build())
- .build();
+ test::AttributeBuilder().Build())
+ .Build())
+ .Build();
}
- ::testing::AssertionResult flatten(xml::XmlResource* doc,
- android::ResXMLTree* outTree,
+ ::testing::AssertionResult Flatten(xml::XmlResource* doc,
+ android::ResXMLTree* out_tree,
const XmlFlattenerOptions& options = {}) {
using namespace android; // For NO_ERROR on windows because it is a macro.
BigBuffer buffer(1024);
XmlFlattener flattener(&buffer, options);
- if (!flattener.consume(mContext.get(), doc)) {
+ if (!flattener.Consume(context_.get(), doc)) {
return ::testing::AssertionFailure() << "failed to flatten XML Tree";
}
- std::unique_ptr<uint8_t[]> data = util::copy(buffer);
- if (outTree->setTo(data.get(), buffer.size(), true) != NO_ERROR) {
+ std::unique_ptr<uint8_t[]> data = util::Copy(buffer);
+ if (out_tree->setTo(data.get(), buffer.size(), true) != NO_ERROR) {
return ::testing::AssertionFailure() << "flattened XML is corrupt";
}
return ::testing::AssertionSuccess();
}
protected:
- std::unique_ptr<IAaptContext> mContext;
+ std::unique_ptr<IAaptContext> context_;
};
TEST_F(XmlFlattenerTest, FlattenXmlWithNoCompiledAttributes) {
- std::unique_ptr<xml::XmlResource> doc = test::buildXmlDom(R"EOF(
+ std::unique_ptr<xml::XmlResource> doc = test::BuildXmlDom(R"EOF(
<View xmlns:test="http://com.test"
attr="hey">
<Layout test:hello="hi" />
@@ -77,27 +78,27 @@
</View>)EOF");
android::ResXMLTree tree;
- ASSERT_TRUE(flatten(doc.get(), &tree));
+ ASSERT_TRUE(Flatten(doc.get(), &tree));
ASSERT_EQ(tree.next(), android::ResXMLTree::START_NAMESPACE);
size_t len;
- const char16_t* namespacePrefix = tree.getNamespacePrefix(&len);
- EXPECT_EQ(StringPiece16(namespacePrefix, len), u"test");
+ const char16_t* namespace_prefix = tree.getNamespacePrefix(&len);
+ EXPECT_EQ(StringPiece16(namespace_prefix, len), u"test");
- const char16_t* namespaceUri = tree.getNamespaceUri(&len);
- ASSERT_EQ(StringPiece16(namespaceUri, len), u"http://com.test");
+ const char16_t* namespace_uri = tree.getNamespaceUri(&len);
+ ASSERT_EQ(StringPiece16(namespace_uri, len), u"http://com.test");
ASSERT_EQ(tree.next(), android::ResXMLTree::START_TAG);
ASSERT_EQ(tree.getElementNamespace(&len), nullptr);
- const char16_t* tagName = tree.getElementName(&len);
- EXPECT_EQ(StringPiece16(tagName, len), u"View");
+ const char16_t* tag_name = tree.getElementName(&len);
+ EXPECT_EQ(StringPiece16(tag_name, len), u"View");
ASSERT_EQ(1u, tree.getAttributeCount());
ASSERT_EQ(tree.getAttributeNamespace(0, &len), nullptr);
- const char16_t* attrName = tree.getAttributeName(0, &len);
- EXPECT_EQ(StringPiece16(attrName, len), u"attr");
+ const char16_t* attr_name = tree.getAttributeName(0, &len);
+ EXPECT_EQ(StringPiece16(attr_name, len), u"attr");
EXPECT_EQ(0, tree.indexOfAttribute(nullptr, 0, u"attr",
StringPiece16(u"attr").size()));
@@ -105,22 +106,22 @@
ASSERT_EQ(tree.next(), android::ResXMLTree::START_TAG);
ASSERT_EQ(tree.getElementNamespace(&len), nullptr);
- tagName = tree.getElementName(&len);
- EXPECT_EQ(StringPiece16(tagName, len), u"Layout");
+ tag_name = tree.getElementName(&len);
+ EXPECT_EQ(StringPiece16(tag_name, len), u"Layout");
ASSERT_EQ(1u, tree.getAttributeCount());
- const char16_t* attrNamespace = tree.getAttributeNamespace(0, &len);
- EXPECT_EQ(StringPiece16(attrNamespace, len), u"http://com.test");
+ const char16_t* attr_namespace = tree.getAttributeNamespace(0, &len);
+ EXPECT_EQ(StringPiece16(attr_namespace, len), u"http://com.test");
- attrName = tree.getAttributeName(0, &len);
- EXPECT_EQ(StringPiece16(attrName, len), u"hello");
+ attr_name = tree.getAttributeName(0, &len);
+ EXPECT_EQ(StringPiece16(attr_name, len), u"hello");
ASSERT_EQ(tree.next(), android::ResXMLTree::END_TAG);
ASSERT_EQ(tree.next(), android::ResXMLTree::START_TAG);
ASSERT_EQ(tree.getElementNamespace(&len), nullptr);
- tagName = tree.getElementName(&len);
- EXPECT_EQ(StringPiece16(tagName, len), u"Layout");
+ tag_name = tree.getElementName(&len);
+ EXPECT_EQ(StringPiece16(tag_name, len), u"Layout");
ASSERT_EQ(0u, tree.getAttributeCount());
ASSERT_EQ(tree.next(), android::ResXMLTree::TEXT);
@@ -129,39 +130,39 @@
ASSERT_EQ(tree.next(), android::ResXMLTree::END_TAG);
ASSERT_EQ(tree.getElementNamespace(&len), nullptr);
- tagName = tree.getElementName(&len);
- EXPECT_EQ(StringPiece16(tagName, len), u"Layout");
+ tag_name = tree.getElementName(&len);
+ EXPECT_EQ(StringPiece16(tag_name, len), u"Layout");
ASSERT_EQ(tree.next(), android::ResXMLTree::END_TAG);
ASSERT_EQ(tree.getElementNamespace(&len), nullptr);
- tagName = tree.getElementName(&len);
- EXPECT_EQ(StringPiece16(tagName, len), u"View");
+ tag_name = tree.getElementName(&len);
+ EXPECT_EQ(StringPiece16(tag_name, len), u"View");
ASSERT_EQ(tree.next(), android::ResXMLTree::END_NAMESPACE);
- namespacePrefix = tree.getNamespacePrefix(&len);
- EXPECT_EQ(StringPiece16(namespacePrefix, len), u"test");
+ namespace_prefix = tree.getNamespacePrefix(&len);
+ EXPECT_EQ(StringPiece16(namespace_prefix, len), u"test");
- namespaceUri = tree.getNamespaceUri(&len);
- ASSERT_EQ(StringPiece16(namespaceUri, len), u"http://com.test");
+ namespace_uri = tree.getNamespaceUri(&len);
+ ASSERT_EQ(StringPiece16(namespace_uri, len), u"http://com.test");
ASSERT_EQ(tree.next(), android::ResXMLTree::END_DOCUMENT);
}
TEST_F(XmlFlattenerTest, FlattenCompiledXmlAndStripSdk21) {
- std::unique_ptr<xml::XmlResource> doc = test::buildXmlDom(R"EOF(
+ std::unique_ptr<xml::XmlResource> doc = test::BuildXmlDom(R"EOF(
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingStart="1dp"
android:colorAccent="#ffffff"/>)EOF");
XmlReferenceLinker linker;
- ASSERT_TRUE(linker.consume(mContext.get(), doc.get()));
- ASSERT_TRUE(linker.getSdkLevels().count(17) == 1);
- ASSERT_TRUE(linker.getSdkLevels().count(21) == 1);
+ ASSERT_TRUE(linker.Consume(context_.get(), doc.get()));
+ ASSERT_TRUE(linker.sdk_levels().count(17) == 1);
+ ASSERT_TRUE(linker.sdk_levels().count(21) == 1);
android::ResXMLTree tree;
XmlFlattenerOptions options;
- options.maxSdkLevel = 17;
- ASSERT_TRUE(flatten(doc.get(), &tree, options));
+ options.max_sdk_level = 17;
+ ASSERT_TRUE(Flatten(doc.get(), &tree, options));
while (tree.next() != android::ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), android::ResXMLTree::BAD_DOCUMENT);
@@ -173,23 +174,23 @@
}
TEST_F(XmlFlattenerTest, FlattenCompiledXmlAndStripOnlyTools) {
- std::unique_ptr<xml::XmlResource> doc = test::buildXmlDom(R"EOF(
+ std::unique_ptr<xml::XmlResource> doc = test::BuildXmlDom(R"EOF(
<View xmlns:tools="http://schemas.android.com/tools"
xmlns:foo="http://schemas.android.com/foo"
foo:bar="Foo"
tools:ignore="MissingTranslation"/>)EOF");
android::ResXMLTree tree;
- ASSERT_TRUE(flatten(doc.get(), &tree));
+ ASSERT_TRUE(Flatten(doc.get(), &tree));
ASSERT_EQ(tree.next(), android::ResXMLTree::START_NAMESPACE);
size_t len;
- const char16_t* namespacePrefix = tree.getNamespacePrefix(&len);
- EXPECT_EQ(StringPiece16(namespacePrefix, len), u"foo");
+ const char16_t* namespace_prefix = tree.getNamespacePrefix(&len);
+ EXPECT_EQ(StringPiece16(namespace_prefix, len), u"foo");
- const char16_t* namespaceUri = tree.getNamespaceUri(&len);
- ASSERT_EQ(StringPiece16(namespaceUri, len),
+ const char16_t* namespace_uri = tree.getNamespaceUri(&len);
+ ASSERT_EQ(StringPiece16(namespace_uri, len),
u"http://schemas.android.com/foo");
ASSERT_EQ(tree.next(), android::ResXMLTree::START_TAG);
@@ -200,14 +201,14 @@
}
TEST_F(XmlFlattenerTest, AssignSpecialAttributeIndices) {
- std::unique_ptr<xml::XmlResource> doc = test::buildXmlDom(R"EOF(
+ std::unique_ptr<xml::XmlResource> doc = test::BuildXmlDom(R"EOF(
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/id"
class="str"
style="@id/id"/>)EOF");
android::ResXMLTree tree;
- ASSERT_TRUE(flatten(doc.get(), &tree));
+ ASSERT_TRUE(Flatten(doc.get(), &tree));
while (tree.next() != android::ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), android::ResXMLTree::BAD_DOCUMENT);
@@ -225,10 +226,10 @@
*/
TEST_F(XmlFlattenerTest, NoNamespaceIsNotTheSameAsEmptyNamespace) {
std::unique_ptr<xml::XmlResource> doc =
- test::buildXmlDom("<View package=\"android\"/>");
+ test::BuildXmlDom("<View package=\"android\"/>");
android::ResXMLTree tree;
- ASSERT_TRUE(flatten(doc.get(), &tree));
+ ASSERT_TRUE(Flatten(doc.get(), &tree));
while (tree.next() != android::ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), android::ResXMLTree::BAD_DOCUMENT);
@@ -242,10 +243,10 @@
TEST_F(XmlFlattenerTest, EmptyStringValueInAttributeIsNotNull) {
std::unique_ptr<xml::XmlResource> doc =
- test::buildXmlDom("<View package=\"\"/>");
+ test::BuildXmlDom("<View package=\"\"/>");
android::ResXMLTree tree;
- ASSERT_TRUE(flatten(doc.get(), &tree));
+ ASSERT_TRUE(Flatten(doc.get(), &tree));
while (tree.next() != android::ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), android::ResXMLTree::BAD_DOCUMENT);