1 /*
2  * Copyright (C) 2016 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 "androidfw/AttributeResolution.h"
18 
19 #include <cstdint>
20 
21 #include <log/log.h>
22 
23 #include "androidfw/AssetManager2.h"
24 #include "androidfw/AttributeFinder.h"
25 
26 constexpr bool kDebugStyles = false;
27 #define DEBUG_LOG(...) do { if (kDebugStyles) { ALOGI(__VA_ARGS__); } } while(0)
28 
29 namespace android {
30 
31 namespace {
32 
33 // Java asset cookies have 0 as an invalid cookie, but TypedArray expects < 0.
ApkAssetsCookieToJavaCookie(ApkAssetsCookie cookie)34 static uint32_t ApkAssetsCookieToJavaCookie(ApkAssetsCookie cookie) {
35   return cookie != kInvalidCookie ? static_cast<uint32_t>(cookie + 1) : static_cast<uint32_t>(-1);
36 }
37 
38 class XmlAttributeFinder
39     : public BackTrackingAttributeFinder<XmlAttributeFinder, size_t> {
40  public:
XmlAttributeFinder(const ResXMLParser * parser)41   explicit XmlAttributeFinder(const ResXMLParser* parser)
42       : BackTrackingAttributeFinder(0, parser != nullptr ? parser->getAttributeCount() : 0),
43         parser_(parser) {}
44 
GetAttribute(size_t index) const45   inline uint32_t GetAttribute(size_t index) const {
46     return parser_->getAttributeNameResID(index);
47   }
48 
49  private:
50   const ResXMLParser* parser_;
51 };
52 
53 class BagAttributeFinder
54     : public BackTrackingAttributeFinder<BagAttributeFinder, const ResolvedBag::Entry*> {
55  public:
BagAttributeFinder(const ResolvedBag * bag)56   explicit BagAttributeFinder(const ResolvedBag* bag)
57       : BackTrackingAttributeFinder(bag != nullptr ? bag->entries : nullptr,
58                                     bag != nullptr ? bag->entries + bag->entry_count : nullptr) {
59   }
60 
GetAttribute(const ResolvedBag::Entry * entry) const61   inline uint32_t GetAttribute(const ResolvedBag::Entry* entry) const {
62     return entry->key;
63   }
64 };
65 
GetStyleBag(Theme * theme,uint32_t theme_attribute_resid,uint32_t fallback_resid,uint32_t * out_theme_flags)66 base::expected<const ResolvedBag*, NullOrIOError> GetStyleBag(Theme* theme,
67                                                               uint32_t theme_attribute_resid,
68                                                               uint32_t fallback_resid,
69                                                               uint32_t* out_theme_flags) {
70   // Load the style from the attribute if specified.
71   if (theme_attribute_resid != 0U) {
72     std::optional<AssetManager2::SelectedValue> value = theme->GetAttribute(theme_attribute_resid);
73     if (value.has_value()) {
74       *out_theme_flags |= value->flags;
75       auto result = theme->GetAssetManager()->ResolveBag(*value);
76       if (result.has_value() || IsIOError(result)) {
77         return result;
78       }
79     }
80   }
81 
82   // Fallback to loading the style from the resource id if specified.
83   if (fallback_resid != 0U) {
84     return theme->GetAssetManager()->GetBag(fallback_resid);
85   }
86 
87   return base::unexpected(std::nullopt);
88 }
89 
GetXmlStyleBag(Theme * theme,ResXMLParser * xml_parser,uint32_t * out_theme_flags)90 base::expected<const ResolvedBag*, NullOrIOError> GetXmlStyleBag(Theme* theme,
91                                                                  ResXMLParser* xml_parser,
92                                                                  uint32_t* out_theme_flags) {
93   if (xml_parser == nullptr) {
94     return base::unexpected(std::nullopt);
95   }
96 
97   // Retrieve the style resource ID associated with the current XML tag's style attribute.
98   Res_value value;
99   const ssize_t idx = xml_parser->indexOfStyle();
100   if (idx < 0 || xml_parser->getAttributeValue(idx, &value) < 0) {
101     return base::unexpected(std::nullopt);
102   }
103 
104   if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
105     // Resolve the attribute with out theme.
106     if (std::optional<AssetManager2::SelectedValue> result = theme->GetAttribute(value.data)) {
107       *out_theme_flags |= result->flags;
108       return theme->GetAssetManager()->ResolveBag(*result);
109     }
110   }
111 
112   if (value.dataType == Res_value::TYPE_REFERENCE) {
113     return theme->GetAssetManager()->GetBag(value.data);
114   }
115 
116   return base::unexpected(std::nullopt);
117 }
118 
119 } // namespace
120 
ResolveAttrs(Theme * theme,uint32_t def_style_attr,uint32_t def_style_res,uint32_t * src_values,size_t src_values_length,uint32_t * attrs,size_t attrs_length,uint32_t * out_values,uint32_t * out_indices)121 base::expected<std::monostate, IOError> ResolveAttrs(Theme* theme, uint32_t def_style_attr,
122                                                      uint32_t def_style_res, uint32_t* src_values,
123                                                      size_t src_values_length, uint32_t* attrs,
124                                                      size_t attrs_length, uint32_t* out_values,
125                                                      uint32_t* out_indices) {
126   DEBUG_LOG("APPLY STYLE: theme=0x%p defStyleAttr=0x%x defStyleRes=0x%x", theme, def_style_attr,
127             def_style_res);
128 
129   int indices_idx = 0;
130   const AssetManager2* assetmanager = theme->GetAssetManager();
131 
132   // Load default style from attribute or resource id, if specified...
133   uint32_t def_style_theme_flags = 0U;
134   const auto default_style_bag = GetStyleBag(theme, def_style_attr, def_style_res,
135                                              &def_style_theme_flags);
136   if (UNLIKELY(IsIOError(default_style_bag))) {
137     return base::unexpected(GetIOError(default_style_bag.error()));
138   }
139 
140   BagAttributeFinder def_style_attr_finder(default_style_bag.value_or(nullptr));
141 
142   // Now iterate through all of the attributes that the client has requested,
143   // filling in each with whatever data we can find.
144   for (size_t ii = 0; ii < attrs_length; ii++) {
145     const uint32_t cur_ident = attrs[ii];
146     DEBUG_LOG("RETRIEVING ATTR 0x%08x...", cur_ident);
147 
148     // Try to find a value for this attribute...  we prioritize values
149     // coming from, first XML attributes, then XML style, then default
150     // style, and finally the theme.
151 
152     // Retrieve the current input value if available.
153     AssetManager2::SelectedValue value{};
154     if (src_values_length > 0 && src_values[ii] != 0) {
155       value.type = Res_value::TYPE_ATTRIBUTE;
156       value.data = src_values[ii];
157       DEBUG_LOG("-> From values: type=0x%x, data=0x%08x", value.type, value.data);
158     } else {
159       const ResolvedBag::Entry* const entry = def_style_attr_finder.Find(cur_ident);
160       if (entry != def_style_attr_finder.end()) {
161         value = AssetManager2::SelectedValue(*default_style_bag, *entry);
162         value.flags |= def_style_theme_flags;
163         DEBUG_LOG("-> From def style: type=0x%x, data=0x%08x", value.type, value.data);
164       }
165     }
166 
167     if (value.type != Res_value::TYPE_NULL) {
168       // Take care of resolving the found resource to its final value.
169       const auto result = theme->ResolveAttributeReference(value);
170       if (UNLIKELY(IsIOError(result))) {
171         return base::unexpected(GetIOError(result.error()));
172       }
173       DEBUG_LOG("-> Resolved attr: type=0x%x, data=0x%08x", value.type, value.data);
174     } else if (value.data != Res_value::DATA_NULL_EMPTY) {
175       // If we still don't have a value for this attribute, try to find it in the theme!
176       if (auto attr_value = theme->GetAttribute(cur_ident)) {
177         value = *attr_value;
178         DEBUG_LOG("-> From theme: type=0x%x, data=0x%08x", value.type, value.data);
179 
180         const auto result = assetmanager->ResolveReference(value, true /* cache_value */);
181         if (UNLIKELY(IsIOError(result))) {
182           return base::unexpected(GetIOError(result.error()));
183         }
184         DEBUG_LOG("-> Resolved theme: type=0x%x, data=0x%08x", value.type, value.data);
185       }
186     }
187 
188     // Deal with the special @null value -- it turns back to TYPE_NULL.
189     if (value.type == Res_value::TYPE_REFERENCE && value.data == 0) {
190       DEBUG_LOG("-> Setting to @null!");
191       value.type = Res_value::TYPE_NULL;
192       value.data = Res_value::DATA_NULL_UNDEFINED;
193       value.cookie = kInvalidCookie;
194     }
195 
196     DEBUG_LOG("Attribute 0x%08x: type=0x%x, data=0x%08x", cur_ident, value.type, value.data);
197 
198     // Write the final value back to Java.
199     out_values[STYLE_TYPE] = value.type;
200     out_values[STYLE_DATA] = value.data;
201     out_values[STYLE_ASSET_COOKIE] = ApkAssetsCookieToJavaCookie(value.cookie);
202     out_values[STYLE_RESOURCE_ID] = value.resid;
203     out_values[STYLE_CHANGING_CONFIGURATIONS] = value.flags;
204     out_values[STYLE_DENSITY] = value.config.density;
205 
206     if (out_indices != nullptr &&
207         (value.type != Res_value::TYPE_NULL || value.data == Res_value::DATA_NULL_EMPTY)) {
208       out_indices[++indices_idx] = ii;
209     }
210 
211     out_values += STYLE_NUM_ENTRIES;
212   }
213 
214   if (out_indices != nullptr) {
215     out_indices[0] = indices_idx;
216   }
217   return {};
218 }
219 
ApplyStyle(Theme * theme,ResXMLParser * xml_parser,uint32_t def_style_attr,uint32_t def_style_resid,const uint32_t * attrs,size_t attrs_length,uint32_t * out_values,uint32_t * out_indices)220 base::expected<std::monostate, IOError> ApplyStyle(Theme* theme, ResXMLParser* xml_parser,
221                                                    uint32_t def_style_attr,
222                                                    uint32_t def_style_resid,
223                                                    const uint32_t* attrs, size_t attrs_length,
224                                                    uint32_t* out_values, uint32_t* out_indices) {
225   DEBUG_LOG("APPLY STYLE: theme=0x%p defStyleAttr=0x%x defStyleRes=0x%x xml=0x%p", theme,
226             def_style_attr, def_style_resid, xml_parser);
227 
228   int indices_idx = 0;
229   const AssetManager2* assetmanager = theme->GetAssetManager();
230 
231   // Load default style from attribute, if specified...
232   uint32_t def_style_theme_flags = 0U;
233   const auto default_style_bag = GetStyleBag(theme, def_style_attr, def_style_resid,
234                                              &def_style_theme_flags);
235   if (IsIOError(default_style_bag)) {
236     return base::unexpected(GetIOError(default_style_bag.error()));
237   }
238 
239   // Retrieve the style resource ID associated with the current XML tag's style attribute.
240   uint32_t xml_style_theme_flags = 0U;
241   const auto xml_style_bag = GetXmlStyleBag(theme, xml_parser, &def_style_theme_flags);
242   if (IsIOError(xml_style_bag)) {
243     return base::unexpected(GetIOError(xml_style_bag.error()));
244   }
245 
246   BagAttributeFinder def_style_attr_finder(default_style_bag.value_or(nullptr));
247   BagAttributeFinder xml_style_attr_finder(xml_style_bag.value_or(nullptr));
248   XmlAttributeFinder xml_attr_finder(xml_parser);
249 
250   // Now iterate through all of the attributes that the client has requested,
251   // filling in each with whatever data we can find.
252   for (size_t ii = 0; ii < attrs_length; ii++) {
253     const uint32_t cur_ident = attrs[ii];
254     DEBUG_LOG("RETRIEVING ATTR 0x%08x...", cur_ident);
255 
256     AssetManager2::SelectedValue value{};
257     uint32_t value_source_resid = 0;
258 
259     // Try to find a value for this attribute...  we prioritize values
260     // coming from, first XML attributes, then XML style, then default
261     // style, and finally the theme.
262 
263     // Walk through the xml attributes looking for the requested attribute.
264     const size_t xml_attr_idx = xml_attr_finder.Find(cur_ident);
265     if (xml_attr_idx != xml_attr_finder.end()) {
266       // We found the attribute we were looking for.
267       Res_value attribute_value{};
268       xml_parser->getAttributeValue(xml_attr_idx, &attribute_value);
269       value.type = attribute_value.dataType;
270       value.data = attribute_value.data;
271       value_source_resid = xml_parser->getSourceResourceId();
272       DEBUG_LOG("-> From XML: type=0x%x, data=0x%08x", value.type, value.data);
273     }
274 
275     if (value.type == Res_value::TYPE_NULL && value.data != Res_value::DATA_NULL_EMPTY) {
276       // Walk through the style class values looking for the requested attribute.
277       const ResolvedBag::Entry* entry = xml_style_attr_finder.Find(cur_ident);
278       if (entry != xml_style_attr_finder.end()) {
279         value = AssetManager2::SelectedValue(*xml_style_bag, *entry);
280         value.flags |= xml_style_theme_flags;
281         value_source_resid = entry->style;
282         DEBUG_LOG("-> From style: type=0x%x, data=0x%08x, style=0x%08x", value.type, value.data,
283                   value_source_resid);
284       }
285     }
286 
287     if (value.type == Res_value::TYPE_NULL && value.data != Res_value::DATA_NULL_EMPTY) {
288       // Walk through the default style values looking for the requested attribute.
289       const ResolvedBag::Entry* entry = def_style_attr_finder.Find(cur_ident);
290       if (entry != def_style_attr_finder.end()) {
291         value = AssetManager2::SelectedValue(*default_style_bag, *entry);
292         value.flags |= def_style_theme_flags;
293         value_source_resid = entry->style;
294         DEBUG_LOG("-> From def style: type=0x%x, data=0x%08x, style=0x%08x", value.type, value.data,
295                   entry->style);
296       }
297     }
298 
299     if (value.type != Res_value::TYPE_NULL) {
300       // Take care of resolving the found resource to its final value.
301       auto result = theme->ResolveAttributeReference(value);
302       if (UNLIKELY(IsIOError(result))) {
303         return base::unexpected(GetIOError(result.error()));
304       }
305       DEBUG_LOG("-> Resolved attr: type=0x%x, data=0x%08x", value.type, value.data);
306     } else if (value.data != Res_value::DATA_NULL_EMPTY) {
307       // If we still don't have a value for this attribute, try to find it in the theme!
308       if (auto attr_value = theme->GetAttribute(cur_ident)) {
309         value = *attr_value;
310         DEBUG_LOG("-> From theme: type=0x%x, data=0x%08x", value.type, value.data);
311 
312         auto result = assetmanager->ResolveReference(value, true /* cache_value */);
313         if (UNLIKELY(IsIOError(result))) {
314           return base::unexpected(GetIOError(result.error()));
315         }
316         DEBUG_LOG("-> Resolved theme: type=0x%x, data=0x%08x", value.type, value.data);
317         // TODO: set value_source_resid for the style in the theme that was used.
318       }
319     }
320 
321     // Deal with the special @null value -- it turns back to TYPE_NULL.
322     if (value.type == Res_value::TYPE_REFERENCE && value.data == 0U) {
323       DEBUG_LOG("-> Setting to @null!");
324       value.type = Res_value::TYPE_NULL;
325       value.data = Res_value::DATA_NULL_UNDEFINED;
326       value.cookie = kInvalidCookie;
327     }
328 
329     DEBUG_LOG("Attribute 0x%08x: type=0x%x, data=0x%08x", cur_ident, value.type, value.data);
330 
331     // Write the final value back to Java.
332     out_values[STYLE_TYPE] = value.type;
333     out_values[STYLE_DATA] = value.data;
334     out_values[STYLE_ASSET_COOKIE] = ApkAssetsCookieToJavaCookie(value.cookie);
335     out_values[STYLE_RESOURCE_ID] = value.resid;
336     out_values[STYLE_CHANGING_CONFIGURATIONS] = value.flags;
337     out_values[STYLE_DENSITY] = value.config.density;
338     out_values[STYLE_SOURCE_RESOURCE_ID] = value_source_resid;
339 
340     if (value.type != Res_value::TYPE_NULL || value.data == Res_value::DATA_NULL_EMPTY) {
341       // out_indices must NOT be nullptr.
342       out_indices[++indices_idx] = ii;
343     }
344     out_values += STYLE_NUM_ENTRIES;
345   }
346 
347   // out_indices must NOT be nullptr.
348   out_indices[0] = indices_idx;
349   return {};
350 }
351 
RetrieveAttributes(AssetManager2 * assetmanager,ResXMLParser * xml_parser,uint32_t * attrs,size_t attrs_length,uint32_t * out_values,uint32_t * out_indices)352 base::expected<std::monostate, IOError> RetrieveAttributes(AssetManager2* assetmanager,
353                                                            ResXMLParser* xml_parser,
354                                                            uint32_t* attrs,
355                                                            size_t attrs_length,
356                                                            uint32_t* out_values,
357                                                            uint32_t* out_indices) {
358   int indices_idx = 0;
359 
360   // Retrieve the XML attributes, if requested.
361   size_t ix = 0;
362   const size_t xml_attr_count = xml_parser->getAttributeCount();
363   uint32_t cur_xml_attr = xml_parser->getAttributeNameResID(ix);
364 
365   // Now iterate through all of the attributes that the client has requested,
366   // filling in each with whatever data we can find.
367   for (size_t ii = 0; ii < attrs_length; ii++) {
368     const uint32_t cur_ident = attrs[ii];
369      AssetManager2::SelectedValue value{};
370 
371     // Try to find a value for this attribute...
372     // Skip through XML attributes until the end or the next possible match.
373     while (ix < xml_attr_count && cur_ident > cur_xml_attr) {
374       cur_xml_attr = xml_parser->getAttributeNameResID(++ix);
375     }
376 
377     // Retrieve the current XML attribute if it matches, and step to next.
378     if (ix < xml_attr_count && cur_ident == cur_xml_attr) {
379       Res_value attribute_value{};
380       xml_parser->getAttributeValue(ix, &attribute_value);
381       value.type = attribute_value.dataType;
382       value.data = attribute_value.data;
383       cur_xml_attr = xml_parser->getAttributeNameResID(++ix);
384     }
385 
386     if (value.type != Res_value::TYPE_NULL) {
387       // Take care of resolving the found resource to its final value.
388       auto result = assetmanager->ResolveReference(value);
389       if (UNLIKELY(IsIOError(result))) {
390         return base::unexpected(GetIOError(result.error()));
391       }
392     }
393 
394     // Deal with the special @null value -- it turns back to TYPE_NULL.
395     if (value.type == Res_value::TYPE_REFERENCE && value.data == 0U) {
396       value.type = Res_value::TYPE_NULL;
397       value.data = Res_value::DATA_NULL_UNDEFINED;
398       value.cookie = kInvalidCookie;
399     }
400 
401     // Write the final value back to Java.
402     out_values[STYLE_TYPE] = value.type;
403     out_values[STYLE_DATA] = value.data;
404     out_values[STYLE_ASSET_COOKIE] = ApkAssetsCookieToJavaCookie(value.cookie);
405     out_values[STYLE_RESOURCE_ID] = value.resid;
406     out_values[STYLE_CHANGING_CONFIGURATIONS] = value.flags;
407     out_values[STYLE_DENSITY] = value.config.density;
408 
409     if (out_indices != nullptr &&
410         (value.type != Res_value::TYPE_NULL ||
411          value.data == Res_value::DATA_NULL_EMPTY)) {
412       out_indices[++indices_idx] = ii;
413     }
414 
415     out_values += STYLE_NUM_ENTRIES;
416   }
417 
418   if (out_indices != nullptr) {
419     out_indices[0] = indices_idx;
420   }
421   return {};
422 }
423 
424 }  // namespace android
425