1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "ResourceTable.h"
18
19 #include <algorithm>
20 #include <memory>
21 #include <optional>
22 #include <tuple>
23
24 #include "android-base/logging.h"
25 #include "androidfw/ConfigDescription.h"
26 #include "androidfw/ResourceTypes.h"
27
28 #include "NameMangler.h"
29 #include "ResourceUtils.h"
30 #include "ResourceValues.h"
31 #include "ValueVisitor.h"
32 #include "text/Unicode.h"
33 #include "trace/TraceBuffer.h"
34 #include "util/Util.h"
35
36 using ::aapt::text::IsValidResourceEntryName;
37 using ::android::ConfigDescription;
38 using ::android::StringPiece;
39 using ::android::base::StringPrintf;
40
41 namespace aapt {
42
43 const char* Overlayable::kActorScheme = "overlay";
44
45 namespace {
less_than_type(const std::unique_ptr<ResourceTableType> & lhs,const ResourceNamedTypeRef & rhs)46 bool less_than_type(const std::unique_ptr<ResourceTableType>& lhs,
47 const ResourceNamedTypeRef& rhs) {
48 return lhs->named_type < rhs;
49 }
50
51 template <typename T>
less_than_struct_with_name(const std::unique_ptr<T> & lhs,StringPiece rhs)52 bool less_than_struct_with_name(const std::unique_ptr<T>& lhs, StringPiece rhs) {
53 return lhs->name.compare(0, lhs->name.size(), rhs.data(), rhs.size()) < 0;
54 }
55
56 template <typename T>
greater_than_struct_with_name(StringPiece lhs,const std::unique_ptr<T> & rhs)57 bool greater_than_struct_with_name(StringPiece lhs, const std::unique_ptr<T>& rhs) {
58 return rhs->name.compare(0, rhs->name.size(), lhs.data(), lhs.size()) > 0;
59 }
60
61 template <typename T>
62 struct NameEqualRange {
operator ()aapt::__anone7635bc10111::NameEqualRange63 bool operator()(const std::unique_ptr<T>& lhs, StringPiece rhs) const {
64 return less_than_struct_with_name<T>(lhs, rhs);
65 }
operator ()aapt::__anone7635bc10111::NameEqualRange66 bool operator()(StringPiece lhs, const std::unique_ptr<T>& rhs) const {
67 return greater_than_struct_with_name<T>(lhs, rhs);
68 }
69 };
70
71 template <typename T, typename U>
less_than_struct_with_name_and_id(const T & lhs,const std::pair<std::string_view,std::optional<U>> & rhs)72 bool less_than_struct_with_name_and_id(const T& lhs,
73 const std::pair<std::string_view, std::optional<U>>& rhs) {
74 if (lhs.id != rhs.second) {
75 return lhs.id < rhs.second;
76 }
77 return lhs.name.compare(0, lhs.name.size(), rhs.first.data(), rhs.first.size()) < 0;
78 }
79
80 template <typename T, typename Func, typename Elements>
FindElementsRunAction(android::StringPiece name,Elements & entries,Func action)81 T* FindElementsRunAction(android::StringPiece name, Elements& entries, Func action) {
82 const auto iter =
83 std::lower_bound(entries.begin(), entries.end(), name, less_than_struct_with_name<T>);
84 const bool found = iter != entries.end() && name == (*iter)->name;
85 return action(found, iter);
86 }
87
88 struct ConfigKey {
89 const ConfigDescription* config;
90 StringPiece product;
91 };
92
93 template <typename T>
lt_config_key_ref(const T & lhs,const ConfigKey & rhs)94 bool lt_config_key_ref(const T& lhs, const ConfigKey& rhs) {
95 int cmp = lhs->config.compare(*rhs.config);
96 if (cmp == 0) {
97 cmp = StringPiece(lhs->product).compare(rhs.product);
98 }
99 return cmp < 0;
100 }
101
102 } // namespace
103
ResourceTable(ResourceTable::Validation validation)104 ResourceTable::ResourceTable(ResourceTable::Validation validation) : validation_(validation) {
105 }
106
FindPackage(android::StringPiece name) const107 ResourceTablePackage* ResourceTable::FindPackage(android::StringPiece name) const {
108 return FindElementsRunAction<ResourceTablePackage>(
109 name, packages, [&](bool found, auto& iter) { return found ? iter->get() : nullptr; });
110 }
111
FindOrCreatePackage(android::StringPiece name)112 ResourceTablePackage* ResourceTable::FindOrCreatePackage(android::StringPiece name) {
113 return FindElementsRunAction<ResourceTablePackage>(name, packages, [&](bool found, auto& iter) {
114 return found ? iter->get() : packages.emplace(iter, new ResourceTablePackage(name))->get();
115 });
116 }
117
118 template <typename Func, typename Elements>
FindTypeRunAction(const ResourceNamedTypeRef & type,Elements & entries,Func action)119 static ResourceTableType* FindTypeRunAction(const ResourceNamedTypeRef& type, Elements& entries,
120 Func action) {
121 const auto iter = std::lower_bound(entries.begin(), entries.end(), type, less_than_type);
122 const bool found = iter != entries.end() && type == (*iter)->named_type;
123 return action(found, iter);
124 }
125
FindTypeWithDefaultName(const ResourceType type) const126 ResourceTableType* ResourceTablePackage::FindTypeWithDefaultName(const ResourceType type) const {
127 auto named_type = ResourceNamedTypeWithDefaultName(type);
128 return FindType(named_type);
129 }
130
FindType(const ResourceNamedTypeRef & type) const131 ResourceTableType* ResourceTablePackage::FindType(const ResourceNamedTypeRef& type) const {
132 return FindTypeRunAction(type, types,
133 [&](bool found, auto& iter) { return found ? iter->get() : nullptr; });
134 }
135
FindOrCreateType(const ResourceNamedTypeRef & type)136 ResourceTableType* ResourceTablePackage::FindOrCreateType(const ResourceNamedTypeRef& type) {
137 return FindTypeRunAction(type, types, [&](bool found, auto& iter) {
138 return found ? iter->get() : types.emplace(iter, new ResourceTableType(type))->get();
139 });
140 }
141
CreateEntry(android::StringPiece name)142 ResourceEntry* ResourceTableType::CreateEntry(android::StringPiece name) {
143 return FindElementsRunAction<ResourceEntry>(name, entries, [&](bool found, auto& iter) {
144 return entries.emplace(iter, new ResourceEntry(name))->get();
145 });
146 }
147
FindEntry(android::StringPiece name) const148 ResourceEntry* ResourceTableType::FindEntry(android::StringPiece name) const {
149 return FindElementsRunAction<ResourceEntry>(
150 name, entries, [&](bool found, auto& iter) { return found ? iter->get() : nullptr; });
151 }
152
FindOrCreateEntry(android::StringPiece name)153 ResourceEntry* ResourceTableType::FindOrCreateEntry(android::StringPiece name) {
154 return FindElementsRunAction<ResourceEntry>(name, entries, [&](bool found, auto& iter) {
155 return found ? iter->get() : entries.emplace(iter, new ResourceEntry(name))->get();
156 });
157 }
158
FindValue(const ConfigDescription & config,android::StringPiece product)159 ResourceConfigValue* ResourceEntry::FindValue(const ConfigDescription& config,
160 android::StringPiece product) {
161 auto iter = std::lower_bound(values.begin(), values.end(), ConfigKey{&config, product},
162 lt_config_key_ref<std::unique_ptr<ResourceConfigValue>>);
163 if (iter != values.end()) {
164 ResourceConfigValue* value = iter->get();
165 if (value->config == config && StringPiece(value->product) == product) {
166 return value;
167 }
168 }
169 return nullptr;
170 }
171
FindValue(const android::ConfigDescription & config,android::StringPiece product) const172 const ResourceConfigValue* ResourceEntry::FindValue(const android::ConfigDescription& config,
173 android::StringPiece product) const {
174 auto iter = std::lower_bound(values.begin(), values.end(), ConfigKey{&config, product},
175 lt_config_key_ref<std::unique_ptr<ResourceConfigValue>>);
176 if (iter != values.end()) {
177 ResourceConfigValue* value = iter->get();
178 if (value->config == config && StringPiece(value->product) == product) {
179 return value;
180 }
181 }
182 return nullptr;
183 }
184
FindOrCreateValue(const ConfigDescription & config,StringPiece product)185 ResourceConfigValue* ResourceEntry::FindOrCreateValue(const ConfigDescription& config,
186 StringPiece product) {
187 auto iter = std::lower_bound(values.begin(), values.end(), ConfigKey{&config, product},
188 lt_config_key_ref<std::unique_ptr<ResourceConfigValue>>);
189 if (iter != values.end()) {
190 ResourceConfigValue* value = iter->get();
191 if (value->config == config && StringPiece(value->product) == product) {
192 return value;
193 }
194 }
195 ResourceConfigValue* newValue =
196 values.insert(iter, util::make_unique<ResourceConfigValue>(config, product))->get();
197 return newValue;
198 }
199
FindAllValues(const ConfigDescription & config)200 std::vector<ResourceConfigValue*> ResourceEntry::FindAllValues(const ConfigDescription& config) {
201 std::vector<ResourceConfigValue*> results;
202
203 auto iter = values.begin();
204 for (; iter != values.end(); ++iter) {
205 ResourceConfigValue* value = iter->get();
206 if (value->config == config) {
207 results.push_back(value);
208 ++iter;
209 break;
210 }
211 }
212
213 for (; iter != values.end(); ++iter) {
214 ResourceConfigValue* value = iter->get();
215 if (value->config == config) {
216 results.push_back(value);
217 }
218 }
219 return results;
220 }
221
HasDefaultValue() const222 bool ResourceEntry::HasDefaultValue() const {
223 const ConfigDescription& default_config = ConfigDescription::DefaultConfig();
224
225 // The default config should be at the top of the list, since the list is sorted.
226 for (auto& config_value : values) {
227 if (config_value->config == default_config) {
228 return true;
229 }
230 }
231 return false;
232 }
233
234 // The default handler for collisions.
235 //
236 // Typically, a weak value will be overridden by a strong value. An existing weak
237 // value will not be overridden by an incoming weak value.
238 //
239 // There are some exceptions:
240 //
241 // Attributes: There are two types of Attribute values: USE and DECL.
242 //
243 // USE is anywhere an Attribute is declared without a format, and in a place that would
244 // be legal to declare if the Attribute already existed. This is typically in a
245 // <declare-styleable> tag. Attributes defined in a <declare-styleable> are also weak.
246 //
247 // DECL is an absolute declaration of an Attribute and specifies an explicit format.
248 //
249 // A DECL will override a USE without error. Two DECLs must match in their format for there to be
250 // no error.
ResolveValueCollision(Value * existing,Value * incoming)251 ResourceTable::CollisionResult ResourceTable::ResolveValueCollision(Value* existing,
252 Value* incoming) {
253 Attribute* existing_attr = ValueCast<Attribute>(existing);
254 Attribute* incoming_attr = ValueCast<Attribute>(incoming);
255 if (!incoming_attr) {
256 if (incoming->IsWeak()) {
257 // We're trying to add a weak resource but a resource
258 // already exists. Keep the existing.
259 return CollisionResult::kKeepOriginal;
260 } else if (existing->IsWeak()) {
261 // Override the weak resource with the new strong resource.
262 return CollisionResult::kTakeNew;
263 }
264 // The existing and incoming values are strong, this is an error
265 // if the values are not both attributes.
266 return CollisionResult::kConflict;
267 }
268
269 if (!existing_attr) {
270 if (existing->IsWeak()) {
271 // The existing value is not an attribute and it is weak,
272 // so take the incoming attribute value.
273 return CollisionResult::kTakeNew;
274 }
275 // The existing value is not an attribute and it is strong,
276 // so the incoming attribute value is an error.
277 return CollisionResult::kConflict;
278 }
279
280 CHECK(incoming_attr != nullptr && existing_attr != nullptr);
281
282 //
283 // Attribute specific handling. At this point we know both
284 // values are attributes. Since we can declare and define
285 // attributes all-over, we do special handling to see
286 // which definition sticks.
287 //
288 if (existing_attr->IsCompatibleWith(*incoming_attr)) {
289 // The two attributes are both DECLs, but they are plain attributes with compatible formats.
290 // Keep the strongest one.
291 return existing_attr->IsWeak() ? CollisionResult::kTakeNew : CollisionResult::kKeepOriginal;
292 }
293
294 if (existing_attr->IsWeak() && existing_attr->type_mask == android::ResTable_map::TYPE_ANY) {
295 // Any incoming attribute is better than this.
296 return CollisionResult::kTakeNew;
297 }
298
299 if (incoming_attr->IsWeak() && incoming_attr->type_mask == android::ResTable_map::TYPE_ANY) {
300 // The incoming attribute may be a USE instead of a DECL.
301 // Keep the existing attribute.
302 return CollisionResult::kKeepOriginal;
303 }
304
305 return CollisionResult::kConflict;
306 }
307
308 namespace {
309 template <typename T, typename Comparer>
310 struct SortedVectorInserter : public Comparer {
LowerBoundaapt::__anone7635bc10911::SortedVectorInserter311 std::pair<bool, typename std::vector<T>::iterator> LowerBound(std::vector<T>& el,
312 const T& value) {
313 auto it = std::lower_bound(el.begin(), el.end(), value, [&](auto& lhs, auto& rhs) {
314 return Comparer::operator()(lhs, rhs);
315 });
316 bool found =
317 it != el.end() && !Comparer::operator()(*it, value) && !Comparer::operator()(value, *it);
318 return std::make_pair(found, it);
319 }
320
Insertaapt::__anone7635bc10911::SortedVectorInserter321 T* Insert(std::vector<T>& el, T&& value) {
322 auto [found, it] = LowerBound(el, value);
323 if (found) {
324 return &*it;
325 }
326 return &*el.insert(it, std::forward<T>(value));
327 }
328 };
329
330 struct PackageViewComparer {
operator ()aapt::__anone7635bc10911::PackageViewComparer331 bool operator()(const ResourceTablePackageView& lhs, const ResourceTablePackageView& rhs) {
332 return less_than_struct_with_name_and_id<ResourceTablePackageView, uint8_t>(
333 lhs, std::make_pair(rhs.name, rhs.id));
334 }
335 };
336
337 struct TypeViewComparer {
operator ()aapt::__anone7635bc10911::TypeViewComparer338 bool operator()(const ResourceTableTypeView& lhs, const ResourceTableTypeView& rhs) {
339 return lhs.id != rhs.id ? lhs.id < rhs.id : lhs.named_type < rhs.named_type;
340 }
341 };
342
343 struct EntryViewComparer {
operator ()aapt::__anone7635bc10911::EntryViewComparer344 bool operator()(const ResourceTableEntryView& lhs, const ResourceTableEntryView& rhs) {
345 return less_than_struct_with_name_and_id<ResourceTableEntryView, uint16_t>(
346 lhs, std::make_pair(rhs.name, rhs.id));
347 }
348 };
349
InsertEntryIntoTableView(ResourceTableView & table,const ResourceTablePackage * package,const ResourceTableType * type,const std::string & entry_name,const std::optional<ResourceId> & id,const Visibility & visibility,const std::optional<AllowNew> & allow_new,const std::optional<OverlayableItem> & overlayable_item,const std::optional<StagedId> & staged_id,const std::vector<std::unique_ptr<ResourceConfigValue>> & values)350 void InsertEntryIntoTableView(ResourceTableView& table, const ResourceTablePackage* package,
351 const ResourceTableType* type, const std::string& entry_name,
352 const std::optional<ResourceId>& id, const Visibility& visibility,
353 const std::optional<AllowNew>& allow_new,
354 const std::optional<OverlayableItem>& overlayable_item,
355 const std::optional<StagedId>& staged_id,
356 const std::vector<std::unique_ptr<ResourceConfigValue>>& values) {
357 SortedVectorInserter<ResourceTablePackageView, PackageViewComparer> package_inserter;
358 SortedVectorInserter<ResourceTableTypeView, TypeViewComparer> type_inserter;
359 SortedVectorInserter<ResourceTableEntryView, EntryViewComparer> entry_inserter;
360
361 ResourceTablePackageView new_package{package->name,
362 id ? id.value().package_id() : std::optional<uint8_t>{}};
363 auto view_package = package_inserter.Insert(table.packages, std::move(new_package));
364
365 ResourceTableTypeView new_type{type->named_type,
366 id ? id.value().type_id() : std::optional<uint8_t>{}};
367 auto view_type = type_inserter.Insert(view_package->types, std::move(new_type));
368
369 if (visibility.level == Visibility::Level::kPublic) {
370 // Only mark the type visibility level as public, it doesn't care about being private.
371 view_type->visibility_level = Visibility::Level::kPublic;
372 }
373
374 ResourceTableEntryView new_entry{.name = entry_name,
375 .id = id ? id.value().entry_id() : std::optional<uint16_t>{},
376 .visibility = visibility,
377 .allow_new = allow_new,
378 .overlayable_item = overlayable_item,
379 .staged_id = staged_id};
380 for (auto& value : values) {
381 new_entry.values.emplace_back(value.get());
382 }
383
384 entry_inserter.Insert(view_type->entries, std::move(new_entry));
385 }
386 } // namespace
387
FindValue(const ConfigDescription & config,android::StringPiece product) const388 const ResourceConfigValue* ResourceTableEntryView::FindValue(const ConfigDescription& config,
389 android::StringPiece product) const {
390 auto iter = std::lower_bound(values.begin(), values.end(), ConfigKey{&config, product},
391 lt_config_key_ref<const ResourceConfigValue*>);
392 if (iter != values.end()) {
393 const ResourceConfigValue* value = *iter;
394 if (value->config == config && StringPiece(value->product) == product) {
395 return value;
396 }
397 }
398 return nullptr;
399 }
400
GetPartitionedView(const ResourceTableViewOptions & options) const401 ResourceTableView ResourceTable::GetPartitionedView(const ResourceTableViewOptions& options) const {
402 ResourceTableView view;
403 for (const auto& package : packages) {
404 for (const auto& type : package->types) {
405 for (const auto& entry : type->entries) {
406 InsertEntryIntoTableView(view, package.get(), type.get(), entry->name, entry->id,
407 entry->visibility, entry->allow_new, entry->overlayable_item,
408 entry->staged_id, entry->values);
409
410 if (options.create_alias_entries && entry->staged_id) {
411 auto alias_id = entry->staged_id.value().id;
412 InsertEntryIntoTableView(view, package.get(), type.get(), entry->name, alias_id,
413 entry->visibility, entry->allow_new, entry->overlayable_item, {},
414 entry->values);
415 }
416 }
417 }
418 }
419
420 // The android runtime does not support querying resources when the there are multiple type ids
421 // for the same resource type within the same package. For this reason, if there are types with
422 // multiple type ids, each type needs to exist in its own package in order to be queried by name.
423 std::vector<ResourceTablePackageView> new_packages;
424 SortedVectorInserter<ResourceTablePackageView, PackageViewComparer> package_inserter;
425 SortedVectorInserter<ResourceTableTypeView, TypeViewComparer> type_inserter;
426 for (auto& package : view.packages) {
427 // If a new package was already created for a different type within this package, then
428 // we can reuse those packages for other types that need to be extracted from this package.
429 // `start_index` is the index of the first newly created package that can be reused.
430 const size_t start_index = new_packages.size();
431 std::map<ResourceNamedType, size_t> type_new_package_index;
432 for (auto type_it = package.types.begin(); type_it != package.types.end();) {
433 auto& type = *type_it;
434 auto type_index_iter = type_new_package_index.find(type.named_type);
435 if (type_index_iter == type_new_package_index.end()) {
436 // First occurrence of the resource type in this package. Keep it in this package.
437 type_new_package_index.insert(type_index_iter,
438 std::make_pair(type.named_type, start_index));
439 ++type_it;
440 continue;
441 }
442
443 // The resource type has already been seen for this package, so this type must be extracted to
444 // a new separate package.
445 const size_t index = type_index_iter->second;
446 if (new_packages.size() == index) {
447 new_packages.emplace_back(ResourceTablePackageView{package.name, package.id});
448 }
449
450 // Move the type into a new package
451 auto& other_package = new_packages[index];
452 type_new_package_index[type.named_type] = index + 1;
453 type_inserter.Insert(other_package.types, std::move(type));
454 type_it = package.types.erase(type_it);
455 }
456 }
457
458 for (auto& new_package : new_packages) {
459 // Insert newly created packages after their original packages
460 auto [_, it] = package_inserter.LowerBound(view.packages, new_package);
461 view.packages.insert(++it, std::move(new_package));
462 }
463
464 return view;
465 }
466
AddResource(NewResource && res,android::IDiagnostics * diag)467 bool ResourceTable::AddResource(NewResource&& res, android::IDiagnostics* diag) {
468 CHECK(diag != nullptr) << "Diagnostic pointer is null";
469
470 const bool validate = validation_ == Validation::kEnabled;
471 const android::Source source = res.value ? res.value->GetSource() : android::Source{};
472 if (validate && !res.allow_mangled && !IsValidResourceEntryName(res.name.entry)) {
473 diag->Error(android::DiagMessage(source)
474 << "resource '" << res.name << "' has invalid entry name '" << res.name.entry);
475 return false;
476 }
477
478 if (res.id.has_value() && !res.id->first.is_valid()) {
479 diag->Error(android::DiagMessage(source)
480 << "trying to add resource '" << res.name << "' with ID " << res.id->first
481 << " but that ID is invalid");
482 return false;
483 }
484
485 auto package = FindOrCreatePackage(res.name.package);
486 auto type = package->FindOrCreateType(res.name.type);
487 auto entry_it = std::equal_range(type->entries.begin(), type->entries.end(), res.name.entry,
488 NameEqualRange<ResourceEntry>{});
489 const size_t entry_count = std::distance(entry_it.first, entry_it.second);
490
491 ResourceEntry* entry;
492 if (entry_count == 0) {
493 // Adding a new resource
494 entry = type->CreateEntry(res.name.entry);
495 } else if (entry_count == 1) {
496 // Assume that the existing resource is being modified
497 entry = entry_it.first->get();
498 } else {
499 // Multiple resources with the same name exist in the resource table. The only way to
500 // distinguish between them is using resource id since each resource should have a unique id.
501 CHECK(res.id.has_value()) << "ambiguous modification of resource entry '" << res.name
502 << "' without specifying a resource id.";
503 entry = entry_it.first->get();
504 for (auto it = entry_it.first; it != entry_it.second; ++it) {
505 CHECK((bool)(*it)->id) << "ambiguous modification of resource entry '" << res.name
506 << "' with multiple entries without resource ids";
507 if ((*it)->id == res.id->first) {
508 entry = it->get();
509 break;
510 }
511 }
512 }
513
514 if (res.id.has_value()) {
515 if (entry->id && entry->id.value() != res.id->first) {
516 if (res.id->second != OnIdConflict::CREATE_ENTRY) {
517 diag->Error(android::DiagMessage(source)
518 << "trying to add resource '" << res.name << "' with ID " << res.id->first
519 << " but resource already has ID " << entry->id.value());
520 return false;
521 }
522 entry = type->CreateEntry(res.name.entry);
523 }
524 entry->id = res.id->first;
525 }
526
527 if (res.visibility.has_value()) {
528 // Only mark the type visibility level as public, it doesn't care about being private.
529 if (res.visibility->level == Visibility::Level::kPublic) {
530 type->visibility_level = Visibility::Level::kPublic;
531 }
532
533 if (res.visibility->level > entry->visibility.level) {
534 // This symbol definition takes precedence, replace.
535 entry->visibility = res.visibility.value();
536 }
537
538 if (res.visibility->staged_api) {
539 entry->visibility.staged_api = entry->visibility.staged_api;
540 }
541 }
542
543 if (res.overlayable.has_value()) {
544 if (entry->overlayable_item) {
545 diag->Error(android::DiagMessage(res.overlayable->source)
546 << "duplicate overlayable declaration for resource '" << res.name << "'");
547 diag->Error(android::DiagMessage(entry->overlayable_item.value().source)
548 << "previous declaration here");
549 return false;
550 }
551 entry->overlayable_item = res.overlayable.value();
552 }
553
554 if (res.allow_new.has_value()) {
555 entry->allow_new = res.allow_new.value();
556 }
557
558 if (res.staged_id.has_value()) {
559 entry->staged_id = res.staged_id.value();
560 }
561
562 if (res.value != nullptr) {
563 auto config_value = entry->FindOrCreateValue(res.config, res.product);
564 if (!config_value->value) {
565 // Resource does not exist, add it now.
566 config_value->value = std::move(res.value);
567 } else {
568 // When validation is enabled, ensure that a resource cannot have multiple values defined for
569 // the same configuration.
570 auto result = validate ? ResolveValueCollision(config_value->value.get(), res.value.get())
571 : CollisionResult::kKeepBoth;
572 switch (result) {
573 case CollisionResult::kKeepBoth:
574 // Insert the value ignoring for duplicate configurations
575 entry->values.push_back(util::make_unique<ResourceConfigValue>(res.config, res.product));
576 entry->values.back()->value = std::move(res.value);
577 break;
578
579 case CollisionResult::kTakeNew:
580 // Take the incoming value.
581 config_value->value = std::move(res.value);
582 break;
583
584 case CollisionResult::kConflict:
585 diag->Error(android::DiagMessage(source)
586 << "duplicate value for resource '" << res.name << "' "
587 << "with config '" << res.config << "'");
588 diag->Error(android::DiagMessage(source) << "resource previously defined here");
589 return false;
590
591 case CollisionResult::kKeepOriginal:
592 break;
593 }
594 }
595 }
596
597 return true;
598 }
599
FindResource(const ResourceNameRef & name) const600 std::optional<ResourceTable::SearchResult> ResourceTable::FindResource(
601 const ResourceNameRef& name) const {
602 ResourceTablePackage* package = FindPackage(name.package);
603 if (package == nullptr) {
604 return {};
605 }
606
607 ResourceTableType* type = package->FindType(name.type);
608 if (type == nullptr) {
609 return {};
610 }
611
612 ResourceEntry* entry = type->FindEntry(name.entry);
613 if (entry == nullptr) {
614 return {};
615 }
616 return SearchResult{package, type, entry};
617 }
618
FindResource(const ResourceNameRef & name,ResourceId id) const619 std::optional<ResourceTable::SearchResult> ResourceTable::FindResource(const ResourceNameRef& name,
620 ResourceId id) const {
621 ResourceTablePackage* package = FindPackage(name.package);
622 if (package == nullptr) {
623 return {};
624 }
625
626 ResourceTableType* type = package->FindType(name.type);
627 if (type == nullptr) {
628 return {};
629 }
630
631 auto entry_it = std::equal_range(type->entries.begin(), type->entries.end(), name.entry,
632 NameEqualRange<ResourceEntry>{});
633 for (auto it = entry_it.first; it != entry_it.second; ++it) {
634 if ((*it)->id == id) {
635 return SearchResult{package, type, it->get()};
636 }
637 }
638 return {};
639 }
640
RemoveResource(const ResourceNameRef & name,ResourceId id) const641 bool ResourceTable::RemoveResource(const ResourceNameRef& name, ResourceId id) const {
642 ResourceTablePackage* package = FindPackage(name.package);
643 if (package == nullptr) {
644 return {};
645 }
646
647 ResourceTableType* type = package->FindType(name.type);
648 if (type == nullptr) {
649 return {};
650 }
651
652 auto entry_it = std::equal_range(type->entries.begin(), type->entries.end(), name.entry,
653 NameEqualRange<ResourceEntry>{});
654 for (auto it = entry_it.first; it != entry_it.second; ++it) {
655 if ((*it)->id == id) {
656 type->entries.erase(it);
657 return true;
658 }
659 }
660 return false;
661 }
662
Clone() const663 std::unique_ptr<ResourceTable> ResourceTable::Clone() const {
664 std::unique_ptr<ResourceTable> new_table = util::make_unique<ResourceTable>();
665 CloningValueTransformer cloner(&new_table->string_pool);
666 for (const auto& pkg : packages) {
667 ResourceTablePackage* new_pkg = new_table->FindOrCreatePackage(pkg->name);
668 for (const auto& type : pkg->types) {
669 ResourceTableType* new_type = new_pkg->FindOrCreateType(type->named_type);
670 new_type->visibility_level = type->visibility_level;
671
672 for (const auto& entry : type->entries) {
673 ResourceEntry* new_entry = new_type->CreateEntry(entry->name);
674 new_entry->id = entry->id;
675 new_entry->visibility = entry->visibility;
676 new_entry->allow_new = entry->allow_new;
677 new_entry->overlayable_item = entry->overlayable_item;
678
679 for (const auto& config_value : entry->values) {
680 ResourceConfigValue* new_value =
681 new_entry->FindOrCreateValue(config_value->config, config_value->product);
682 new_value->value = config_value->value->Transform(cloner);
683 }
684 }
685 }
686 }
687 return new_table;
688 }
689
NewResourceBuilder(const ResourceNameRef & name)690 NewResourceBuilder::NewResourceBuilder(const ResourceNameRef& name) {
691 res_.name = name.ToResourceName();
692 }
693
NewResourceBuilder(const std::string & name)694 NewResourceBuilder::NewResourceBuilder(const std::string& name) {
695 ResourceNameRef ref;
696 CHECK(ResourceUtils::ParseResourceName(name, &ref)) << "invalid resource name: " << name;
697 res_.name = ref.ToResourceName();
698 }
699
SetValue(std::unique_ptr<Value> value,android::ConfigDescription config,std::string product)700 NewResourceBuilder& NewResourceBuilder::SetValue(std::unique_ptr<Value> value,
701 android::ConfigDescription config,
702 std::string product) {
703 res_.value = std::move(value);
704 res_.config = std::move(config);
705 res_.product = std::move(product);
706 return *this;
707 }
708
SetId(ResourceId id,OnIdConflict on_conflict)709 NewResourceBuilder& NewResourceBuilder::SetId(ResourceId id, OnIdConflict on_conflict) {
710 res_.id = std::make_pair(id, on_conflict);
711 return *this;
712 }
713
SetVisibility(Visibility visibility)714 NewResourceBuilder& NewResourceBuilder::SetVisibility(Visibility visibility) {
715 res_.visibility = std::move(visibility);
716 return *this;
717 }
718
SetOverlayable(OverlayableItem overlayable)719 NewResourceBuilder& NewResourceBuilder::SetOverlayable(OverlayableItem overlayable) {
720 res_.overlayable = std::move(overlayable);
721 return *this;
722 }
SetAllowNew(AllowNew allow_new)723 NewResourceBuilder& NewResourceBuilder::SetAllowNew(AllowNew allow_new) {
724 res_.allow_new = std::move(allow_new);
725 return *this;
726 }
727
SetStagedId(StagedId staged_alias)728 NewResourceBuilder& NewResourceBuilder::SetStagedId(StagedId staged_alias) {
729 res_.staged_id = std::move(staged_alias);
730 return *this;
731 }
732
SetAllowMangled(bool allow_mangled)733 NewResourceBuilder& NewResourceBuilder::SetAllowMangled(bool allow_mangled) {
734 res_.allow_mangled = allow_mangled;
735 return *this;
736 }
737
Build()738 NewResource NewResourceBuilder::Build() {
739 return std::move(res_);
740 }
741
742 } // namespace aapt
743