1 /*
2  * Copyright (C) 2018 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 "idmap2/PrettyPrintVisitor.h"
18 
19 #include <string>
20 
21 #include "android-base/macros.h"
22 #include "android-base/stringprintf.h"
23 #include "androidfw/ApkAssets.h"
24 #include "idmap2/ResourceUtils.h"
25 #include "idmap2/Result.h"
26 
27 namespace android::idmap2 {
28 
29 #define RESID(pkg, type, entry) (((pkg) << 24) | ((type) << 16) | (entry))
30 
visit(const Idmap & idmap ATTRIBUTE_UNUSED)31 void PrettyPrintVisitor::visit(const Idmap& idmap ATTRIBUTE_UNUSED) {
32 }
33 
visit(const IdmapHeader & header)34 void PrettyPrintVisitor::visit(const IdmapHeader& header) {
35   stream_ << "target apk path  : " << header.GetTargetPath() << std::endl
36           << "overlay apk path : " << header.GetOverlayPath() << std::endl;
37 
38   target_apk_ = ApkAssets::Load(header.GetTargetPath().to_string());
39   if (target_apk_) {
40     target_am_.SetApkAssets({target_apk_.get()});
41   }
42 }
43 
visit(const IdmapData & data ATTRIBUTE_UNUSED)44 void PrettyPrintVisitor::visit(const IdmapData& data ATTRIBUTE_UNUSED) {
45 }
46 
visit(const IdmapData::Header & header ATTRIBUTE_UNUSED)47 void PrettyPrintVisitor::visit(const IdmapData::Header& header ATTRIBUTE_UNUSED) {
48   last_seen_package_id_ = header.GetTargetPackageId();
49 }
50 
visit(const IdmapData::TypeEntry & type_entry)51 void PrettyPrintVisitor::visit(const IdmapData::TypeEntry& type_entry) {
52   const bool target_package_loaded = !target_am_.GetApkAssets().empty();
53   for (uint16_t i = 0; i < type_entry.GetEntryCount(); i++) {
54     const EntryId entry = type_entry.GetEntry(i);
55     if (entry == kNoEntry) {
56       continue;
57     }
58 
59     const ResourceId target_resid =
60         RESID(last_seen_package_id_, type_entry.GetTargetTypeId(), type_entry.GetEntryOffset() + i);
61     const ResourceId overlay_resid =
62         RESID(last_seen_package_id_, type_entry.GetOverlayTypeId(), entry);
63 
64     stream_ << base::StringPrintf("0x%08x -> 0x%08x", target_resid, overlay_resid);
65     if (target_package_loaded) {
66       Result<std::string> name = utils::ResToTypeEntryName(target_am_, target_resid);
67       if (name) {
68         stream_ << " " << *name;
69       }
70     }
71     stream_ << std::endl;
72   }
73 }
74 
75 }  // namespace android::idmap2
76