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