blob: c4ecbafc008b0ef536f0aec497b2348ef8ab72c0 [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Adam Lesinski46708052017-09-29 14:49:15 -070017#include "format/binary/TableFlattener.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070018
Adam Lesinski803c7c82016-04-06 16:09:43 -070019#include <algorithm>
Adam Lesinskicacb28f2016-10-19 12:18:14 -070020#include <numeric>
Adam Lesinskid0f116b2016-07-08 15:00:32 -070021#include <sstream>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070022#include <type_traits>
Adam Lesinski1ab598f2015-08-14 14:26:04 -070023
Adam Lesinskice5e56e22016-10-21 17:56:45 -070024#include "android-base/logging.h"
25#include "android-base/macros.h"
Adam Lesinski490595a2017-11-07 17:08:07 -080026#include "android-base/stringprintf.h"
Ryan Mitchell75e20dd2018-11-06 16:39:36 -080027#include "androidfw/ResourceUtils.h"
Adam Lesinskice5e56e22016-10-21 17:56:45 -070028
29#include "ResourceTable.h"
30#include "ResourceValues.h"
Adam Lesinskic8f71aa2017-02-08 07:03:50 -080031#include "SdkConstants.h"
Adam Lesinskice5e56e22016-10-21 17:56:45 -070032#include "ValueVisitor.h"
Adam Lesinski46708052017-09-29 14:49:15 -070033#include "format/binary/ChunkWriter.h"
34#include "format/binary/ResourceTypeExtensions.h"
Adam Lesinskice5e56e22016-10-21 17:56:45 -070035#include "util/BigBuffer.h"
36
Adam Lesinski1ab598f2015-08-14 14:26:04 -070037using namespace android;
38
39namespace aapt {
40
41namespace {
42
43template <typename T>
Adam Lesinskice5e56e22016-10-21 17:56:45 -070044static bool cmp_ids(const T* a, const T* b) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070045 return a->id.value() < b->id.value();
Adam Lesinski1ab598f2015-08-14 14:26:04 -070046}
47
48static void strcpy16_htod(uint16_t* dst, size_t len, const StringPiece16& src) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070049 if (len == 0) {
50 return;
51 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070052
Adam Lesinskicacb28f2016-10-19 12:18:14 -070053 size_t i;
Adam Lesinskice5e56e22016-10-21 17:56:45 -070054 const char16_t* src_data = src.data();
Adam Lesinskicacb28f2016-10-19 12:18:14 -070055 for (i = 0; i < len - 1 && i < src.size(); i++) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -070056 dst[i] = util::HostToDevice16((uint16_t)src_data[i]);
Adam Lesinskicacb28f2016-10-19 12:18:14 -070057 }
58 dst[i] = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070059}
60
Adam Lesinskice5e56e22016-10-21 17:56:45 -070061static bool cmp_style_entries(const Style::Entry& a, const Style::Entry& b) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070062 if (a.key.id) {
63 if (b.key.id) {
64 return a.key.id.value() < b.key.id.value();
65 }
66 return true;
67 } else if (!b.key.id) {
68 return a.key.name.value() < b.key.name.value();
69 }
70 return false;
Adam Lesinski59e04c62016-02-04 15:59:23 -080071}
72
Adam Lesinski1ab598f2015-08-14 14:26:04 -070073struct FlatEntry {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070074 ResourceEntry* entry;
75 Value* value;
Adam Lesinski3b4cd942015-10-30 16:31:42 -070076
Adam Lesinskicacb28f2016-10-19 12:18:14 -070077 // The entry string pool index to the entry's name.
Adam Lesinskice5e56e22016-10-21 17:56:45 -070078 uint32_t entry_key;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070079};
80
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070081class MapFlattenVisitor : public ValueVisitor {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070082 public:
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070083 using ValueVisitor::Visit;
Adam Lesinski1ab598f2015-08-14 14:26:04 -070084
Adam Lesinskice5e56e22016-10-21 17:56:45 -070085 MapFlattenVisitor(ResTable_entry_ext* out_entry, BigBuffer* buffer)
Adam Lesinski46708052017-09-29 14:49:15 -070086 : out_entry_(out_entry), buffer_(buffer) {
87 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -070088
Adam Lesinskice5e56e22016-10-21 17:56:45 -070089 void Visit(Attribute* attr) override {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070090 {
91 Reference key = Reference(ResourceId(ResTable_map::ATTR_TYPE));
Adam Lesinskice5e56e22016-10-21 17:56:45 -070092 BinaryPrimitive val(Res_value::TYPE_INT_DEC, attr->type_mask);
93 FlattenEntry(&key, &val);
Adam Lesinski28cacf02015-11-23 14:22:47 -080094 }
95
Adam Lesinskice5e56e22016-10-21 17:56:45 -070096 if (attr->min_int != std::numeric_limits<int32_t>::min()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070097 Reference key = Reference(ResourceId(ResTable_map::ATTR_MIN));
Adam Lesinski46708052017-09-29 14:49:15 -070098 BinaryPrimitive val(Res_value::TYPE_INT_DEC, static_cast<uint32_t>(attr->min_int));
Adam Lesinskice5e56e22016-10-21 17:56:45 -070099 FlattenEntry(&key, &val);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700100 }
101
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700102 if (attr->max_int != std::numeric_limits<int32_t>::max()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700103 Reference key = Reference(ResourceId(ResTable_map::ATTR_MAX));
Adam Lesinski46708052017-09-29 14:49:15 -0700104 BinaryPrimitive val(Res_value::TYPE_INT_DEC, static_cast<uint32_t>(attr->max_int));
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700105 FlattenEntry(&key, &val);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700106 }
107
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700108 for (Attribute::Symbol& s : attr->symbols) {
109 BinaryPrimitive val(Res_value::TYPE_INT_DEC, s.value);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700110 FlattenEntry(&s.symbol, &val);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700111 }
112 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800113
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700114 void Visit(Style* style) override {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700115 if (style->parent) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700116 const Reference& parent_ref = style->parent.value();
117 CHECK(bool(parent_ref.id)) << "parent has no ID";
118 out_entry_->parent.ident = util::HostToDevice32(parent_ref.id.value().id);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700119 }
120
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700121 // Sort the style.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700122 std::sort(style->entries.begin(), style->entries.end(), cmp_style_entries);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700123
124 for (Style::Entry& entry : style->entries) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700125 FlattenEntry(&entry.key, entry.value.get());
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700126 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700127 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700128
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700129 void Visit(Styleable* styleable) override {
130 for (auto& attr_ref : styleable->entries) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700131 BinaryPrimitive val(Res_value{});
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700132 FlattenEntry(&attr_ref, &val);
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700133 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700134 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800135
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700136 void Visit(Array* array) override {
Ryan Mitchell0f7da5e2018-08-16 16:10:00 -0700137 const size_t count = array->elements.size();
138 for (size_t i = 0; i < count; i++) {
139 Reference key(android::ResTable_map::ATTR_MIN + i);
140 FlattenEntry(&key, array->elements[i].get());
Adam Lesinski59e04c62016-02-04 15:59:23 -0800141 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700142 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800143
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700144 void Visit(Plural* plural) override {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700145 const size_t count = plural->values.size();
146 for (size_t i = 0; i < count; i++) {
147 if (!plural->values[i]) {
148 continue;
149 }
150
151 ResourceId q;
152 switch (i) {
153 case Plural::Zero:
154 q.id = android::ResTable_map::ATTR_ZERO;
155 break;
156
157 case Plural::One:
158 q.id = android::ResTable_map::ATTR_ONE;
159 break;
160
161 case Plural::Two:
162 q.id = android::ResTable_map::ATTR_TWO;
163 break;
164
165 case Plural::Few:
166 q.id = android::ResTable_map::ATTR_FEW;
167 break;
168
169 case Plural::Many:
170 q.id = android::ResTable_map::ATTR_MANY;
171 break;
172
173 case Plural::Other:
174 q.id = android::ResTable_map::ATTR_OTHER;
175 break;
176
177 default:
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700178 LOG(FATAL) << "unhandled plural type";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700179 break;
180 }
181
182 Reference key(q);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700183 FlattenEntry(&key, plural->values[i].get());
Adam Lesinski59e04c62016-02-04 15:59:23 -0800184 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700185 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800186
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700187 /**
188 * Call this after visiting a Value. This will finish any work that
189 * needs to be done to prepare the entry.
190 */
Adam Lesinski46708052017-09-29 14:49:15 -0700191 void Finish() {
192 out_entry_->count = util::HostToDevice32(entry_count_);
193 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800194
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700195 private:
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700196 DISALLOW_COPY_AND_ASSIGN(MapFlattenVisitor);
197
198 void FlattenKey(Reference* key, ResTable_map* out_entry) {
199 CHECK(bool(key->id)) << "key has no ID";
200 out_entry->name.ident = util::HostToDevice32(key->id.value().id);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700201 }
Adam Lesinski59e04c62016-02-04 15:59:23 -0800202
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700203 void FlattenValue(Item* value, ResTable_map* out_entry) {
204 CHECK(value->Flatten(&out_entry->value)) << "flatten failed";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700205 }
206
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700207 void FlattenEntry(Reference* key, Item* value) {
208 ResTable_map* out_entry = buffer_->NextBlock<ResTable_map>();
209 FlattenKey(key, out_entry);
210 FlattenValue(value, out_entry);
211 out_entry->value.size = util::HostToDevice16(sizeof(out_entry->value));
212 entry_count_++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700213 }
214
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700215 ResTable_entry_ext* out_entry_;
216 BigBuffer* buffer_;
217 size_t entry_count_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700218};
219
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800220struct OverlayableChunk {
221 std::string actor;
222 Source source;
223 std::map<OverlayableItem::PolicyFlags, std::set<ResourceId>> policy_ids;
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800224};
225
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700226class PackageFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700227 public:
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800228 PackageFlattener(IAaptContext* context, ResourceTablePackage* package,
Luke Nicholsonb0643302017-12-01 15:29:03 -0800229 const std::map<size_t, std::string>* shared_libs, bool use_sparse_entries,
230 bool collapse_key_stringpool, const std::set<std::string>& whitelisted_resources)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800231 : context_(context),
232 diag_(context->GetDiagnostics()),
233 package_(package),
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800234 shared_libs_(shared_libs),
Luke Nicholsonb0643302017-12-01 15:29:03 -0800235 use_sparse_entries_(use_sparse_entries),
236 collapse_key_stringpool_(collapse_key_stringpool),
237 whitelisted_resources_(whitelisted_resources) {
Adam Lesinski46708052017-09-29 14:49:15 -0700238 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700239
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700240 bool FlattenPackage(BigBuffer* buffer) {
241 ChunkWriter pkg_writer(buffer);
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800242 ResTable_package* pkg_header = pkg_writer.StartChunk<ResTable_package>(RES_TABLE_PACKAGE_TYPE);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700243 pkg_header->id = util::HostToDevice32(package_->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700244
Adam Lesinskib522f042017-04-21 16:57:59 -0700245 // AAPT truncated the package name, so do the same.
246 // Shared libraries require full package names, so don't truncate theirs.
247 if (context_->GetPackageType() != PackageType::kApp &&
248 package_->name.size() >= arraysize(pkg_header->name)) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700249 diag_->Error(DiagMessage() << "package name '" << package_->name
Adam Lesinskib522f042017-04-21 16:57:59 -0700250 << "' is too long. "
251 "Shared libraries cannot have truncated package names");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700252 return false;
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700253 }
254
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700255 // Copy the package name in device endianness.
Adam Lesinskib522f042017-04-21 16:57:59 -0700256 strcpy16_htod(pkg_header->name, arraysize(pkg_header->name), util::Utf8ToUtf16(package_->name));
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700257
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700258 // Serialize the types. We do this now so that our type and key strings
259 // are populated. We write those first.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700260 BigBuffer type_buffer(1024);
261 FlattenTypes(&type_buffer);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700262
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700263 pkg_header->typeStrings = util::HostToDevice32(pkg_writer.size());
Ryan Mitchella15c2a82018-03-26 11:05:31 -0700264 StringPool::FlattenUtf16(pkg_writer.buffer(), type_pool_, diag_);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700265
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700266 pkg_header->keyStrings = util::HostToDevice32(pkg_writer.size());
Ryan Mitchella15c2a82018-03-26 11:05:31 -0700267 StringPool::FlattenUtf8(pkg_writer.buffer(), key_pool_, diag_);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700268
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700269 // Append the types.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700270 buffer->AppendBuffer(std::move(type_buffer));
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700271
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800272 // If there are libraries (or if the package ID is 0x00), encode a library chunk.
273 if (package_->id.value() == 0x00 || !shared_libs_->empty()) {
274 FlattenLibrarySpec(buffer);
275 }
276
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800277 FlattenOverlayable(buffer);
278
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700279 pkg_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700280 return true;
281 }
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700282
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700283 private:
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700284 DISALLOW_COPY_AND_ASSIGN(PackageFlattener);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700285
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700286 template <typename T, bool IsItem>
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700287 T* WriteEntry(FlatEntry* entry, BigBuffer* buffer) {
Adam Lesinski46708052017-09-29 14:49:15 -0700288 static_assert(
289 std::is_same<ResTable_entry, T>::value || std::is_same<ResTable_entry_ext, T>::value,
290 "T must be ResTable_entry or ResTable_entry_ext");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700291
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700292 T* result = buffer->NextBlock<T>();
293 ResTable_entry* out_entry = (ResTable_entry*)result;
Adam Lesinski71be7052017-12-12 16:48:07 -0800294 if (entry->entry->visibility.level == Visibility::Level::kPublic) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700295 out_entry->flags |= ResTable_entry::FLAG_PUBLIC;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700296 }
297
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700298 if (entry->value->IsWeak()) {
299 out_entry->flags |= ResTable_entry::FLAG_WEAK;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700300 }
301
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700302 if (!IsItem) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700303 out_entry->flags |= ResTable_entry::FLAG_COMPLEX;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700304 }
305
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700306 out_entry->flags = util::HostToDevice16(out_entry->flags);
307 out_entry->key.index = util::HostToDevice32(entry->entry_key);
308 out_entry->size = util::HostToDevice16(sizeof(T));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700309 return result;
310 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700311
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700312 bool FlattenValue(FlatEntry* entry, BigBuffer* buffer) {
313 if (Item* item = ValueCast<Item>(entry->value)) {
314 WriteEntry<ResTable_entry, true>(entry, buffer);
315 Res_value* outValue = buffer->NextBlock<Res_value>();
316 CHECK(item->Flatten(outValue)) << "flatten failed";
317 outValue->size = util::HostToDevice16(sizeof(*outValue));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700318 } else {
Adam Lesinski46708052017-09-29 14:49:15 -0700319 ResTable_entry_ext* out_entry = WriteEntry<ResTable_entry_ext, false>(entry, buffer);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700320 MapFlattenVisitor visitor(out_entry, buffer);
321 entry->value->Accept(&visitor);
322 visitor.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700323 }
324 return true;
325 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700326
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800327 bool FlattenConfig(const ResourceTableType* type, const ConfigDescription& config,
328 const size_t num_total_entries, std::vector<FlatEntry>* entries,
329 BigBuffer* buffer) {
330 CHECK(num_total_entries != 0);
331 CHECK(num_total_entries <= std::numeric_limits<uint16_t>::max());
332
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700333 ChunkWriter type_writer(buffer);
Adam Lesinski46708052017-09-29 14:49:15 -0700334 ResTable_type* type_header = type_writer.StartChunk<ResTable_type>(RES_TABLE_TYPE_TYPE);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700335 type_header->id = type->id.value();
336 type_header->config = config;
337 type_header->config.swapHtoD();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700338
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800339 std::vector<uint32_t> offsets;
340 offsets.resize(num_total_entries, 0xffffffffu);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700341
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800342 BigBuffer values_buffer(512);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700343 for (FlatEntry& flat_entry : *entries) {
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800344 CHECK(static_cast<size_t>(flat_entry.entry->id.value()) < num_total_entries);
345 offsets[flat_entry.entry->id.value()] = values_buffer.size();
346 if (!FlattenValue(&flat_entry, &values_buffer)) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700347 diag_->Error(DiagMessage()
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700348 << "failed to flatten resource '"
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800349 << ResourceNameRef(package_->name, type->type, flat_entry.entry->name)
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700350 << "' for configuration '" << config << "'");
351 return false;
352 }
353 }
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800354
355 bool sparse_encode = use_sparse_entries_;
356
357 // Only sparse encode if the entries will be read on platforms O+.
358 sparse_encode =
359 sparse_encode && (context_->GetMinSdkVersion() >= SDK_O || config.sdkVersion >= SDK_O);
360
361 // Only sparse encode if the offsets are representable in 2 bytes.
362 sparse_encode =
363 sparse_encode && (values_buffer.size() / 4u) <= std::numeric_limits<uint16_t>::max();
364
365 // Only sparse encode if the ratio of populated entries to total entries is below some
366 // threshold.
367 sparse_encode =
368 sparse_encode && ((100 * entries->size()) / num_total_entries) < kSparseEncodingThreshold;
369
370 if (sparse_encode) {
371 type_header->entryCount = util::HostToDevice32(entries->size());
372 type_header->flags |= ResTable_type::FLAG_SPARSE;
373 ResTable_sparseTypeEntry* indices =
374 type_writer.NextBlock<ResTable_sparseTypeEntry>(entries->size());
375 for (size_t i = 0; i < num_total_entries; i++) {
376 if (offsets[i] != ResTable_type::NO_ENTRY) {
377 CHECK((offsets[i] & 0x03) == 0);
378 indices->idx = util::HostToDevice16(i);
379 indices->offset = util::HostToDevice16(offsets[i] / 4u);
380 indices++;
381 }
382 }
383 } else {
384 type_header->entryCount = util::HostToDevice32(num_total_entries);
385 uint32_t* indices = type_writer.NextBlock<uint32_t>(num_total_entries);
386 for (size_t i = 0; i < num_total_entries; i++) {
387 indices[i] = util::HostToDevice32(offsets[i]);
388 }
389 }
390
391 type_header->entriesStart = util::HostToDevice32(type_writer.size());
392 type_writer.buffer()->AppendBuffer(std::move(values_buffer));
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700393 type_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700394 return true;
395 }
396
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700397 std::vector<ResourceTableType*> CollectAndSortTypes() {
398 std::vector<ResourceTableType*> sorted_types;
399 for (auto& type : package_->types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700400 if (type->type == ResourceType::kStyleable) {
401 // Styleables aren't real Resource Types, they are represented in the
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700402 // R.java file.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700403 continue;
404 }
405
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700406 CHECK(bool(type->id)) << "type must have an ID set";
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700407
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700408 sorted_types.push_back(type.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700409 }
Adam Lesinski46708052017-09-29 14:49:15 -0700410 std::sort(sorted_types.begin(), sorted_types.end(), cmp_ids<ResourceTableType>);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700411 return sorted_types;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700412 }
413
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700414 std::vector<ResourceEntry*> CollectAndSortEntries(ResourceTableType* type) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700415 // Sort the entries by entry ID.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700416 std::vector<ResourceEntry*> sorted_entries;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700417 for (auto& entry : type->entries) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700418 CHECK(bool(entry->id)) << "entry must have an ID set";
419 sorted_entries.push_back(entry.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700420 }
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800421 std::sort(sorted_entries.begin(), sorted_entries.end(), cmp_ids<ResourceEntry>);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700422 return sorted_entries;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700423 }
424
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800425 bool FlattenOverlayable(BigBuffer* buffer) {
426 std::set<ResourceId> seen_ids;
427 std::map<std::string, OverlayableChunk> overlayable_chunks;
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800428
429 CHECK(bool(package_->id)) << "package must have an ID set when flattening <overlayable>";
430 for (auto& type : package_->types) {
431 CHECK(bool(type->id)) << "type must have an ID set when flattening <overlayable>";
432 for (auto& entry : type->entries) {
433 CHECK(bool(type->id)) << "entry must have an ID set when flattening <overlayable>";
Ryan Mitchell54237ff2018-12-13 15:44:29 -0800434 if (!entry->overlayable_item) {
Ryan Mitchell1bb1fe02018-11-16 11:21:41 -0800435 continue;
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800436 }
Ryan Mitchell1bb1fe02018-11-16 11:21:41 -0800437
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800438 OverlayableItem& item = entry->overlayable_item.value();
439
440 // Resource ids should only appear once in the resource table
441 ResourceId id = android::make_resid(package_->id.value(), type->id.value(),
442 entry->id.value());
443 CHECK(seen_ids.find(id) == seen_ids.end())
444 << "multiple overlayable definitions found for resource "
445 << ResourceName(package_->name, type->type, entry->name).to_string();
446 seen_ids.insert(id);
447
448 // Find the overlayable chunk with the specified name
449 OverlayableChunk* overlayable_chunk = nullptr;
450 auto iter = overlayable_chunks.find(item.overlayable->name);
451 if (iter == overlayable_chunks.end()) {
452 OverlayableChunk chunk{item.overlayable->actor, item.overlayable->source};
453 overlayable_chunk =
454 &overlayable_chunks.insert({item.overlayable->name, chunk}).first->second;
455 } else {
456 OverlayableChunk& chunk = iter->second;
457 if (!(chunk.source == item.overlayable->source)) {
458 // The name of an overlayable set of resources must be unique
459 context_->GetDiagnostics()->Error(DiagMessage(item.overlayable->source)
460 << "duplicate overlayable name"
461 << item.overlayable->name << "'");
462 context_->GetDiagnostics()->Error(DiagMessage(chunk.source)
463 << "previous declaration here");
464 return false;
465 }
466
467 CHECK(chunk.actor == item.overlayable->actor);
468 overlayable_chunk = &chunk;
Ryan Mitchell1bb1fe02018-11-16 11:21:41 -0800469 }
470
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800471 uint32_t policy_flags = 0;
472 if (item.policies == OverlayableItem::Policy::kNone) {
Ryan Mitchell1bb1fe02018-11-16 11:21:41 -0800473 // Encode overlayable entries defined without a policy as publicly overlayable
474 policy_flags |= ResTable_overlayable_policy_header::POLICY_PUBLIC;
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800475 } else {
476 if (item.policies & OverlayableItem::Policy::kPublic) {
477 policy_flags |= ResTable_overlayable_policy_header::POLICY_PUBLIC;
478 }
479 if (item.policies & OverlayableItem::Policy::kSystem) {
480 policy_flags |= ResTable_overlayable_policy_header::POLICY_SYSTEM_PARTITION;
481 }
482 if (item.policies & OverlayableItem::Policy::kVendor) {
483 policy_flags |= ResTable_overlayable_policy_header::POLICY_VENDOR_PARTITION;
484 }
485 if (item.policies & OverlayableItem::Policy::kProduct) {
486 policy_flags |= ResTable_overlayable_policy_header::POLICY_PRODUCT_PARTITION;
487 }
488 if (item.policies & OverlayableItem::Policy::kProductServices) {
489 policy_flags |= ResTable_overlayable_policy_header::POLICY_PRODUCT_SERVICES_PARTITION;
Ryan Mitchell1bb1fe02018-11-16 11:21:41 -0800490 }
491 }
492
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800493 auto policy = overlayable_chunk->policy_ids.find(policy_flags);
494 if (policy != overlayable_chunk->policy_ids.end()) {
495 policy->second.insert(id);
496 } else {
497 overlayable_chunk->policy_ids.insert(
498 std::make_pair(policy_flags, std::set<ResourceId>{id}));
Ryan Mitchell1bb1fe02018-11-16 11:21:41 -0800499 }
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800500 }
501 }
502
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800503 for (auto& overlayable_pair : overlayable_chunks) {
504 std::string name = overlayable_pair.first;
505 OverlayableChunk& overlayable = overlayable_pair.second;
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800506
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800507 // Write the header of the overlayable chunk
508 ChunkWriter overlayable_writer(buffer);
509 auto* overlayable_type =
510 overlayable_writer.StartChunk<ResTable_overlayable_header>(RES_TABLE_OVERLAYABLE_TYPE);
511 if (name.size() >= arraysize(overlayable_type->name)) {
512 diag_->Error(DiagMessage() << "overlayable name '" << name
513 << "' exceeds maximum length ("
514 << arraysize(overlayable_type->name)
515 << " utf16 characters)");
516 return false;
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800517 }
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800518 strcpy16_htod(overlayable_type->name, arraysize(overlayable_type->name),
519 util::Utf8ToUtf16(name));
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800520
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800521 if (overlayable.actor.size() >= arraysize(overlayable_type->actor)) {
522 diag_->Error(DiagMessage() << "overlayable name '" << overlayable.actor
523 << "' exceeds maximum length ("
524 << arraysize(overlayable_type->actor)
525 << " utf16 characters)");
526 return false;
527 }
528 strcpy16_htod(overlayable_type->actor, arraysize(overlayable_type->actor),
529 util::Utf8ToUtf16(overlayable.actor));
530
531 // Write each policy block for the overlayable
532 for (auto& policy_ids : overlayable.policy_ids) {
533 ChunkWriter policy_writer(buffer);
534 auto* policy_type = policy_writer.StartChunk<ResTable_overlayable_policy_header>(
535 RES_TABLE_OVERLAYABLE_POLICY_TYPE);
536 policy_type->policy_flags = util::HostToDevice32(static_cast<uint32_t>(policy_ids.first));
537 policy_type->entry_count = util::HostToDevice32(static_cast<uint32_t>(
538 policy_ids.second.size()));
539 // Write the ids after the policy header
540 auto* id_block = policy_writer.NextBlock<ResTable_ref>(policy_ids.second.size());
541 for (const ResourceId& id : policy_ids.second) {
542 id_block->ident = util::HostToDevice32(id.id);
543 id_block++;
544 }
545 policy_writer.Finish();
546 }
547 overlayable_writer.Finish();
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800548 }
549
Ryan Mitchellef5673a2018-12-12 18:45:34 -0800550 return true;
Ryan Mitchell75e20dd2018-11-06 16:39:36 -0800551 }
552
Adam Lesinski46708052017-09-29 14:49:15 -0700553 bool FlattenTypeSpec(ResourceTableType* type, std::vector<ResourceEntry*>* sorted_entries,
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700554 BigBuffer* buffer) {
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700555 ChunkWriter type_spec_writer(buffer);
556 ResTable_typeSpec* spec_header =
Adam Lesinski46708052017-09-29 14:49:15 -0700557 type_spec_writer.StartChunk<ResTable_typeSpec>(RES_TABLE_TYPE_SPEC_TYPE);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700558 spec_header->id = type->id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700559
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700560 if (sorted_entries->empty()) {
561 type_spec_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700562 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700563 }
564
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700565 // We can't just take the size of the vector. There may be holes in the
566 // entry ID space.
567 // Since the entries are sorted by ID, the last one will be the biggest.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700568 const size_t num_entries = sorted_entries->back()->id.value() + 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700569
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700570 spec_header->entryCount = util::HostToDevice32(num_entries);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700571
572 // Reserve space for the masks of each resource in this type. These
573 // show for which configuration axis the resource changes.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700574 uint32_t* config_masks = type_spec_writer.NextBlock<uint32_t>(num_entries);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700575
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700576 const size_t actual_num_entries = sorted_entries->size();
577 for (size_t entryIndex = 0; entryIndex < actual_num_entries; entryIndex++) {
578 ResourceEntry* entry = sorted_entries->at(entryIndex);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700579
580 // Populate the config masks for this entry.
581
Adam Lesinski71be7052017-12-12 16:48:07 -0800582 if (entry->visibility.level == Visibility::Level::kPublic) {
Adam Lesinski46708052017-09-29 14:49:15 -0700583 config_masks[entry->id.value()] |= util::HostToDevice32(ResTable_typeSpec::SPEC_PUBLIC);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700584 }
585
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700586 const size_t config_count = entry->values.size();
587 for (size_t i = 0; i < config_count; i++) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700588 const ConfigDescription& config = entry->values[i]->config;
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700589 for (size_t j = i + 1; j < config_count; j++) {
590 config_masks[entry->id.value()] |=
591 util::HostToDevice32(config.diff(entry->values[j]->config));
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700592 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700593 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700594 }
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700595 type_spec_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700596 return true;
597 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700598
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700599 bool FlattenTypes(BigBuffer* buffer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700600 // Sort the types by their IDs. They will be inserted into the StringPool in
601 // this order.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700602 std::vector<ResourceTableType*> sorted_types = CollectAndSortTypes();
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700603
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700604 size_t expected_type_id = 1;
605 for (ResourceTableType* type : sorted_types) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700606 // If there is a gap in the type IDs, fill in the StringPool
607 // with empty values until we reach the ID we expect.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700608 while (type->id.value() > expected_type_id) {
609 std::stringstream type_name;
610 type_name << "?" << expected_type_id;
611 type_pool_.MakeRef(type_name.str());
612 expected_type_id++;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700613 }
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700614 expected_type_id++;
Adam Lesinski93190b72017-11-03 15:20:17 -0700615 type_pool_.MakeRef(to_string(type->type));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700616
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700617 std::vector<ResourceEntry*> sorted_entries = CollectAndSortEntries(type);
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800618 if (sorted_entries.empty()) {
619 continue;
620 }
621
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700622 if (!FlattenTypeSpec(type, &sorted_entries, buffer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700623 return false;
624 }
625
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800626 // Since the entries are sorted by ID, the last ID will be the largest.
627 const size_t num_entries = sorted_entries.back()->id.value() + 1;
628
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700629 // The binary resource table lists resource entries for each
630 // configuration.
631 // We store them inverted, where a resource entry lists the values for
632 // each
633 // configuration available. Here we reverse this to match the binary
634 // table.
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800635 std::map<ConfigDescription, std::vector<FlatEntry>> config_to_entry_list_map;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700636
Luke Nicholsonb0643302017-12-01 15:29:03 -0800637 // hardcoded string uses characters which make it an invalid resource name
638 const std::string obfuscated_resource_name = "0_resource_name_obfuscated";
639
640 for (ResourceEntry* entry : sorted_entries) {
641 uint32_t local_key_index;
642 if (!collapse_key_stringpool_ ||
643 whitelisted_resources_.find(entry->name) != whitelisted_resources_.end()) {
644 local_key_index = (uint32_t)key_pool_.MakeRef(entry->name).index();
645 } else {
646 // resource isn't whitelisted, add it as obfuscated value
647 local_key_index = (uint32_t)key_pool_.MakeRef(obfuscated_resource_name).index();
648 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700649 // Group values by configuration.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700650 for (auto& config_value : entry->values) {
651 config_to_entry_list_map[config_value->config].push_back(
Luke Nicholsonb0643302017-12-01 15:29:03 -0800652 FlatEntry{entry, config_value->value.get(), local_key_index});
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700653 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700654 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700655
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700656 // Flatten a configuration value.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700657 for (auto& entry : config_to_entry_list_map) {
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800658 if (!FlattenConfig(type, entry.first, num_entries, &entry.second, buffer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700660 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700661 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700662 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700663 return true;
664 }
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700665
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800666 void FlattenLibrarySpec(BigBuffer* buffer) {
667 ChunkWriter lib_writer(buffer);
668 ResTable_lib_header* lib_header =
669 lib_writer.StartChunk<ResTable_lib_header>(RES_TABLE_LIBRARY_TYPE);
670
671 const size_t num_entries = (package_->id.value() == 0x00 ? 1 : 0) + shared_libs_->size();
672 CHECK(num_entries > 0);
673
674 lib_header->count = util::HostToDevice32(num_entries);
675
676 ResTable_lib_entry* lib_entry = buffer->NextBlock<ResTable_lib_entry>(num_entries);
677 if (package_->id.value() == 0x00) {
678 // Add this package
679 lib_entry->packageId = util::HostToDevice32(0x00);
680 strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName),
681 util::Utf8ToUtf16(package_->name));
682 ++lib_entry;
683 }
684
685 for (auto& map_entry : *shared_libs_) {
686 lib_entry->packageId = util::HostToDevice32(map_entry.first);
687 strcpy16_htod(lib_entry->packageName, arraysize(lib_entry->packageName),
688 util::Utf8ToUtf16(map_entry.second));
689 ++lib_entry;
690 }
691 lib_writer.Finish();
692 }
693
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800694 IAaptContext* context_;
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700695 IDiagnostics* diag_;
696 ResourceTablePackage* package_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800697 const std::map<size_t, std::string>* shared_libs_;
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800698 bool use_sparse_entries_;
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700699 StringPool type_pool_;
700 StringPool key_pool_;
Luke Nicholsonb0643302017-12-01 15:29:03 -0800701 bool collapse_key_stringpool_;
702 const std::set<std::string>& whitelisted_resources_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700703};
704
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705} // namespace
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700706
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700707bool TableFlattener::Consume(IAaptContext* context, ResourceTable* table) {
Ryan Mitchell4e9a9222018-11-13 10:40:07 -0800708 if (options_.sort_stringpool_entries) {
709 // We must do this before writing the resources, since the string pool IDs may change.
710 table->string_pool.Prune();
711 table->string_pool.Sort([](const StringPool::Context &a, const StringPool::Context &b) -> int {
712 int diff = util::compare(a.priority, b.priority);
713 if (diff == 0) {
714 diff = a.config.compare(b.config);
715 }
716 return diff;
717 });
718 }
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700719
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700720 // Write the ResTable header.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700721 ChunkWriter table_writer(buffer_);
Adam Lesinski4ca56972017-04-26 21:49:53 -0700722 ResTable_header* table_header = table_writer.StartChunk<ResTable_header>(RES_TABLE_TYPE);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700723 table_header->packageCount = util::HostToDevice32(table->packages.size());
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700724
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700725 // Flatten the values string pool.
Ryan Mitchella15c2a82018-03-26 11:05:31 -0700726 StringPool::FlattenUtf8(table_writer.buffer(), table->string_pool,
727 context->GetDiagnostics());
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700728
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700729 BigBuffer package_buffer(1024);
Adam Lesinski9ba47d82015-10-13 11:37:10 -0700730
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731 // Flatten each package.
732 for (auto& package : table->packages) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700733 if (context->GetPackageType() == PackageType::kApp) {
734 // Write a self mapping entry for this package if the ID is non-standard (0x7f).
735 const uint8_t package_id = package->id.value();
736 if (package_id != kFrameworkPackageId && package_id != kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800737 auto result = table->included_packages_.insert({package_id, package->name});
738 if (!result.second && result.first->second != package->name) {
739 // A mapping for this package ID already exists, and is a different package. Error!
740 context->GetDiagnostics()->Error(
741 DiagMessage() << android::base::StringPrintf(
742 "can't map package ID %02x to '%s'. Already mapped to '%s'", package_id,
743 package->name.c_str(), result.first->second.c_str()));
744 return false;
745 }
Adam Lesinski8780eb62017-10-31 17:44:39 -0700746 }
747 }
748
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800749 PackageFlattener flattener(context, package.get(), &table->included_packages_,
Luke Nicholsonb0643302017-12-01 15:29:03 -0800750 options_.use_sparse_entries, options_.collapse_key_stringpool,
751 options_.whitelisted_resources);
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700752 if (!flattener.FlattenPackage(&package_buffer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700753 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700754 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700755 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700756
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700757 // Finally merge all the packages into the main buffer.
Adam Lesinskice5e56e22016-10-21 17:56:45 -0700758 table_writer.buffer()->AppendBuffer(std::move(package_buffer));
759 table_writer.Finish();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700760 return true;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700761}
762
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700763} // namespace aapt