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