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 "format/proto/ProtoDeserialize.h"
18 
19 #include "android-base/logging.h"
20 #include "android-base/macros.h"
21 #include "androidfw/ResourceTypes.h"
22 #include "androidfw/Locale.h"
23 
24 #include "ResourceTable.h"
25 #include "ResourceUtils.h"
26 #include "ResourceValues.h"
27 #include "ValueVisitor.h"
28 
29 using ::android::ConfigDescription;
30 using ::android::LocaleValue;
31 using ::android::ResStringPool;
32 
33 using PolicyFlags = android::ResTable_overlayable_policy_header::PolicyFlags;
34 
35 namespace aapt {
36 
37 namespace {
38 
39 class ReferenceIdToNameVisitor : public DescendingValueVisitor {
40  public:
41   using DescendingValueVisitor::Visit;
42 
ReferenceIdToNameVisitor(const std::map<ResourceId,ResourceNameRef> * mapping)43   explicit ReferenceIdToNameVisitor(const std::map<ResourceId, ResourceNameRef>* mapping)
44       : mapping_(mapping) {
45     CHECK(mapping_ != nullptr);
46   }
47 
Visit(Reference * reference)48   void Visit(Reference* reference) override {
49     if (!reference->id || !reference->id.value().is_valid()) {
50       return;
51     }
52 
53     ResourceId id = reference->id.value();
54     auto cache_iter = mapping_->find(id);
55     if (cache_iter != mapping_->end()) {
56       reference->name = cache_iter->second.ToResourceName();
57     }
58   }
59 
60  private:
61   DISALLOW_COPY_AND_ASSIGN(ReferenceIdToNameVisitor);
62 
63   const std::map<ResourceId, ResourceNameRef>* mapping_;
64 };
65 
66 }  // namespace
67 
DeserializeConfigFromPb(const pb::Configuration & pb_config,ConfigDescription * out_config,std::string * out_error)68 bool DeserializeConfigFromPb(const pb::Configuration& pb_config, ConfigDescription* out_config,
69                              std::string* out_error) {
70   out_config->mcc = static_cast<uint16_t>(pb_config.mcc());
71   out_config->mnc = static_cast<uint16_t>(pb_config.mnc());
72 
73   if (!pb_config.locale().empty()) {
74     LocaleValue lv;
75     if (!lv.InitFromBcp47Tag(pb_config.locale())) {
76       std::ostringstream error;
77       error << "configuration has invalid locale '" << pb_config.locale() << "'";
78       *out_error = error.str();
79       return false;
80     }
81     lv.WriteTo(out_config);
82   }
83 
84   switch (pb_config.layout_direction()) {
85     case pb::Configuration_LayoutDirection_LAYOUT_DIRECTION_LTR:
86       out_config->screenLayout = (out_config->screenLayout & ~ConfigDescription::MASK_LAYOUTDIR) |
87                                  ConfigDescription::LAYOUTDIR_LTR;
88       break;
89 
90     case pb::Configuration_LayoutDirection_LAYOUT_DIRECTION_RTL:
91       out_config->screenLayout = (out_config->screenLayout & ~ConfigDescription::MASK_LAYOUTDIR) |
92                                  ConfigDescription::LAYOUTDIR_RTL;
93       break;
94 
95     default:
96       break;
97   }
98 
99   out_config->smallestScreenWidthDp = static_cast<uint16_t>(pb_config.smallest_screen_width_dp());
100   out_config->screenWidthDp = static_cast<uint16_t>(pb_config.screen_width_dp());
101   out_config->screenHeightDp = static_cast<uint16_t>(pb_config.screen_height_dp());
102 
103   switch (pb_config.screen_layout_size()) {
104     case pb::Configuration_ScreenLayoutSize_SCREEN_LAYOUT_SIZE_SMALL:
105       out_config->screenLayout = (out_config->screenLayout & ~ConfigDescription::MASK_SCREENSIZE) |
106                                  ConfigDescription::SCREENSIZE_SMALL;
107       break;
108 
109     case pb::Configuration_ScreenLayoutSize_SCREEN_LAYOUT_SIZE_NORMAL:
110       out_config->screenLayout = (out_config->screenLayout & ~ConfigDescription::MASK_SCREENSIZE) |
111                                  ConfigDescription::SCREENSIZE_NORMAL;
112       break;
113 
114     case pb::Configuration_ScreenLayoutSize_SCREEN_LAYOUT_SIZE_LARGE:
115       out_config->screenLayout = (out_config->screenLayout & ~ConfigDescription::MASK_SCREENSIZE) |
116                                  ConfigDescription::SCREENSIZE_LARGE;
117       break;
118 
119     case pb::Configuration_ScreenLayoutSize_SCREEN_LAYOUT_SIZE_XLARGE:
120       out_config->screenLayout = (out_config->screenLayout & ~ConfigDescription::MASK_SCREENSIZE) |
121                                  ConfigDescription::SCREENSIZE_XLARGE;
122       break;
123 
124     default:
125       break;
126   }
127 
128   switch (pb_config.screen_layout_long()) {
129     case pb::Configuration_ScreenLayoutLong_SCREEN_LAYOUT_LONG_LONG:
130       out_config->screenLayout = (out_config->screenLayout & ~ConfigDescription::MASK_SCREENLONG) |
131                                  ConfigDescription::SCREENLONG_YES;
132       break;
133 
134     case pb::Configuration_ScreenLayoutLong_SCREEN_LAYOUT_LONG_NOTLONG:
135       out_config->screenLayout = (out_config->screenLayout & ~ConfigDescription::MASK_SCREENLONG) |
136                                  ConfigDescription::SCREENLONG_NO;
137       break;
138 
139     default:
140       break;
141   }
142 
143   switch (pb_config.screen_round()) {
144     case pb::Configuration_ScreenRound_SCREEN_ROUND_ROUND:
145       out_config->screenLayout2 =
146           (out_config->screenLayout2 & ~ConfigDescription::MASK_SCREENROUND) |
147           ConfigDescription::SCREENROUND_YES;
148       break;
149 
150     case pb::Configuration_ScreenRound_SCREEN_ROUND_NOTROUND:
151       out_config->screenLayout2 =
152           (out_config->screenLayout2 & ~ConfigDescription::MASK_SCREENROUND) |
153           ConfigDescription::SCREENROUND_NO;
154       break;
155 
156     default:
157       break;
158   }
159 
160   switch (pb_config.wide_color_gamut()) {
161     case pb::Configuration_WideColorGamut_WIDE_COLOR_GAMUT_WIDECG:
162       out_config->colorMode = (out_config->colorMode & ~ConfigDescription::MASK_WIDE_COLOR_GAMUT) |
163                               ConfigDescription::WIDE_COLOR_GAMUT_YES;
164       break;
165 
166     case pb::Configuration_WideColorGamut_WIDE_COLOR_GAMUT_NOWIDECG:
167       out_config->colorMode = (out_config->colorMode & ~ConfigDescription::MASK_WIDE_COLOR_GAMUT) |
168                               ConfigDescription::WIDE_COLOR_GAMUT_NO;
169       break;
170 
171     default:
172       break;
173   }
174 
175   switch (pb_config.hdr()) {
176     case pb::Configuration_Hdr_HDR_HIGHDR:
177       out_config->colorMode =
178           (out_config->colorMode & ~ConfigDescription::MASK_HDR) | ConfigDescription::HDR_YES;
179       break;
180 
181     case pb::Configuration_Hdr_HDR_LOWDR:
182       out_config->colorMode =
183           (out_config->colorMode & ~ConfigDescription::MASK_HDR) | ConfigDescription::HDR_NO;
184       break;
185 
186     default:
187       break;
188   }
189 
190   switch (pb_config.orientation()) {
191     case pb::Configuration_Orientation_ORIENTATION_PORT:
192       out_config->orientation = ConfigDescription::ORIENTATION_PORT;
193       break;
194 
195     case pb::Configuration_Orientation_ORIENTATION_LAND:
196       out_config->orientation = ConfigDescription::ORIENTATION_LAND;
197       break;
198 
199     case pb::Configuration_Orientation_ORIENTATION_SQUARE:
200       out_config->orientation = ConfigDescription::ORIENTATION_SQUARE;
201       break;
202 
203     default:
204       break;
205   }
206 
207   switch (pb_config.ui_mode_type()) {
208     case pb::Configuration_UiModeType_UI_MODE_TYPE_NORMAL:
209       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_TYPE) |
210                            ConfigDescription::UI_MODE_TYPE_NORMAL;
211       break;
212 
213     case pb::Configuration_UiModeType_UI_MODE_TYPE_DESK:
214       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_TYPE) |
215                            ConfigDescription::UI_MODE_TYPE_DESK;
216       break;
217 
218     case pb::Configuration_UiModeType_UI_MODE_TYPE_CAR:
219       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_TYPE) |
220                            ConfigDescription::UI_MODE_TYPE_CAR;
221       break;
222 
223     case pb::Configuration_UiModeType_UI_MODE_TYPE_TELEVISION:
224       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_TYPE) |
225                            ConfigDescription::UI_MODE_TYPE_TELEVISION;
226       break;
227 
228     case pb::Configuration_UiModeType_UI_MODE_TYPE_APPLIANCE:
229       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_TYPE) |
230                            ConfigDescription::UI_MODE_TYPE_APPLIANCE;
231       break;
232 
233     case pb::Configuration_UiModeType_UI_MODE_TYPE_WATCH:
234       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_TYPE) |
235                            ConfigDescription::UI_MODE_TYPE_WATCH;
236       break;
237 
238     case pb::Configuration_UiModeType_UI_MODE_TYPE_VRHEADSET:
239       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_TYPE) |
240                            ConfigDescription::UI_MODE_TYPE_VR_HEADSET;
241       break;
242 
243     default:
244       break;
245   }
246 
247   switch (pb_config.ui_mode_night()) {
248     case pb::Configuration_UiModeNight_UI_MODE_NIGHT_NIGHT:
249       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_NIGHT) |
250                            ConfigDescription::UI_MODE_NIGHT_YES;
251       break;
252 
253     case pb::Configuration_UiModeNight_UI_MODE_NIGHT_NOTNIGHT:
254       out_config->uiMode = (out_config->uiMode & ~ConfigDescription::MASK_UI_MODE_NIGHT) |
255                            ConfigDescription::UI_MODE_NIGHT_NO;
256       break;
257 
258     default:
259       break;
260   }
261 
262   out_config->density = static_cast<uint16_t>(pb_config.density());
263 
264   switch (pb_config.touchscreen()) {
265     case pb::Configuration_Touchscreen_TOUCHSCREEN_NOTOUCH:
266       out_config->touchscreen = ConfigDescription::TOUCHSCREEN_NOTOUCH;
267       break;
268 
269     case pb::Configuration_Touchscreen_TOUCHSCREEN_STYLUS:
270       out_config->touchscreen = ConfigDescription::TOUCHSCREEN_STYLUS;
271       break;
272 
273     case pb::Configuration_Touchscreen_TOUCHSCREEN_FINGER:
274       out_config->touchscreen = ConfigDescription::TOUCHSCREEN_FINGER;
275       break;
276 
277     default:
278       break;
279   }
280 
281   switch (pb_config.keys_hidden()) {
282     case pb::Configuration_KeysHidden_KEYS_HIDDEN_KEYSEXPOSED:
283       out_config->inputFlags = (out_config->inputFlags & ~ConfigDescription::MASK_KEYSHIDDEN) |
284                                ConfigDescription::KEYSHIDDEN_NO;
285       break;
286 
287     case pb::Configuration_KeysHidden_KEYS_HIDDEN_KEYSHIDDEN:
288       out_config->inputFlags = (out_config->inputFlags & ~ConfigDescription::MASK_KEYSHIDDEN) |
289                                ConfigDescription::KEYSHIDDEN_YES;
290       break;
291 
292     case pb::Configuration_KeysHidden_KEYS_HIDDEN_KEYSSOFT:
293       out_config->inputFlags = (out_config->inputFlags & ~ConfigDescription::MASK_KEYSHIDDEN) |
294                                ConfigDescription::KEYSHIDDEN_SOFT;
295       break;
296 
297     default:
298       break;
299   }
300 
301   switch (pb_config.keyboard()) {
302     case pb::Configuration_Keyboard_KEYBOARD_NOKEYS:
303       out_config->keyboard = ConfigDescription::KEYBOARD_NOKEYS;
304       break;
305 
306     case pb::Configuration_Keyboard_KEYBOARD_QWERTY:
307       out_config->keyboard = ConfigDescription::KEYBOARD_QWERTY;
308       break;
309 
310     case pb::Configuration_Keyboard_KEYBOARD_TWELVEKEY:
311       out_config->keyboard = ConfigDescription::KEYBOARD_12KEY;
312       break;
313 
314     default:
315       break;
316   }
317 
318   switch (pb_config.nav_hidden()) {
319     case pb::Configuration_NavHidden_NAV_HIDDEN_NAVEXPOSED:
320       out_config->inputFlags = (out_config->inputFlags & ~ConfigDescription::MASK_NAVHIDDEN) |
321                                ConfigDescription::NAVHIDDEN_NO;
322       break;
323 
324     case pb::Configuration_NavHidden_NAV_HIDDEN_NAVHIDDEN:
325       out_config->inputFlags = (out_config->inputFlags & ~ConfigDescription::MASK_NAVHIDDEN) |
326                                ConfigDescription::NAVHIDDEN_YES;
327       break;
328 
329     default:
330       break;
331   }
332 
333   switch (pb_config.navigation()) {
334     case pb::Configuration_Navigation_NAVIGATION_NONAV:
335       out_config->navigation = ConfigDescription::NAVIGATION_NONAV;
336       break;
337 
338     case pb::Configuration_Navigation_NAVIGATION_DPAD:
339       out_config->navigation = ConfigDescription::NAVIGATION_DPAD;
340       break;
341 
342     case pb::Configuration_Navigation_NAVIGATION_TRACKBALL:
343       out_config->navigation = ConfigDescription::NAVIGATION_TRACKBALL;
344       break;
345 
346     case pb::Configuration_Navigation_NAVIGATION_WHEEL:
347       out_config->navigation = ConfigDescription::NAVIGATION_WHEEL;
348       break;
349 
350     default:
351       break;
352   }
353 
354   out_config->screenWidth = static_cast<uint16_t>(pb_config.screen_width());
355   out_config->screenHeight = static_cast<uint16_t>(pb_config.screen_height());
356   out_config->sdkVersion = static_cast<uint16_t>(pb_config.sdk_version());
357   return true;
358 }
359 
DeserializeSourceFromPb(const pb::Source & pb_source,const ResStringPool & src_pool,Source * out_source)360 static void DeserializeSourceFromPb(const pb::Source& pb_source, const ResStringPool& src_pool,
361                                     Source* out_source) {
362   out_source->path = util::GetString(src_pool, pb_source.path_idx());
363   out_source->line = static_cast<size_t>(pb_source.position().line_number());
364 }
365 
DeserializeVisibilityFromPb(const pb::Visibility::Level & pb_level)366 static Visibility::Level DeserializeVisibilityFromPb(const pb::Visibility::Level& pb_level) {
367   switch (pb_level) {
368     case pb::Visibility::PRIVATE:
369       return Visibility::Level::kPrivate;
370     case pb::Visibility::PUBLIC:
371       return Visibility::Level::kPublic;
372     default:
373       break;
374   }
375   return Visibility::Level::kUndefined;
376 }
377 
DeserializeOverlayableItemFromPb(const pb::OverlayableItem & pb_overlayable,const android::ResStringPool & src_pool,OverlayableItem * out_overlayable,std::string * out_error)378 bool DeserializeOverlayableItemFromPb(const pb::OverlayableItem& pb_overlayable,
379                                       const android::ResStringPool& src_pool,
380                                       OverlayableItem* out_overlayable, std::string* out_error) {
381   for (const int policy : pb_overlayable.policy()) {
382     switch (policy) {
383       case pb::OverlayableItem::PUBLIC:
384         out_overlayable->policies |= PolicyFlags::PUBLIC;
385         break;
386       case pb::OverlayableItem::SYSTEM:
387         out_overlayable->policies |= PolicyFlags::SYSTEM_PARTITION;
388         break;
389       case pb::OverlayableItem::VENDOR:
390         out_overlayable->policies |= PolicyFlags::VENDOR_PARTITION;
391         break;
392       case pb::OverlayableItem::PRODUCT:
393         out_overlayable->policies |= PolicyFlags::PRODUCT_PARTITION;
394         break;
395       case pb::OverlayableItem::SIGNATURE:
396         out_overlayable->policies |= PolicyFlags::SIGNATURE;
397         break;
398       case pb::OverlayableItem::ODM:
399         out_overlayable->policies |= PolicyFlags::ODM_PARTITION;
400         break;
401       case pb::OverlayableItem::OEM:
402         out_overlayable->policies |= PolicyFlags::OEM_PARTITION;
403         break;
404       case pb::OverlayableItem::ACTOR:
405         out_overlayable->policies |= PolicyFlags::ACTOR_SIGNATURE;
406         break;
407       default:
408         *out_error = "unknown overlayable policy";
409         return false;
410     }
411   }
412 
413   if (pb_overlayable.has_source()) {
414     DeserializeSourceFromPb(pb_overlayable.source(), src_pool, &out_overlayable->source);
415   }
416 
417   out_overlayable->comment = pb_overlayable.comment();
418   return true;
419 }
420 
DeserializePackageFromPb(const pb::Package & pb_package,const ResStringPool & src_pool,io::IFileCollection * files,const std::vector<std::shared_ptr<Overlayable>> & overlayables,ResourceTable * out_table,std::string * out_error)421 static bool DeserializePackageFromPb(const pb::Package& pb_package, const ResStringPool& src_pool,
422                                      io::IFileCollection* files,
423                                      const std::vector<std::shared_ptr<Overlayable>>& overlayables,
424                                      ResourceTable* out_table, std::string* out_error) {
425   Maybe<uint8_t> id;
426   if (pb_package.has_package_id()) {
427     id = static_cast<uint8_t>(pb_package.package_id().id());
428   }
429 
430   std::map<ResourceId, ResourceNameRef> id_index;
431 
432   ResourceTablePackage* pkg =
433       out_table->CreatePackageAllowingDuplicateNames(pb_package.package_name(), id);
434   for (const pb::Type& pb_type : pb_package.type()) {
435     const ResourceType* res_type = ParseResourceType(pb_type.name());
436     if (res_type == nullptr) {
437       std::ostringstream error;
438       error << "unknown type '" << pb_type.name() << "'";
439       *out_error = error.str();
440       return false;
441     }
442 
443     ResourceTableType* type = pkg->FindOrCreateType(*res_type);
444     if (pb_type.has_type_id()) {
445       type->id = static_cast<uint8_t>(pb_type.type_id().id());
446     }
447 
448     for (const pb::Entry& pb_entry : pb_type.entry()) {
449       ResourceEntry* entry = type->FindOrCreateEntry(pb_entry.name());
450       if (pb_entry.has_entry_id()) {
451         entry->id = static_cast<uint16_t>(pb_entry.entry_id().id());
452       }
453 
454       // Deserialize the symbol status (public/private with source and comments).
455       if (pb_entry.has_visibility()) {
456         const pb::Visibility& pb_visibility = pb_entry.visibility();
457         if (pb_visibility.has_source()) {
458           DeserializeSourceFromPb(pb_visibility.source(), src_pool, &entry->visibility.source);
459         }
460         entry->visibility.comment = pb_visibility.comment();
461 
462         const Visibility::Level level = DeserializeVisibilityFromPb(pb_visibility.level());
463         entry->visibility.level = level;
464         if (level == Visibility::Level::kPublic) {
465           // Propagate the public visibility up to the Type.
466           type->visibility_level = Visibility::Level::kPublic;
467         } else if (level == Visibility::Level::kPrivate) {
468           // Only propagate if no previous state was assigned.
469           if (type->visibility_level == Visibility::Level::kUndefined) {
470             type->visibility_level = Visibility::Level::kPrivate;
471           }
472         }
473       }
474 
475       if (pb_entry.has_allow_new()) {
476         const pb::AllowNew& pb_allow_new = pb_entry.allow_new();
477 
478         AllowNew allow_new;
479         if (pb_allow_new.has_source()) {
480           DeserializeSourceFromPb(pb_allow_new.source(), src_pool, &allow_new.source);
481         }
482         allow_new.comment = pb_allow_new.comment();
483         entry->allow_new = std::move(allow_new);
484       }
485 
486       if (pb_entry.has_overlayable_item()) {
487         // Find the overlayable to which this item belongs
488         pb::OverlayableItem pb_overlayable_item = pb_entry.overlayable_item();
489         if (pb_overlayable_item.overlayable_idx() >= overlayables.size()) {
490           *out_error = android::base::StringPrintf("invalid overlayable_idx value %d",
491                                                    pb_overlayable_item.overlayable_idx());
492           return false;
493         }
494 
495         OverlayableItem overlayable_item(overlayables[pb_overlayable_item.overlayable_idx()]);
496         if (!DeserializeOverlayableItemFromPb(pb_overlayable_item, src_pool, &overlayable_item,
497                                               out_error)) {
498           return false;
499         }
500 
501         entry->overlayable_item = std::move(overlayable_item);
502       }
503 
504       ResourceId resid(pb_package.package_id().id(), pb_type.type_id().id(),
505                        pb_entry.entry_id().id());
506       if (resid.is_valid()) {
507         id_index[resid] = ResourceNameRef(pkg->name, type->type, entry->name);
508       }
509 
510       for (const pb::ConfigValue& pb_config_value : pb_entry.config_value()) {
511         const pb::Configuration& pb_config = pb_config_value.config();
512 
513         ConfigDescription config;
514         if (!DeserializeConfigFromPb(pb_config, &config, out_error)) {
515           return false;
516         }
517 
518         ResourceConfigValue* config_value = entry->FindOrCreateValue(config, pb_config.product());
519         if (config_value->value != nullptr) {
520           *out_error = "duplicate configuration in resource table";
521           return false;
522         }
523 
524         config_value->value = DeserializeValueFromPb(pb_config_value.value(), src_pool, config,
525                                                      &out_table->string_pool, files, out_error);
526         if (config_value->value == nullptr) {
527           return false;
528         }
529       }
530     }
531   }
532 
533   ReferenceIdToNameVisitor visitor(&id_index);
534   VisitAllValuesInPackage(pkg, &visitor);
535   return true;
536 }
537 
DeserializeTableFromPb(const pb::ResourceTable & pb_table,io::IFileCollection * files,ResourceTable * out_table,std::string * out_error)538 bool DeserializeTableFromPb(const pb::ResourceTable& pb_table, io::IFileCollection* files,
539                             ResourceTable* out_table, std::string* out_error) {
540   // We import the android namespace because on Windows NO_ERROR is a macro, not an enum, which
541   // causes errors when qualifying it with android::
542   using namespace android;
543 
544   ResStringPool source_pool;
545   if (pb_table.has_source_pool()) {
546     status_t result = source_pool.setTo(pb_table.source_pool().data().data(),
547                                         pb_table.source_pool().data().size());
548     if (result != NO_ERROR) {
549       *out_error = "invalid source pool";
550       return false;
551     }
552   }
553 
554   // Deserialize the overlayable groups of the table
555   std::vector<std::shared_ptr<Overlayable>> overlayables;
556   for (const pb::Overlayable& pb_overlayable : pb_table.overlayable()) {
557     auto group = std::make_shared<Overlayable>(pb_overlayable.name(), pb_overlayable.actor());
558     if (pb_overlayable.has_source()) {
559       DeserializeSourceFromPb(pb_overlayable.source(), source_pool, &group->source);
560     }
561     overlayables.push_back(group);
562   }
563 
564   for (const pb::Package& pb_package : pb_table.package()) {
565     if (!DeserializePackageFromPb(pb_package, source_pool, files, overlayables, out_table,
566                                   out_error)) {
567       return false;
568     }
569   }
570   return true;
571 }
572 
DeserializeFileReferenceTypeFromPb(const pb::FileReference::Type & type)573 static ResourceFile::Type DeserializeFileReferenceTypeFromPb(const pb::FileReference::Type& type) {
574   switch (type) {
575     case pb::FileReference::BINARY_XML:
576       return ResourceFile::Type::kBinaryXml;
577     case pb::FileReference::PROTO_XML:
578       return ResourceFile::Type::kProtoXml;
579     case pb::FileReference::PNG:
580       return ResourceFile::Type::kPng;
581     default:
582       return ResourceFile::Type::kUnknown;
583   }
584 }
585 
DeserializeCompiledFileFromPb(const pb::internal::CompiledFile & pb_file,ResourceFile * out_file,std::string * out_error)586 bool DeserializeCompiledFileFromPb(const pb::internal::CompiledFile& pb_file,
587                                    ResourceFile* out_file, std::string* out_error) {
588   ResourceNameRef name_ref;
589   if (!ResourceUtils::ParseResourceName(pb_file.resource_name(), &name_ref)) {
590     std::ostringstream error;
591     error << "invalid resource name in compiled file header: " << pb_file.resource_name();
592     *out_error = error.str();
593     return false;
594   }
595 
596   out_file->name = name_ref.ToResourceName();
597   out_file->source.path = pb_file.source_path();
598   out_file->type = DeserializeFileReferenceTypeFromPb(pb_file.type());
599 
600   std::string config_error;
601   if (!DeserializeConfigFromPb(pb_file.config(), &out_file->config, &config_error)) {
602     std::ostringstream error;
603     error << "invalid resource configuration in compiled file header: " << config_error;
604     *out_error = error.str();
605     return false;
606   }
607 
608   for (const pb::internal::CompiledFile_Symbol& pb_symbol : pb_file.exported_symbol()) {
609     if (!ResourceUtils::ParseResourceName(pb_symbol.resource_name(), &name_ref)) {
610       std::ostringstream error;
611       error << "invalid resource name for exported symbol in compiled file header: "
612             << pb_file.resource_name();
613       *out_error = error.str();
614       return false;
615     }
616 
617     size_t line = 0u;
618     if (pb_symbol.has_source()) {
619       line = pb_symbol.source().line_number();
620     }
621     out_file->exported_symbols.push_back(SourcedResourceName{name_ref.ToResourceName(), line});
622   }
623   return true;
624 }
625 
DeserializeReferenceTypeFromPb(const pb::Reference_Type & pb_type)626 static Reference::Type DeserializeReferenceTypeFromPb(const pb::Reference_Type& pb_type) {
627   switch (pb_type) {
628     case pb::Reference_Type_REFERENCE:
629       return Reference::Type::kResource;
630     case pb::Reference_Type_ATTRIBUTE:
631       return Reference::Type::kAttribute;
632     default:
633       break;
634   }
635   return Reference::Type::kResource;
636 }
637 
DeserializeReferenceFromPb(const pb::Reference & pb_ref,Reference * out_ref,std::string * out_error)638 static bool DeserializeReferenceFromPb(const pb::Reference& pb_ref, Reference* out_ref,
639                                        std::string* out_error) {
640   out_ref->reference_type = DeserializeReferenceTypeFromPb(pb_ref.type());
641   out_ref->private_reference = pb_ref.private_();
642   out_ref->is_dynamic = pb_ref.is_dynamic().value();
643 
644   if (pb_ref.id() != 0) {
645     out_ref->id = ResourceId(pb_ref.id());
646   }
647 
648   if (!pb_ref.name().empty()) {
649     ResourceNameRef name_ref;
650     if (!ResourceUtils::ParseResourceName(pb_ref.name(), &name_ref, nullptr)) {
651       std::ostringstream error;
652       error << "reference has invalid resource name '" << pb_ref.name() << "'";
653       *out_error = error.str();
654       return false;
655     }
656     out_ref->name = name_ref.ToResourceName();
657   }
658   return true;
659 }
660 
661 template <typename T>
DeserializeItemMetaDataFromPb(const T & pb_item,const android::ResStringPool & src_pool,Value * out_value)662 static void DeserializeItemMetaDataFromPb(const T& pb_item, const android::ResStringPool& src_pool,
663                                           Value* out_value) {
664   if (pb_item.has_source()) {
665     Source source;
666     DeserializeSourceFromPb(pb_item.source(), src_pool, &source);
667     out_value->SetSource(std::move(source));
668   }
669   out_value->SetComment(pb_item.comment());
670 }
671 
DeserializePluralEnumFromPb(const pb::Plural_Arity & arity)672 static size_t DeserializePluralEnumFromPb(const pb::Plural_Arity& arity) {
673   switch (arity) {
674     case pb::Plural_Arity_ZERO:
675       return Plural::Zero;
676     case pb::Plural_Arity_ONE:
677       return Plural::One;
678     case pb::Plural_Arity_TWO:
679       return Plural::Two;
680     case pb::Plural_Arity_FEW:
681       return Plural::Few;
682     case pb::Plural_Arity_MANY:
683       return Plural::Many;
684     default:
685       break;
686   }
687   return Plural::Other;
688 }
689 
DeserializeValueFromPb(const pb::Value & pb_value,const android::ResStringPool & src_pool,const ConfigDescription & config,StringPool * value_pool,io::IFileCollection * files,std::string * out_error)690 std::unique_ptr<Value> DeserializeValueFromPb(const pb::Value& pb_value,
691                                               const android::ResStringPool& src_pool,
692                                               const ConfigDescription& config,
693                                               StringPool* value_pool, io::IFileCollection* files,
694                                               std::string* out_error) {
695   std::unique_ptr<Value> value;
696   if (pb_value.has_item()) {
697     value = DeserializeItemFromPb(pb_value.item(), src_pool, config, value_pool, files, out_error);
698     if (value == nullptr) {
699       return {};
700     }
701 
702   } else if (pb_value.has_compound_value()) {
703     const pb::CompoundValue& pb_compound_value = pb_value.compound_value();
704     switch (pb_compound_value.value_case()) {
705       case pb::CompoundValue::kAttr: {
706         const pb::Attribute& pb_attr = pb_compound_value.attr();
707         std::unique_ptr<Attribute> attr = util::make_unique<Attribute>(pb_attr.format_flags());
708         attr->min_int = pb_attr.min_int();
709         attr->max_int = pb_attr.max_int();
710         for (const pb::Attribute_Symbol& pb_symbol : pb_attr.symbol()) {
711           Attribute::Symbol symbol;
712           DeserializeItemMetaDataFromPb(pb_symbol, src_pool, &symbol.symbol);
713           if (!DeserializeReferenceFromPb(pb_symbol.name(), &symbol.symbol, out_error)) {
714             return {};
715           }
716           symbol.value = pb_symbol.value();
717           symbol.type = pb_symbol.type() != 0U ? pb_symbol.type()
718                                                : android::Res_value::TYPE_INT_DEC;
719           attr->symbols.push_back(std::move(symbol));
720         }
721         value = std::move(attr);
722       } break;
723 
724       case pb::CompoundValue::kStyle: {
725         const pb::Style& pb_style = pb_compound_value.style();
726         std::unique_ptr<Style> style = util::make_unique<Style>();
727         if (pb_style.has_parent()) {
728           style->parent = Reference();
729           if (!DeserializeReferenceFromPb(pb_style.parent(), &style->parent.value(), out_error)) {
730             return {};
731           }
732 
733           if (pb_style.has_parent_source()) {
734             Source parent_source;
735             DeserializeSourceFromPb(pb_style.parent_source(), src_pool, &parent_source);
736             style->parent.value().SetSource(std::move(parent_source));
737           }
738         }
739 
740         for (const pb::Style_Entry& pb_entry : pb_style.entry()) {
741           Style::Entry entry;
742           if (!DeserializeReferenceFromPb(pb_entry.key(), &entry.key, out_error)) {
743             return {};
744           }
745           DeserializeItemMetaDataFromPb(pb_entry, src_pool, &entry.key);
746           entry.value = DeserializeItemFromPb(pb_entry.item(), src_pool, config, value_pool, files,
747                                               out_error);
748           if (entry.value == nullptr) {
749             return {};
750           }
751 
752           // Copy the meta-data into the value as well.
753           DeserializeItemMetaDataFromPb(pb_entry, src_pool, entry.value.get());
754           style->entries.push_back(std::move(entry));
755         }
756         value = std::move(style);
757       } break;
758 
759       case pb::CompoundValue::kStyleable: {
760         const pb::Styleable& pb_styleable = pb_compound_value.styleable();
761         std::unique_ptr<Styleable> styleable = util::make_unique<Styleable>();
762         for (const pb::Styleable_Entry& pb_entry : pb_styleable.entry()) {
763           Reference attr_ref;
764           DeserializeItemMetaDataFromPb(pb_entry, src_pool, &attr_ref);
765           DeserializeReferenceFromPb(pb_entry.attr(), &attr_ref, out_error);
766           styleable->entries.push_back(std::move(attr_ref));
767         }
768         value = std::move(styleable);
769       } break;
770 
771       case pb::CompoundValue::kArray: {
772         const pb::Array& pb_array = pb_compound_value.array();
773         std::unique_ptr<Array> array = util::make_unique<Array>();
774         for (const pb::Array_Element& pb_entry : pb_array.element()) {
775           std::unique_ptr<Item> item = DeserializeItemFromPb(pb_entry.item(), src_pool, config,
776                                                              value_pool, files, out_error);
777           if (item == nullptr) {
778             return {};
779           }
780 
781           DeserializeItemMetaDataFromPb(pb_entry, src_pool, item.get());
782           array->elements.push_back(std::move(item));
783         }
784         value = std::move(array);
785       } break;
786 
787       case pb::CompoundValue::kPlural: {
788         const pb::Plural& pb_plural = pb_compound_value.plural();
789         std::unique_ptr<Plural> plural = util::make_unique<Plural>();
790         for (const pb::Plural_Entry& pb_entry : pb_plural.entry()) {
791           size_t plural_idx = DeserializePluralEnumFromPb(pb_entry.arity());
792           plural->values[plural_idx] = DeserializeItemFromPb(pb_entry.item(), src_pool, config,
793                                                              value_pool, files, out_error);
794           if (!plural->values[plural_idx]) {
795             return {};
796           }
797 
798           DeserializeItemMetaDataFromPb(pb_entry, src_pool, plural->values[plural_idx].get());
799         }
800         value = std::move(plural);
801       } break;
802 
803       default:
804         LOG(FATAL) << "unknown compound value: " << (int)pb_compound_value.value_case();
805         break;
806     }
807   } else {
808     LOG(FATAL) << "unknown value: " << (int)pb_value.value_case();
809     return {};
810   }
811 
812   CHECK(value) << "forgot to set value";
813 
814   value->SetWeak(pb_value.weak());
815   DeserializeItemMetaDataFromPb(pb_value, src_pool, value.get());
816   return value;
817 }
818 
DeserializeItemFromPb(const pb::Item & pb_item,const android::ResStringPool & src_pool,const ConfigDescription & config,StringPool * value_pool,io::IFileCollection * files,std::string * out_error)819 std::unique_ptr<Item> DeserializeItemFromPb(const pb::Item& pb_item,
820                                             const android::ResStringPool& src_pool,
821                                             const ConfigDescription& config, StringPool* value_pool,
822                                             io::IFileCollection* files, std::string* out_error) {
823   switch (pb_item.value_case()) {
824     case pb::Item::kRef: {
825       const pb::Reference& pb_ref = pb_item.ref();
826       std::unique_ptr<Reference> ref = util::make_unique<Reference>();
827       if (!DeserializeReferenceFromPb(pb_ref, ref.get(), out_error)) {
828         return {};
829       }
830       return std::move(ref);
831     } break;
832 
833     case pb::Item::kPrim: {
834       const pb::Primitive& pb_prim = pb_item.prim();
835       android::Res_value val = {};
836       switch (pb_prim.oneof_value_case()) {
837         case pb::Primitive::kNullValue: {
838           val.dataType = android::Res_value::TYPE_NULL;
839           val.data = android::Res_value::DATA_NULL_UNDEFINED;
840         } break;
841         case pb::Primitive::kEmptyValue: {
842           val.dataType = android::Res_value::TYPE_NULL;
843           val.data = android::Res_value::DATA_NULL_EMPTY;
844         } break;
845         case pb::Primitive::kFloatValue: {
846           val.dataType = android::Res_value::TYPE_FLOAT;
847           float float_val = pb_prim.float_value();
848           val.data = *(uint32_t*)&float_val;
849         } break;
850         case pb::Primitive::kDimensionValue: {
851           val.dataType = android::Res_value::TYPE_DIMENSION;
852           val.data  = pb_prim.dimension_value();
853         } break;
854         case pb::Primitive::kFractionValue: {
855           val.dataType = android::Res_value::TYPE_FRACTION;
856           val.data  = pb_prim.fraction_value();
857         } break;
858         case pb::Primitive::kIntDecimalValue: {
859           val.dataType = android::Res_value::TYPE_INT_DEC;
860           val.data = static_cast<uint32_t>(pb_prim.int_decimal_value());
861         } break;
862         case pb::Primitive::kIntHexadecimalValue: {
863           val.dataType = android::Res_value::TYPE_INT_HEX;
864           val.data = pb_prim.int_hexadecimal_value();
865         } break;
866         case pb::Primitive::kBooleanValue: {
867           val.dataType = android::Res_value::TYPE_INT_BOOLEAN;
868           val.data = pb_prim.boolean_value() ? 0xFFFFFFFF : 0x0;
869         } break;
870         case pb::Primitive::kColorArgb8Value: {
871           val.dataType = android::Res_value::TYPE_INT_COLOR_ARGB8;
872           val.data = pb_prim.color_argb8_value();
873         } break;
874         case pb::Primitive::kColorRgb8Value: {
875           val.dataType = android::Res_value::TYPE_INT_COLOR_RGB8;
876           val.data = pb_prim.color_rgb8_value();
877         } break;
878         case pb::Primitive::kColorArgb4Value: {
879           val.dataType = android::Res_value::TYPE_INT_COLOR_ARGB4;
880           val.data = pb_prim.color_argb4_value();
881         } break;
882         case pb::Primitive::kColorRgb4Value: {
883           val.dataType = android::Res_value::TYPE_INT_COLOR_RGB4;
884           val.data = pb_prim.color_rgb4_value();
885         } break;
886         case pb::Primitive::kDimensionValueDeprecated: {  // DEPRECATED
887           val.dataType = android::Res_value::TYPE_DIMENSION;
888           float dimen_val = pb_prim.dimension_value_deprecated();
889           val.data = *(uint32_t*)&dimen_val;
890         } break;
891         case pb::Primitive::kFractionValueDeprecated: {  // DEPRECATED
892           val.dataType = android::Res_value::TYPE_FRACTION;
893           float fraction_val = pb_prim.fraction_value_deprecated();
894           val.data = *(uint32_t*)&fraction_val;
895         } break;
896         default: {
897           LOG(FATAL) << "Unexpected Primitive type: "
898                      << static_cast<uint32_t>(pb_prim.oneof_value_case());
899           return {};
900         } break;
901       }
902       return util::make_unique<BinaryPrimitive>(val);
903     } break;
904 
905     case pb::Item::kId: {
906       return util::make_unique<Id>();
907     } break;
908 
909     case pb::Item::kStr: {
910       return util::make_unique<String>(
911           value_pool->MakeRef(pb_item.str().value(), StringPool::Context(config)));
912     } break;
913 
914     case pb::Item::kRawStr: {
915       return util::make_unique<RawString>(
916           value_pool->MakeRef(pb_item.raw_str().value(), StringPool::Context(config)));
917     } break;
918 
919     case pb::Item::kStyledStr: {
920       const pb::StyledString& pb_str = pb_item.styled_str();
921       StyleString style_str{pb_str.value()};
922       for (const pb::StyledString::Span& pb_span : pb_str.span()) {
923         style_str.spans.push_back(Span{pb_span.tag(), pb_span.first_char(), pb_span.last_char()});
924       }
925       return util::make_unique<StyledString>(value_pool->MakeRef(
926           style_str, StringPool::Context(StringPool::Context::kNormalPriority, config)));
927     } break;
928 
929     case pb::Item::kFile: {
930       const pb::FileReference& pb_file = pb_item.file();
931       std::unique_ptr<FileReference> file_ref =
932           util::make_unique<FileReference>(value_pool->MakeRef(
933               pb_file.path(), StringPool::Context(StringPool::Context::kHighPriority, config)));
934       file_ref->type = DeserializeFileReferenceTypeFromPb(pb_file.type());
935       if (files != nullptr) {
936         file_ref->file = files->FindFile(*file_ref->path);
937       }
938       return std::move(file_ref);
939     } break;
940 
941     default:
942       LOG(FATAL) << "unknown item: " << (int)pb_item.value_case();
943       break;
944   }
945   return {};
946 }
947 
DeserializeXmlResourceFromPb(const pb::XmlNode & pb_node,std::string * out_error)948 std::unique_ptr<xml::XmlResource> DeserializeXmlResourceFromPb(const pb::XmlNode& pb_node,
949                                                                std::string* out_error) {
950   if (!pb_node.has_element()) {
951     return {};
952   }
953 
954   std::unique_ptr<xml::XmlResource> resource = util::make_unique<xml::XmlResource>();
955   resource->root = util::make_unique<xml::Element>();
956   if (!DeserializeXmlFromPb(pb_node, resource->root.get(), &resource->string_pool, out_error)) {
957     return {};
958   }
959   return resource;
960 }
961 
DeserializeXmlFromPb(const pb::XmlNode & pb_node,xml::Element * out_el,StringPool * value_pool,std::string * out_error)962 bool DeserializeXmlFromPb(const pb::XmlNode& pb_node, xml::Element* out_el, StringPool* value_pool,
963                           std::string* out_error) {
964   const pb::XmlElement& pb_el = pb_node.element();
965   out_el->name = pb_el.name();
966   out_el->namespace_uri = pb_el.namespace_uri();
967   out_el->line_number = pb_node.source().line_number();
968   out_el->column_number = pb_node.source().column_number();
969 
970   for (const pb::XmlNamespace& pb_ns : pb_el.namespace_declaration()) {
971     xml::NamespaceDecl decl;
972     decl.uri = pb_ns.uri();
973     decl.prefix = pb_ns.prefix();
974     decl.line_number = pb_ns.source().line_number();
975     decl.column_number = pb_ns.source().column_number();
976     out_el->namespace_decls.push_back(std::move(decl));
977   }
978 
979   for (const pb::XmlAttribute& pb_attr : pb_el.attribute()) {
980     xml::Attribute attr;
981     attr.name = pb_attr.name();
982     attr.namespace_uri = pb_attr.namespace_uri();
983     attr.value = pb_attr.value();
984     if (pb_attr.resource_id() != 0u) {
985       attr.compiled_attribute = xml::AaptAttribute{Attribute(), ResourceId(pb_attr.resource_id())};
986     }
987     if (pb_attr.has_compiled_item()) {
988       attr.compiled_value =
989           DeserializeItemFromPb(pb_attr.compiled_item(), {}, {}, value_pool, nullptr, out_error);
990       if (attr.compiled_value == nullptr) {
991         return {};
992       }
993       attr.compiled_value->SetSource(Source().WithLine(pb_attr.source().line_number()));
994     }
995     out_el->attributes.push_back(std::move(attr));
996   }
997 
998   // Deserialize the children.
999   for (const pb::XmlNode& pb_child : pb_el.child()) {
1000     switch (pb_child.node_case()) {
1001       case pb::XmlNode::NodeCase::kText: {
1002         std::unique_ptr<xml::Text> text = util::make_unique<xml::Text>();
1003         text->line_number = pb_child.source().line_number();
1004         text->column_number = pb_child.source().column_number();
1005         text->text = pb_child.text();
1006         out_el->AppendChild(std::move(text));
1007       } break;
1008 
1009       case pb::XmlNode::NodeCase::kElement: {
1010         std::unique_ptr<xml::Element> child_el = util::make_unique<xml::Element>();
1011         if (!DeserializeXmlFromPb(pb_child, child_el.get(), value_pool, out_error)) {
1012           return false;
1013         }
1014         out_el->AppendChild(std::move(child_el));
1015       } break;
1016 
1017       default:
1018         LOG(FATAL) << "unknown XmlNode " << (int)pb_child.node_case();
1019         break;
1020     }
1021   }
1022   return true;
1023 }
1024 
1025 }  // namespace aapt
1026