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