blob: 3805825c86825a939227b24760011e12e6c69e18 [file] [log] [blame]
David Brazdil2b9c35b2018-01-12 15:44:43 +00001/*
2 * Copyright (C) 2017 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 <fstream>
18#include <iostream>
David Brazdil0b6de0c2018-06-28 11:56:41 +010019#include <map>
20#include <set>
Vladimir Markoe5125562019-02-06 17:38:26 +000021#include <string>
22#include <string_view>
David Brazdil2b9c35b2018-01-12 15:44:43 +000023
24#include "android-base/stringprintf.h"
25#include "android-base/strings.h"
26
David Brazdil20c765f2018-10-27 21:45:15 +000027#include "base/bit_utils.h"
David Brazdildcfa89b2018-10-31 11:04:10 +000028#include "base/hiddenapi_flags.h"
David Sehr79e26072018-04-06 17:58:50 -070029#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080030#include "base/os.h"
David Brazdildcfa89b2018-10-31 11:04:10 +000031#include "base/stl_util.h"
Vladimir Markoe5125562019-02-06 17:38:26 +000032#include "base/string_view_cpp20.h"
David Brazdil2b9c35b2018-01-12 15:44:43 +000033#include "base/unix_file/fd_file.h"
34#include "dex/art_dex_file_loader.h"
Mathieu Chartier396dc082018-08-06 12:29:57 -070035#include "dex/class_accessor-inl.h"
David Brazdil2b9c35b2018-01-12 15:44:43 +000036#include "dex/dex_file-inl.h"
David Brazdil2b9c35b2018-01-12 15:44:43 +000037
38namespace art {
David Brazdil62a4bcf2018-12-13 17:00:06 +000039namespace hiddenapi {
David Brazdil2b9c35b2018-01-12 15:44:43 +000040
Mathew Inwoodb62f6f12019-01-07 14:02:52 +000041const char kErrorHelp[] = "\nSee go/hiddenapi-error for help.";
42
David Brazdil2b9c35b2018-01-12 15:44:43 +000043static int original_argc;
44static char** original_argv;
45
46static std::string CommandLine() {
47 std::vector<std::string> command;
Andreas Gampe2a487eb2018-11-19 11:41:22 -080048 command.reserve(original_argc);
David Brazdil2b9c35b2018-01-12 15:44:43 +000049 for (int i = 0; i < original_argc; ++i) {
50 command.push_back(original_argv[i]);
51 }
52 return android::base::Join(command, ' ');
53}
54
55static void UsageErrorV(const char* fmt, va_list ap) {
56 std::string error;
57 android::base::StringAppendV(&error, fmt, ap);
58 LOG(ERROR) << error;
59}
60
61static void UsageError(const char* fmt, ...) {
62 va_list ap;
63 va_start(ap, fmt);
64 UsageErrorV(fmt, ap);
65 va_end(ap);
66}
67
68NO_RETURN static void Usage(const char* fmt, ...) {
69 va_list ap;
70 va_start(ap, fmt);
71 UsageErrorV(fmt, ap);
72 va_end(ap);
73
74 UsageError("Command: %s", CommandLine().c_str());
David Brazdil003e64b2018-06-27 13:20:52 +010075 UsageError("Usage: hiddenapi [command_name] [options]...");
David Brazdil2b9c35b2018-01-12 15:44:43 +000076 UsageError("");
David Brazdil003e64b2018-06-27 13:20:52 +010077 UsageError(" Command \"encode\": encode API list membership in boot dex files");
David Brazdil20c765f2018-10-27 21:45:15 +000078 UsageError(" --input-dex=<filename>: dex file which belongs to boot class path");
79 UsageError(" --output-dex=<filename>: file to write encoded dex into");
80 UsageError(" input and output dex files are paired in order of appearance");
David Brazdil2b9c35b2018-01-12 15:44:43 +000081 UsageError("");
David Brazdil91690d32018-11-04 18:07:23 +000082 UsageError(" --api-flags=<filename>:");
83 UsageError(" CSV file with signatures of methods/fields and their respective flags");
84 UsageError("");
85 UsageError(" --no-force-assign-all:");
86 UsageError(" Disable check that all dex entries have been assigned a flag");
David Brazdil2b9c35b2018-01-12 15:44:43 +000087 UsageError("");
David Brazdil0b6de0c2018-06-28 11:56:41 +010088 UsageError(" Command \"list\": dump lists of public and private API");
89 UsageError(" --boot-dex=<filename>: dex file which belongs to boot class path");
David Brazdil62a4bcf2018-12-13 17:00:06 +000090 UsageError(" --public-stub-classpath=<filenames>:");
Andrei Onea370a0642019-03-01 17:48:27 +000091 UsageError(" --system-stub-classpath=<filenames>:");
92 UsageError(" --test-stub-classpath=<filenames>:");
David Brazdil90faceb2018-12-14 14:36:15 +000093 UsageError(" --core-platform-stub-classpath=<filenames>:");
David Brazdil62a4bcf2018-12-13 17:00:06 +000094 UsageError(" colon-separated list of dex/apk files which form API stubs of boot");
95 UsageError(" classpath. Multiple classpaths can be specified");
David Brazdil0b6de0c2018-06-28 11:56:41 +010096 UsageError("");
David Brazdil62a4bcf2018-12-13 17:00:06 +000097 UsageError(" --out-api-flags=<filename>: output file for a CSV file with API flags");
David Brazdil0b6de0c2018-06-28 11:56:41 +010098 UsageError("");
David Brazdil2b9c35b2018-01-12 15:44:43 +000099
100 exit(EXIT_FAILURE);
101}
102
David Brazdil0b6de0c2018-06-28 11:56:41 +0100103template<typename E>
104static bool Contains(const std::vector<E>& vec, const E& elem) {
105 return std::find(vec.begin(), vec.end(), elem) != vec.end();
106}
107
Mathieu Chartier396dc082018-08-06 12:29:57 -0700108class DexClass : public ClassAccessor {
David Brazdil2b9c35b2018-01-12 15:44:43 +0000109 public:
Mathieu Chartier396dc082018-08-06 12:29:57 -0700110 explicit DexClass(const ClassAccessor& accessor) : ClassAccessor(accessor) {}
David Brazdil2b9c35b2018-01-12 15:44:43 +0000111
Mathieu Chartier396dc082018-08-06 12:29:57 -0700112 const uint8_t* GetData() const { return dex_file_.GetClassData(GetClassDef()); }
David Brazdil2b9c35b2018-01-12 15:44:43 +0000113
Mathieu Chartier396dc082018-08-06 12:29:57 -0700114 const dex::TypeIndex GetSuperclassIndex() const { return GetClassDef().superclass_idx_; }
David Brazdil0b6de0c2018-06-28 11:56:41 +0100115
116 bool HasSuperclass() const { return dex_file_.IsTypeIndexValid(GetSuperclassIndex()); }
117
Vladimir Markoae1d2c82019-02-18 13:40:44 +0000118 std::string_view GetSuperclassDescriptor() const {
Mathieu Chartier396dc082018-08-06 12:29:57 -0700119 return HasSuperclass() ? dex_file_.StringByTypeIdx(GetSuperclassIndex()) : "";
David Brazdil0b6de0c2018-06-28 11:56:41 +0100120 }
121
Vladimir Markoae1d2c82019-02-18 13:40:44 +0000122 std::set<std::string_view> GetInterfaceDescriptors() const {
123 std::set<std::string_view> list;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800124 const dex::TypeList* ifaces = dex_file_.GetInterfacesList(GetClassDef());
David Brazdil0b6de0c2018-06-28 11:56:41 +0100125 for (uint32_t i = 0; ifaces != nullptr && i < ifaces->Size(); ++i) {
126 list.insert(dex_file_.StringByTypeIdx(ifaces->GetTypeItem(i).type_idx_));
127 }
128 return list;
129 }
130
David Brazdil345c0ed2018-08-03 10:26:44 +0100131 inline bool IsPublic() const { return HasAccessFlags(kAccPublic); }
David Brazdil2da3cbb2019-01-30 16:17:50 +0000132 inline bool IsInterface() const { return HasAccessFlags(kAccInterface); }
David Brazdil0b6de0c2018-06-28 11:56:41 +0100133
134 inline bool Equals(const DexClass& other) const {
Mathieu Chartier396dc082018-08-06 12:29:57 -0700135 bool equals = strcmp(GetDescriptor(), other.GetDescriptor()) == 0;
David Brazdil95779c92019-01-24 09:59:08 +0000136
David Brazdil0b6de0c2018-06-28 11:56:41 +0100137 if (equals) {
David Brazdil95779c92019-01-24 09:59:08 +0000138 LOG(FATAL) << "Class duplication: " << GetDescriptor() << " in " << dex_file_.GetLocation()
139 << " and " << other.dex_file_.GetLocation();
David Brazdil0b6de0c2018-06-28 11:56:41 +0100140 }
David Brazdil95779c92019-01-24 09:59:08 +0000141
David Brazdil0b6de0c2018-06-28 11:56:41 +0100142 return equals;
143 }
David Brazdil2b9c35b2018-01-12 15:44:43 +0000144
145 private:
Mathieu Chartier396dc082018-08-06 12:29:57 -0700146 uint32_t GetAccessFlags() const { return GetClassDef().access_flags_; }
David Brazdil0b6de0c2018-06-28 11:56:41 +0100147 bool HasAccessFlags(uint32_t mask) const { return (GetAccessFlags() & mask) == mask; }
David Brazdil1ff5a652019-01-18 11:44:44 +0000148
Vladimir Markoae1d2c82019-02-18 13:40:44 +0000149 static std::string JoinStringSet(const std::set<std::string_view>& s) {
David Brazdil1ff5a652019-01-18 11:44:44 +0000150 return "{" + ::android::base::Join(std::vector<std::string>(s.begin(), s.end()), ",") + "}";
151 }
David Brazdil2b9c35b2018-01-12 15:44:43 +0000152};
153
154class DexMember {
155 public:
Mathieu Chartier396dc082018-08-06 12:29:57 -0700156 DexMember(const DexClass& klass, const ClassAccessor::Field& item)
157 : klass_(klass), item_(item), is_method_(false) {
158 DCHECK_EQ(GetFieldId().class_idx_, klass.GetClassIdx());
159 }
160
161 DexMember(const DexClass& klass, const ClassAccessor::Method& item)
162 : klass_(klass), item_(item), is_method_(true) {
163 DCHECK_EQ(GetMethodId().class_idx_, klass.GetClassIdx());
David Brazdil2b9c35b2018-01-12 15:44:43 +0000164 }
165
David Brazdil0b6de0c2018-06-28 11:56:41 +0100166 inline const DexClass& GetDeclaringClass() const { return klass_; }
167
Mathieu Chartier396dc082018-08-06 12:29:57 -0700168 inline bool IsMethod() const { return is_method_; }
169 inline bool IsVirtualMethod() const { return IsMethod() && !GetMethod().IsStaticOrDirect(); }
David Brazdil345c0ed2018-08-03 10:26:44 +0100170 inline bool IsConstructor() const { return IsMethod() && HasAccessFlags(kAccConstructor); }
David Brazdil0b6de0c2018-06-28 11:56:41 +0100171
David Brazdil345c0ed2018-08-03 10:26:44 +0100172 inline bool IsPublicOrProtected() const {
173 return HasAccessFlags(kAccPublic) || HasAccessFlags(kAccProtected);
David Brazdil0b6de0c2018-06-28 11:56:41 +0100174 }
175
David Brazdil2b9c35b2018-01-12 15:44:43 +0000176 // Constructs a string with a unique signature of this class member.
177 std::string GetApiEntry() const {
178 std::stringstream ss;
Mathieu Chartier396dc082018-08-06 12:29:57 -0700179 ss << klass_.GetDescriptor() << "->" << GetName() << (IsMethod() ? "" : ":")
180 << GetSignature();
David Brazdil2b9c35b2018-01-12 15:44:43 +0000181 return ss.str();
182 }
183
Mathieu Chartier396dc082018-08-06 12:29:57 -0700184 inline bool operator==(const DexMember& other) const {
David Brazdil0b6de0c2018-06-28 11:56:41 +0100185 // These need to match if they should resolve to one another.
186 bool equals = IsMethod() == other.IsMethod() &&
187 GetName() == other.GetName() &&
188 GetSignature() == other.GetSignature();
189
Orion Hodson2d455202020-07-28 16:22:10 +0100190 // Soundness check that they do match.
David Brazdil0b6de0c2018-06-28 11:56:41 +0100191 if (equals) {
192 CHECK_EQ(IsVirtualMethod(), other.IsVirtualMethod());
193 }
194
195 return equals;
196 }
197
David Brazdil2b9c35b2018-01-12 15:44:43 +0000198 private:
Mathieu Chartier396dc082018-08-06 12:29:57 -0700199 inline uint32_t GetAccessFlags() const { return item_.GetAccessFlags(); }
Andreas Gampe7c5acbb2018-09-20 13:54:52 -0700200 inline bool HasAccessFlags(uint32_t mask) const { return (GetAccessFlags() & mask) == mask; }
David Brazdil0b6de0c2018-06-28 11:56:41 +0100201
Vladimir Markoae1d2c82019-02-18 13:40:44 +0000202 inline std::string_view GetName() const {
Mathieu Chartier396dc082018-08-06 12:29:57 -0700203 return IsMethod() ? item_.GetDexFile().GetMethodName(GetMethodId())
204 : item_.GetDexFile().GetFieldName(GetFieldId());
David Brazdil0b6de0c2018-06-28 11:56:41 +0100205 }
206
207 inline std::string GetSignature() const {
Mathieu Chartier396dc082018-08-06 12:29:57 -0700208 return IsMethod() ? item_.GetDexFile().GetMethodSignature(GetMethodId()).ToString()
209 : item_.GetDexFile().GetFieldTypeDescriptor(GetFieldId());
210 }
211
212 inline const ClassAccessor::Method& GetMethod() const {
213 DCHECK(IsMethod());
214 return down_cast<const ClassAccessor::Method&>(item_);
David Brazdil0b6de0c2018-06-28 11:56:41 +0100215 }
216
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800217 inline const dex::MethodId& GetMethodId() const {
David Brazdil0b6de0c2018-06-28 11:56:41 +0100218 DCHECK(IsMethod());
Mathieu Chartier396dc082018-08-06 12:29:57 -0700219 return item_.GetDexFile().GetMethodId(item_.GetIndex());
David Brazdil2b9c35b2018-01-12 15:44:43 +0000220 }
221
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800222 inline const dex::FieldId& GetFieldId() const {
David Brazdil0b6de0c2018-06-28 11:56:41 +0100223 DCHECK(!IsMethod());
Mathieu Chartier396dc082018-08-06 12:29:57 -0700224 return item_.GetDexFile().GetFieldId(item_.GetIndex());
David Brazdil2b9c35b2018-01-12 15:44:43 +0000225 }
226
David Brazdil2b9c35b2018-01-12 15:44:43 +0000227 const DexClass& klass_;
Mathieu Chartier396dc082018-08-06 12:29:57 -0700228 const ClassAccessor::BaseItem& item_;
229 const bool is_method_;
David Brazdil2b9c35b2018-01-12 15:44:43 +0000230};
231
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100232class ClassPath final {
David Brazdil2b9c35b2018-01-12 15:44:43 +0000233 public:
Paul Duffin496b9b42021-05-17 12:23:01 +0100234 ClassPath(const std::vector<std::string>& dex_paths, bool open_writable, bool ignore_empty) {
235 OpenDexFiles(dex_paths, open_writable, ignore_empty);
David Brazdil0b6de0c2018-06-28 11:56:41 +0100236 }
237
238 template<typename Fn>
239 void ForEachDexClass(Fn fn) {
240 for (auto& dex_file : dex_files_) {
Mathieu Chartier396dc082018-08-06 12:29:57 -0700241 for (ClassAccessor accessor : dex_file->GetClasses()) {
242 fn(DexClass(accessor));
David Brazdil0b6de0c2018-06-28 11:56:41 +0100243 }
244 }
David Brazdil2b9c35b2018-01-12 15:44:43 +0000245 }
246
David Brazdil003e64b2018-06-27 13:20:52 +0100247 template<typename Fn>
248 void ForEachDexMember(Fn fn) {
Mathieu Chartier396dc082018-08-06 12:29:57 -0700249 ForEachDexClass([&fn](const DexClass& klass) {
250 for (const ClassAccessor::Field& field : klass.GetFields()) {
251 fn(DexMember(klass, field));
252 }
253 for (const ClassAccessor::Method& method : klass.GetMethods()) {
254 fn(DexMember(klass, method));
David Brazdil2b9c35b2018-01-12 15:44:43 +0000255 }
David Brazdil0b6de0c2018-06-28 11:56:41 +0100256 });
David Brazdil2b9c35b2018-01-12 15:44:43 +0000257 }
258
David Brazdil20c765f2018-10-27 21:45:15 +0000259 std::vector<const DexFile*> GetDexFiles() const {
260 return MakeNonOwningPointerVector(dex_files_);
261 }
262
David Brazdil2b9c35b2018-01-12 15:44:43 +0000263 void UpdateDexChecksums() {
264 for (auto& dex_file : dex_files_) {
265 // Obtain a writeable pointer to the dex header.
266 DexFile::Header* header = const_cast<DexFile::Header*>(&dex_file->GetHeader());
267 // Recalculate checksum and overwrite the value in the header.
268 header->checksum_ = dex_file->CalculateChecksum();
269 }
270 }
271
David Brazdil003e64b2018-06-27 13:20:52 +0100272 private:
Paul Duffin496b9b42021-05-17 12:23:01 +0100273 void OpenDexFiles(const std::vector<std::string>& dex_paths,
274 bool open_writable,
275 bool ignore_empty) {
David Brazdil003e64b2018-06-27 13:20:52 +0100276 ArtDexFileLoader dex_loader;
277 std::string error_msg;
David Brazdil003e64b2018-06-27 13:20:52 +0100278
David Brazdil0b6de0c2018-06-28 11:56:41 +0100279 if (open_writable) {
280 for (const std::string& filename : dex_paths) {
Andreas Gampe9b031f72018-10-04 11:03:34 -0700281 File fd(filename.c_str(), O_RDWR, /* check_usage= */ false);
David Brazdil0b6de0c2018-06-28 11:56:41 +0100282 CHECK_NE(fd.Fd(), -1) << "Unable to open file '" << filename << "': " << strerror(errno);
283
284 // Memory-map the dex file with MAP_SHARED flag so that changes in memory
285 // propagate to the underlying file. We run dex file verification as if
286 // the dex file was not in boot claass path to check basic assumptions,
287 // such as that at most one of public/private/protected flag is set.
288 // We do those checks here and skip them when loading the processed file
289 // into boot class path.
290 std::unique_ptr<const DexFile> dex_file(dex_loader.OpenDex(fd.Release(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700291 /* location= */ filename,
292 /* verify= */ true,
293 /* verify_checksum= */ true,
294 /* mmap_shared= */ true,
David Brazdil0b6de0c2018-06-28 11:56:41 +0100295 &error_msg));
296 CHECK(dex_file.get() != nullptr) << "Open failed for '" << filename << "' " << error_msg;
297 CHECK(dex_file->IsStandardDexFile()) << "Expected a standard dex file '" << filename << "'";
298 CHECK(dex_file->EnableWrite())
299 << "Failed to enable write permission for '" << filename << "'";
300 dex_files_.push_back(std::move(dex_file));
301 }
302 } else {
303 for (const std::string& filename : dex_paths) {
304 bool success = dex_loader.Open(filename.c_str(),
Andreas Gampe9b031f72018-10-04 11:03:34 -0700305 /* location= */ filename,
306 /* verify= */ true,
307 /* verify_checksum= */ true,
David Brazdil0b6de0c2018-06-28 11:56:41 +0100308 &error_msg,
309 &dex_files_);
Paul Duffin496b9b42021-05-17 12:23:01 +0100310 // If requested ignore a jar with no classes.dex files.
311 if (!success && ignore_empty && error_msg != "Entry not found") {
312 CHECK(success) << "Open failed for '" << filename << "' " << error_msg;
313 }
David Brazdil0b6de0c2018-06-28 11:56:41 +0100314 }
David Brazdil003e64b2018-06-27 13:20:52 +0100315 }
316 }
317
David Brazdil0b6de0c2018-06-28 11:56:41 +0100318 // Opened dex files. Note that these are opened as `const` but may be written into.
David Brazdil003e64b2018-06-27 13:20:52 +0100319 std::vector<std::unique_ptr<const DexFile>> dex_files_;
320};
321
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100322class HierarchyClass final {
David Brazdil0b6de0c2018-06-28 11:56:41 +0100323 public:
324 HierarchyClass() {}
325
326 void AddDexClass(const DexClass& klass) {
327 CHECK(dex_classes_.empty() || klass.Equals(dex_classes_.front()));
328 dex_classes_.push_back(klass);
329 }
330
331 void AddExtends(HierarchyClass& parent) {
332 CHECK(!Contains(extends_, &parent));
333 CHECK(!Contains(parent.extended_by_, this));
334 extends_.push_back(&parent);
335 parent.extended_by_.push_back(this);
336 }
337
338 const DexClass& GetOneDexClass() const {
339 CHECK(!dex_classes_.empty());
340 return dex_classes_.front();
341 }
342
343 // See comment on Hierarchy::ForEachResolvableMember.
344 template<typename Fn>
345 bool ForEachResolvableMember(const DexMember& other, Fn fn) {
David Brazdil2da3cbb2019-01-30 16:17:50 +0000346 std::vector<HierarchyClass*> visited;
347 return ForEachResolvableMember_Impl(other, fn, true, true, visited);
David Brazdil0b6de0c2018-06-28 11:56:41 +0100348 }
349
David Brazdil345c0ed2018-08-03 10:26:44 +0100350 // Returns true if this class contains at least one member matching `other`.
351 bool HasMatchingMember(const DexMember& other) {
David Brazdil2da3cbb2019-01-30 16:17:50 +0000352 return ForEachMatchingMember(other, [](const DexMember&) { return true; });
David Brazdil345c0ed2018-08-03 10:26:44 +0100353 }
354
355 // Recursively iterates over all subclasses of this class and invokes `fn`
356 // on each one. If `fn` returns false for a particular subclass, exploring its
357 // subclasses is skipped.
358 template<typename Fn>
359 void ForEachSubClass(Fn fn) {
360 for (HierarchyClass* subclass : extended_by_) {
361 if (fn(subclass)) {
362 subclass->ForEachSubClass(fn);
363 }
364 }
365 }
366
David Brazdil0b6de0c2018-06-28 11:56:41 +0100367 private:
David Brazdil0b6de0c2018-06-28 11:56:41 +0100368 template<typename Fn>
David Brazdil2da3cbb2019-01-30 16:17:50 +0000369 bool ForEachResolvableMember_Impl(const DexMember& other,
370 Fn fn,
371 bool allow_explore_up,
372 bool allow_explore_down,
373 std::vector<HierarchyClass*> visited) {
374 if (std::find(visited.begin(), visited.end(), this) == visited.end()) {
375 visited.push_back(this);
376 } else {
377 return false;
David Brazdil0b6de0c2018-06-28 11:56:41 +0100378 }
379
David Brazdil2da3cbb2019-01-30 16:17:50 +0000380 // First try to find a member matching `other` in this class.
381 bool found = ForEachMatchingMember(other, fn);
382
383 // If not found, see if it is inherited from parents. Note that this will not
384 // revisit parents already in `visited`.
385 if (!found && allow_explore_up) {
386 for (HierarchyClass* superclass : extends_) {
387 found |= superclass->ForEachResolvableMember_Impl(
388 other,
389 fn,
390 /* allow_explore_up */ true,
391 /* allow_explore_down */ false,
392 visited);
393 }
394 }
395
396 // If this is a virtual method, continue exploring into subclasses so as to visit
397 // all overriding methods. Allow subclasses to explore their superclasses if this
398 // is an interface. This is needed to find implementations of this interface's
399 // methods inherited from superclasses (b/122551864).
400 if (allow_explore_down && other.IsVirtualMethod()) {
401 for (HierarchyClass* subclass : extended_by_) {
402 subclass->ForEachResolvableMember_Impl(
403 other,
404 fn,
405 /* allow_explore_up */ GetOneDexClass().IsInterface(),
406 /* allow_explore_down */ true,
407 visited);
408 }
409 }
410
411 return found;
David Brazdil0b6de0c2018-06-28 11:56:41 +0100412 }
413
414 template<typename Fn>
David Brazdil2da3cbb2019-01-30 16:17:50 +0000415 bool ForEachMatchingMember(const DexMember& other, Fn fn) {
416 bool found = false;
Mathieu Chartier396dc082018-08-06 12:29:57 -0700417 auto compare_member = [&](const DexMember& member) {
David Brazdil2da3cbb2019-01-30 16:17:50 +0000418 // TODO(dbrazdil): Check whether class of `other` can access `member`.
Mathieu Chartier396dc082018-08-06 12:29:57 -0700419 if (member == other) {
David Brazdil2da3cbb2019-01-30 16:17:50 +0000420 found = true;
421 fn(member);
Mathieu Chartier396dc082018-08-06 12:29:57 -0700422 }
423 };
David Brazdil0b6de0c2018-06-28 11:56:41 +0100424 for (const DexClass& dex_class : dex_classes_) {
Mathieu Chartier396dc082018-08-06 12:29:57 -0700425 for (const ClassAccessor::Field& field : dex_class.GetFields()) {
426 compare_member(DexMember(dex_class, field));
427 }
428 for (const ClassAccessor::Method& method : dex_class.GetMethods()) {
429 compare_member(DexMember(dex_class, method));
David Brazdil0b6de0c2018-06-28 11:56:41 +0100430 }
431 }
432 return found;
433 }
434
David Brazdil0b6de0c2018-06-28 11:56:41 +0100435 // DexClass entries of this class found across all the provided dex files.
436 std::vector<DexClass> dex_classes_;
437
438 // Classes which this class inherits, or interfaces which it implements.
439 std::vector<HierarchyClass*> extends_;
440
441 // Classes which inherit from this class.
442 std::vector<HierarchyClass*> extended_by_;
443};
444
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100445class Hierarchy final {
David Brazdil0b6de0c2018-06-28 11:56:41 +0100446 public:
David Brazdil345c0ed2018-08-03 10:26:44 +0100447 explicit Hierarchy(ClassPath& classpath) : classpath_(classpath) {
David Brazdil0b6de0c2018-06-28 11:56:41 +0100448 BuildClassHierarchy();
449 }
450
451 // Perform an operation for each member of the hierarchy which could potentially
452 // be the result of method/field resolution of `other`.
453 // The function `fn` should accept a DexMember reference and return true if
454 // the member was changed. This drives a performance optimization which only
455 // visits overriding members the first time the overridden member is visited.
456 // Returns true if at least one resolvable member was found.
457 template<typename Fn>
458 bool ForEachResolvableMember(const DexMember& other, Fn fn) {
459 HierarchyClass* klass = FindClass(other.GetDeclaringClass().GetDescriptor());
460 return (klass != nullptr) && klass->ForEachResolvableMember(other, fn);
461 }
462
David Brazdil345c0ed2018-08-03 10:26:44 +0100463 // Returns true if `member`, which belongs to this classpath, is visible to
464 // code in child class loaders.
465 bool IsMemberVisible(const DexMember& member) {
466 if (!member.IsPublicOrProtected()) {
467 // Member is private or package-private. Cannot be visible.
468 return false;
469 } else if (member.GetDeclaringClass().IsPublic()) {
470 // Member is public or protected, and class is public. It must be visible.
471 return true;
472 } else if (member.IsConstructor()) {
473 // Member is public or protected constructor and class is not public.
474 // Must be hidden because it cannot be implicitly exposed by a subclass.
475 return false;
476 } else {
477 // Member is public or protected method, but class is not public. Check if
478 // it is exposed through a public subclass.
479 // Example code (`foo` exposed by ClassB):
480 // class ClassA { public void foo() { ... } }
481 // public class ClassB extends ClassA {}
482 HierarchyClass* klass = FindClass(member.GetDeclaringClass().GetDescriptor());
483 CHECK(klass != nullptr);
484 bool visible = false;
485 klass->ForEachSubClass([&visible, &member](HierarchyClass* subclass) {
486 if (subclass->HasMatchingMember(member)) {
487 // There is a member which matches `member` in `subclass`, either
488 // a virtual method overriding `member` or a field overshadowing
489 // `member`. In either case, `member` remains hidden.
490 CHECK(member.IsVirtualMethod() || !member.IsMethod());
491 return false; // do not explore deeper
492 } else if (subclass->GetOneDexClass().IsPublic()) {
493 // `subclass` inherits and exposes `member`.
494 visible = true;
495 return false; // do not explore deeper
496 } else {
497 // `subclass` inherits `member` but does not expose it.
498 return true; // explore deeper
499 }
500 });
501 return visible;
502 }
503 }
504
David Brazdil0b6de0c2018-06-28 11:56:41 +0100505 private:
Vladimir Markoae1d2c82019-02-18 13:40:44 +0000506 HierarchyClass* FindClass(const std::string_view& descriptor) {
David Brazdil0b6de0c2018-06-28 11:56:41 +0100507 auto it = classes_.find(descriptor);
508 if (it == classes_.end()) {
509 return nullptr;
510 } else {
511 return &it->second;
512 }
513 }
514
515 void BuildClassHierarchy() {
516 // Create one HierarchyClass entry in `classes_` per class descriptor
517 // and add all DexClass objects with the same descriptor to that entry.
Mathieu Chartier396dc082018-08-06 12:29:57 -0700518 classpath_.ForEachDexClass([this](const DexClass& klass) {
David Brazdil0b6de0c2018-06-28 11:56:41 +0100519 classes_[klass.GetDescriptor()].AddDexClass(klass);
520 });
521
522 // Connect each HierarchyClass to its successors and predecessors.
523 for (auto& entry : classes_) {
524 HierarchyClass& klass = entry.second;
525 const DexClass& dex_klass = klass.GetOneDexClass();
526
527 if (!dex_klass.HasSuperclass()) {
528 CHECK(dex_klass.GetInterfaceDescriptors().empty())
529 << "java/lang/Object should not implement any interfaces";
530 continue;
531 }
532
Anton Hanssonfdb81da2020-09-22 09:28:58 +0100533 auto add_extends = [&](const std::string_view& extends_desc) {
534 HierarchyClass* extends = FindClass(extends_desc);
535 CHECK(extends != nullptr)
536 << "Superclass/interface " << extends_desc
David Brazdilfe9181d2019-04-25 12:46:32 +0100537 << " of class " << dex_klass.GetDescriptor() << " from dex file \""
538 << dex_klass.GetDexFile().GetLocation() << "\" was not found. "
Anton Hanssonfdb81da2020-09-22 09:28:58 +0100539 << "Either it is missing or it appears later in the classpath spec.";
540 klass.AddExtends(*extends);
541 };
David Brazdil0b6de0c2018-06-28 11:56:41 +0100542
Anton Hanssonfdb81da2020-09-22 09:28:58 +0100543 add_extends(dex_klass.GetSuperclassDescriptor());
Vladimir Markoae1d2c82019-02-18 13:40:44 +0000544 for (const std::string_view& iface_desc : dex_klass.GetInterfaceDescriptors()) {
Anton Hanssonfdb81da2020-09-22 09:28:58 +0100545 add_extends(iface_desc);
David Brazdil0b6de0c2018-06-28 11:56:41 +0100546 }
547 }
548 }
549
David Brazdil345c0ed2018-08-03 10:26:44 +0100550 ClassPath& classpath_;
Vladimir Markoae1d2c82019-02-18 13:40:44 +0000551 std::map<std::string_view, HierarchyClass> classes_;
David Brazdil0b6de0c2018-06-28 11:56:41 +0100552};
553
David Brazdil20c765f2018-10-27 21:45:15 +0000554// Builder of dex section containing hiddenapi flags.
555class HiddenapiClassDataBuilder final {
556 public:
557 explicit HiddenapiClassDataBuilder(const DexFile& dex_file)
558 : num_classdefs_(dex_file.NumClassDefs()),
559 next_class_def_idx_(0u),
560 class_def_has_non_zero_flags_(false),
561 dex_file_has_non_zero_flags_(false),
562 data_(sizeof(uint32_t) * (num_classdefs_ + 1), 0u) {
563 *GetSizeField() = GetCurrentDataSize();
564 }
565
566 // Notify the builder that new flags for the next class def
567 // will be written now. The builder records the current offset
568 // into the header.
569 void BeginClassDef(uint32_t idx) {
570 CHECK_EQ(next_class_def_idx_, idx);
571 CHECK_LT(idx, num_classdefs_);
572 GetOffsetArray()[idx] = GetCurrentDataSize();
573 class_def_has_non_zero_flags_ = false;
574 }
575
576 // Notify the builder that all flags for this class def have been
577 // written. The builder updates the total size of the data struct
578 // and may set offset for class def in header to zero if no data
579 // has been written.
580 void EndClassDef(uint32_t idx) {
581 CHECK_EQ(next_class_def_idx_, idx);
582 CHECK_LT(idx, num_classdefs_);
583
584 ++next_class_def_idx_;
585
586 if (!class_def_has_non_zero_flags_) {
587 // No need to store flags for this class. Remove the written flags
588 // and set offset in header to zero.
589 data_.resize(GetOffsetArray()[idx]);
590 GetOffsetArray()[idx] = 0u;
591 }
592
593 dex_file_has_non_zero_flags_ |= class_def_has_non_zero_flags_;
594
595 if (idx == num_classdefs_ - 1) {
596 if (dex_file_has_non_zero_flags_) {
597 // This was the last class def and we have generated non-zero hiddenapi
598 // flags. Update total size in the header.
599 *GetSizeField() = GetCurrentDataSize();
600 } else {
601 // This was the last class def and we have not generated any non-zero
602 // hiddenapi flags. Clear all the data.
603 data_.clear();
604 }
605 }
606 }
607
608 // Append flags at the end of the data struct. This should be called
609 // between BeginClassDef and EndClassDef in the order of appearance of
610 // fields/methods in the class data stream.
David Brazdil90faceb2018-12-14 14:36:15 +0000611 void WriteFlags(const ApiList& flags) {
612 uint32_t dex_flags = flags.GetDexFlags();
613 EncodeUnsignedLeb128(&data_, dex_flags);
614 class_def_has_non_zero_flags_ |= (dex_flags != 0u);
David Brazdil20c765f2018-10-27 21:45:15 +0000615 }
616
617 // Return backing data, assuming that all flags have been written.
618 const std::vector<uint8_t>& GetData() const {
619 CHECK_EQ(next_class_def_idx_, num_classdefs_) << "Incomplete data";
620 return data_;
621 }
622
623 private:
624 // Returns pointer to the size field in the header of this dex section.
625 uint32_t* GetSizeField() {
626 // Assume malloc() aligns allocated memory to at least uint32_t.
627 CHECK(IsAligned<sizeof(uint32_t)>(data_.data()));
628 return reinterpret_cast<uint32_t*>(data_.data());
629 }
630
631 // Returns pointer to array of offsets (indexed by class def indices) in the
632 // header of this dex section.
633 uint32_t* GetOffsetArray() { return &GetSizeField()[1]; }
634 uint32_t GetCurrentDataSize() const { return data_.size(); }
635
636 // Number of class defs in this dex file.
637 const uint32_t num_classdefs_;
638
639 // Next expected class def index.
640 uint32_t next_class_def_idx_;
641
642 // Whether non-zero flags have been encountered for this class def.
643 bool class_def_has_non_zero_flags_;
644
645 // Whether any non-zero flags have been encountered for this dex file.
646 bool dex_file_has_non_zero_flags_;
647
648 // Vector containing the data of the built data structure.
649 std::vector<uint8_t> data_;
650};
651
652// Edits a dex file, inserting a new HiddenapiClassData section.
653class DexFileEditor final {
654 public:
655 DexFileEditor(const DexFile& old_dex, const std::vector<uint8_t>& hiddenapi_class_data)
656 : old_dex_(old_dex),
657 hiddenapi_class_data_(hiddenapi_class_data),
658 loaded_dex_header_(nullptr),
659 loaded_dex_maplist_(nullptr) {}
660
661 // Copies dex file into a backing data vector, appends the given HiddenapiClassData
662 // and updates the MapList.
663 void Encode() {
664 // We do not support non-standard dex encodings, e.g. compact dex.
665 CHECK(old_dex_.IsStandardDexFile());
666
667 // If there are no data to append, copy the old dex file and return.
668 if (hiddenapi_class_data_.empty()) {
669 AllocateMemory(old_dex_.Size());
670 Append(old_dex_.Begin(), old_dex_.Size(), /* update_header= */ false);
671 return;
672 }
673
674 // Find the old MapList, find its size.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800675 const dex::MapList* old_map = old_dex_.GetMapList();
David Brazdil20c765f2018-10-27 21:45:15 +0000676 CHECK_LT(old_map->size_, std::numeric_limits<uint32_t>::max());
677
678 // Compute the size of the new dex file. We append the HiddenapiClassData,
679 // one MapItem and possibly some padding to align the new MapList.
680 CHECK(IsAligned<kMapListAlignment>(old_dex_.Size()))
681 << "End of input dex file is not 4-byte aligned, possibly because its MapList is not "
682 << "at the end of the file.";
683 size_t size_delta =
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800684 RoundUp(hiddenapi_class_data_.size(), kMapListAlignment) + sizeof(dex::MapItem);
David Brazdil20c765f2018-10-27 21:45:15 +0000685 size_t new_size = old_dex_.Size() + size_delta;
686 AllocateMemory(new_size);
687
688 // Copy the old dex file into the backing data vector. Load the copied
689 // dex file to obtain pointers to its header and MapList.
690 Append(old_dex_.Begin(), old_dex_.Size(), /* update_header= */ false);
691 ReloadDex(/* verify= */ false);
692
693 // Truncate the new dex file before the old MapList. This assumes that
694 // the MapList is the last entry in the dex file. This is currently true
695 // for our tooling.
696 // TODO: Implement the general case by zero-ing the old MapList (turning
697 // it into padding.
698 RemoveOldMapList();
699
700 // Append HiddenapiClassData.
701 size_t payload_offset = AppendHiddenapiClassData();
702
703 // Wrute new MapList with an entry for HiddenapiClassData.
704 CreateMapListWithNewItem(payload_offset);
705
706 // Check that the pre-computed size matches the actual size.
707 CHECK_EQ(offset_, new_size);
708
709 // Reload to all data structures.
710 ReloadDex(/* verify= */ false);
711
712 // Update the dex checksum.
713 UpdateChecksum();
714
715 // Run DexFileVerifier on the new dex file as a CHECK.
716 ReloadDex(/* verify= */ true);
717 }
718
719 // Writes the edited dex file into a file.
720 void WriteTo(const std::string& path) {
721 CHECK(!data_.empty());
722 std::ofstream ofs(path.c_str(), std::ofstream::out | std::ofstream::binary);
723 ofs.write(reinterpret_cast<const char*>(data_.data()), data_.size());
724 ofs.flush();
725 CHECK(ofs.good());
726 ofs.close();
727 }
728
729 private:
730 static constexpr size_t kMapListAlignment = 4u;
731 static constexpr size_t kHiddenapiClassDataAlignment = 4u;
732
733 void ReloadDex(bool verify) {
734 std::string error_msg;
735 DexFileLoader loader;
736 loaded_dex_ = loader.Open(
737 data_.data(),
738 data_.size(),
739 "test_location",
740 old_dex_.GetLocationChecksum(),
741 /* oat_dex_file= */ nullptr,
742 /* verify= */ verify,
743 /* verify_checksum= */ verify,
744 &error_msg);
745 if (loaded_dex_.get() == nullptr) {
746 LOG(FATAL) << "Failed to load edited dex file: " << error_msg;
747 UNREACHABLE();
748 }
749
750 // Load the location of header and map list before we start editing the file.
751 loaded_dex_header_ = const_cast<DexFile::Header*>(&loaded_dex_->GetHeader());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800752 loaded_dex_maplist_ = const_cast<dex::MapList*>(loaded_dex_->GetMapList());
David Brazdil20c765f2018-10-27 21:45:15 +0000753 }
754
755 DexFile::Header& GetHeader() const {
756 CHECK(loaded_dex_header_ != nullptr);
757 return *loaded_dex_header_;
758 }
759
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800760 dex::MapList& GetMapList() const {
David Brazdil20c765f2018-10-27 21:45:15 +0000761 CHECK(loaded_dex_maplist_ != nullptr);
762 return *loaded_dex_maplist_;
763 }
764
765 void AllocateMemory(size_t total_size) {
766 data_.clear();
767 data_.resize(total_size);
768 CHECK(IsAligned<kMapListAlignment>(data_.data()));
769 CHECK(IsAligned<kHiddenapiClassDataAlignment>(data_.data()));
770 offset_ = 0;
771 }
772
773 uint8_t* GetCurrentDataPtr() {
774 return data_.data() + offset_;
775 }
776
777 void UpdateDataSize(off_t delta, bool update_header) {
778 offset_ += delta;
779 if (update_header) {
780 DexFile::Header& header = GetHeader();
781 header.file_size_ += delta;
782 header.data_size_ += delta;
783 }
784 }
785
786 template<typename T>
787 T* Append(const T* src, size_t len, bool update_header = true) {
788 CHECK_LE(offset_ + len, data_.size());
789 uint8_t* dst = GetCurrentDataPtr();
790 memcpy(dst, src, len);
791 UpdateDataSize(len, update_header);
792 return reinterpret_cast<T*>(dst);
793 }
794
795 void InsertPadding(size_t alignment) {
796 size_t len = RoundUp(offset_, alignment) - offset_;
797 std::vector<uint8_t> padding(len, 0);
798 Append(padding.data(), padding.size());
799 }
800
801 void RemoveOldMapList() {
802 size_t map_size = GetMapList().Size();
803 uint8_t* map_start = reinterpret_cast<uint8_t*>(&GetMapList());
804 CHECK_EQ(map_start + map_size, GetCurrentDataPtr()) << "MapList not at the end of dex file";
805 UpdateDataSize(-static_cast<off_t>(map_size), /* update_header= */ true);
806 CHECK_EQ(map_start, GetCurrentDataPtr());
807 loaded_dex_maplist_ = nullptr; // do not use this map list any more
808 }
809
810 void CreateMapListWithNewItem(size_t payload_offset) {
811 InsertPadding(/* alignment= */ kMapListAlignment);
812
813 size_t new_map_offset = offset_;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800814 dex::MapList* map = Append(old_dex_.GetMapList(), old_dex_.GetMapList()->Size());
David Brazdil20c765f2018-10-27 21:45:15 +0000815
816 // Check last map entry is a pointer to itself.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800817 dex::MapItem& old_item = map->list_[map->size_ - 1];
David Brazdil20c765f2018-10-27 21:45:15 +0000818 CHECK(old_item.type_ == DexFile::kDexTypeMapList);
819 CHECK_EQ(old_item.size_, 1u);
820 CHECK_EQ(old_item.offset_, GetHeader().map_off_);
821
822 // Create a new MapItem entry with new MapList details.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800823 dex::MapItem new_item;
David Brazdil20c765f2018-10-27 21:45:15 +0000824 new_item.type_ = old_item.type_;
David Brazdil976b01f2018-11-12 10:46:14 +0000825 new_item.unused_ = 0u; // initialize to ensure dex output is deterministic (b/119308882)
David Brazdil20c765f2018-10-27 21:45:15 +0000826 new_item.size_ = old_item.size_;
827 new_item.offset_ = new_map_offset;
828
829 // Update pointer in the header.
830 GetHeader().map_off_ = new_map_offset;
831
832 // Append a new MapItem and return its pointer.
833 map->size_++;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800834 Append(&new_item, sizeof(dex::MapItem));
David Brazdil20c765f2018-10-27 21:45:15 +0000835
836 // Change penultimate entry to point to metadata.
837 old_item.type_ = DexFile::kDexTypeHiddenapiClassData;
838 old_item.size_ = 1u; // there is only one section
839 old_item.offset_ = payload_offset;
840 }
841
842 size_t AppendHiddenapiClassData() {
843 size_t payload_offset = offset_;
844 CHECK_EQ(kMapListAlignment, kHiddenapiClassDataAlignment);
845 CHECK(IsAligned<kHiddenapiClassDataAlignment>(payload_offset))
846 << "Should not need to align the section, previous data was already aligned";
847 Append(hiddenapi_class_data_.data(), hiddenapi_class_data_.size());
848 return payload_offset;
849 }
850
851 void UpdateChecksum() {
852 GetHeader().checksum_ = loaded_dex_->CalculateChecksum();
853 }
854
855 const DexFile& old_dex_;
856 const std::vector<uint8_t>& hiddenapi_class_data_;
857
858 std::vector<uint8_t> data_;
859 size_t offset_;
860
861 std::unique_ptr<const DexFile> loaded_dex_;
862 DexFile::Header* loaded_dex_header_;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800863 dex::MapList* loaded_dex_maplist_;
David Brazdil20c765f2018-10-27 21:45:15 +0000864};
865
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100866class HiddenApi final {
David Brazdil003e64b2018-06-27 13:20:52 +0100867 public:
David Brazdil91690d32018-11-04 18:07:23 +0000868 HiddenApi() : force_assign_all_(true) {}
David Brazdil003e64b2018-06-27 13:20:52 +0100869
870 void Run(int argc, char** argv) {
871 switch (ParseArgs(argc, argv)) {
872 case Command::kEncode:
873 EncodeAccessFlags();
874 break;
David Brazdil0b6de0c2018-06-28 11:56:41 +0100875 case Command::kList:
876 ListApi();
877 break;
David Brazdil003e64b2018-06-27 13:20:52 +0100878 }
879 }
880
881 private:
882 enum class Command {
David Brazdil003e64b2018-06-27 13:20:52 +0100883 kEncode,
David Brazdil0b6de0c2018-06-28 11:56:41 +0100884 kList,
David Brazdil003e64b2018-06-27 13:20:52 +0100885 };
886
887 Command ParseArgs(int argc, char** argv) {
888 // Skip over the binary's path.
889 argv++;
890 argc--;
891
892 if (argc > 0) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000893 const char* raw_command = argv[0];
894 const std::string_view command(raw_command);
David Brazdil003e64b2018-06-27 13:20:52 +0100895 if (command == "encode") {
896 for (int i = 1; i < argc; ++i) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000897 const char* raw_option = argv[i];
898 const std::string_view option(raw_option);
899 if (StartsWith(option, "--input-dex=")) {
900 boot_dex_paths_.push_back(std::string(option.substr(strlen("--input-dex="))));
901 } else if (StartsWith(option, "--output-dex=")) {
902 output_dex_paths_.push_back(std::string(option.substr(strlen("--output-dex="))));
903 } else if (StartsWith(option, "--api-flags=")) {
904 api_flags_path_ = std::string(option.substr(strlen("--api-flags=")));
David Brazdil91690d32018-11-04 18:07:23 +0000905 } else if (option == "--no-force-assign-all") {
906 force_assign_all_ = false;
David Brazdil003e64b2018-06-27 13:20:52 +0100907 } else {
Vladimir Markoe5125562019-02-06 17:38:26 +0000908 Usage("Unknown argument '%s'", raw_option);
David Brazdil003e64b2018-06-27 13:20:52 +0100909 }
910 }
911 return Command::kEncode;
David Brazdil0b6de0c2018-06-28 11:56:41 +0100912 } else if (command == "list") {
913 for (int i = 1; i < argc; ++i) {
Vladimir Markoe5125562019-02-06 17:38:26 +0000914 const char* raw_option = argv[i];
915 const std::string_view option(raw_option);
916 if (StartsWith(option, "--boot-dex=")) {
917 boot_dex_paths_.push_back(std::string(option.substr(strlen("--boot-dex="))));
918 } else if (StartsWith(option, "--public-stub-classpath=")) {
David Brazdil62a4bcf2018-12-13 17:00:06 +0000919 stub_classpaths_.push_back(std::make_pair(
Vladimir Markoe5125562019-02-06 17:38:26 +0000920 std::string(option.substr(strlen("--public-stub-classpath="))),
Andrei Onea370a0642019-03-01 17:48:27 +0000921 ApiStubs::Kind::kPublicApi));
922 } else if (StartsWith(option, "--system-stub-classpath=")) {
923 stub_classpaths_.push_back(std::make_pair(
924 std::string(option.substr(strlen("--system-stub-classpath="))),
925 ApiStubs::Kind::kSystemApi));
926 } else if (StartsWith(option, "--test-stub-classpath=")) {
927 stub_classpaths_.push_back(std::make_pair(
928 std::string(option.substr(strlen("--test-stub-classpath="))),
929 ApiStubs::Kind::kTestApi));
Vladimir Markoe5125562019-02-06 17:38:26 +0000930 } else if (StartsWith(option, "--core-platform-stub-classpath=")) {
David Brazdil90faceb2018-12-14 14:36:15 +0000931 stub_classpaths_.push_back(std::make_pair(
Vladimir Markoe5125562019-02-06 17:38:26 +0000932 std::string(option.substr(strlen("--core-platform-stub-classpath="))),
Andrei Onea370a0642019-03-01 17:48:27 +0000933 ApiStubs::Kind::kCorePlatformApi));
Vladimir Markoe5125562019-02-06 17:38:26 +0000934 } else if (StartsWith(option, "--out-api-flags=")) {
935 api_flags_path_ = std::string(option.substr(strlen("--out-api-flags=")));
David Brazdil0b6de0c2018-06-28 11:56:41 +0100936 } else {
Vladimir Markoe5125562019-02-06 17:38:26 +0000937 Usage("Unknown argument '%s'", raw_option);
David Brazdil0b6de0c2018-06-28 11:56:41 +0100938 }
939 }
940 return Command::kList;
David Brazdil003e64b2018-06-27 13:20:52 +0100941 } else {
Vladimir Markoe5125562019-02-06 17:38:26 +0000942 Usage("Unknown command '%s'", raw_command);
David Brazdil003e64b2018-06-27 13:20:52 +0100943 }
944 } else {
945 Usage("No command specified");
946 }
947 }
948
949 void EncodeAccessFlags() {
950 if (boot_dex_paths_.empty()) {
David Brazdil20c765f2018-10-27 21:45:15 +0000951 Usage("No input DEX files specified");
952 } else if (output_dex_paths_.size() != boot_dex_paths_.size()) {
953 Usage("Number of input DEX files does not match number of output DEX files");
David Brazdil003e64b2018-06-27 13:20:52 +0100954 }
955
956 // Load dex signatures.
David Brazdil62a4bcf2018-12-13 17:00:06 +0000957 std::map<std::string, ApiList> api_list = OpenApiFile(api_flags_path_);
David Brazdil003e64b2018-06-27 13:20:52 +0100958
David Brazdil20c765f2018-10-27 21:45:15 +0000959 // Iterate over input dex files and insert HiddenapiClassData sections.
960 for (size_t i = 0; i < boot_dex_paths_.size(); ++i) {
961 const std::string& input_path = boot_dex_paths_[i];
962 const std::string& output_path = output_dex_paths_[i];
David Brazdil003e64b2018-06-27 13:20:52 +0100963
Paul Duffin496b9b42021-05-17 12:23:01 +0100964 ClassPath boot_classpath({ input_path },
965 /* open_writable= */ false,
966 /* ignore_empty= */ false);
David Brazdil20c765f2018-10-27 21:45:15 +0000967 std::vector<const DexFile*> input_dex_files = boot_classpath.GetDexFiles();
968 CHECK_EQ(input_dex_files.size(), 1u);
969 const DexFile& input_dex = *input_dex_files[0];
David Brazdil003e64b2018-06-27 13:20:52 +0100970
David Brazdil20c765f2018-10-27 21:45:15 +0000971 HiddenapiClassDataBuilder builder(input_dex);
David Brazdil91690d32018-11-04 18:07:23 +0000972 boot_classpath.ForEachDexClass([&](const DexClass& boot_class) {
David Brazdil20c765f2018-10-27 21:45:15 +0000973 builder.BeginClassDef(boot_class.GetClassDefIndex());
974 if (boot_class.GetData() != nullptr) {
975 auto fn_shared = [&](const DexMember& boot_member) {
David Brazdil20c765f2018-10-27 21:45:15 +0000976 auto it = api_list.find(boot_member.GetApiEntry());
David Brazdil91690d32018-11-04 18:07:23 +0000977 bool api_list_found = (it != api_list.end());
David Brazdil3482caa2019-01-23 18:24:06 +0000978 CHECK(!force_assign_all_ || api_list_found)
979 << "Could not find hiddenapi flags for dex entry: " << boot_member.GetApiEntry();
Andrei Oneafc12a6c2020-07-29 19:52:34 +0100980 builder.WriteFlags(api_list_found ? it->second : ApiList::Sdk());
David Brazdil20c765f2018-10-27 21:45:15 +0000981 };
982 auto fn_field = [&](const ClassAccessor::Field& boot_field) {
983 fn_shared(DexMember(boot_class, boot_field));
984 };
985 auto fn_method = [&](const ClassAccessor::Method& boot_method) {
986 fn_shared(DexMember(boot_class, boot_method));
987 };
988 boot_class.VisitFieldsAndMethods(fn_field, fn_field, fn_method, fn_method);
989 }
990 builder.EndClassDef(boot_class.GetClassDefIndex());
991 });
992
993 DexFileEditor dex_editor(input_dex, builder.GetData());
994 dex_editor.Encode();
995 dex_editor.WriteTo(output_path);
996 }
David Brazdil003e64b2018-06-27 13:20:52 +0100997 }
998
David Brazdil62a4bcf2018-12-13 17:00:06 +0000999 std::map<std::string, ApiList> OpenApiFile(const std::string& path) {
David Brazdil91690d32018-11-04 18:07:23 +00001000 CHECK(!path.empty());
David Brazdil003e64b2018-06-27 13:20:52 +01001001 std::ifstream api_file(path, std::ifstream::in);
1002 CHECK(!api_file.fail()) << "Unable to open file '" << path << "' " << strerror(errno);
1003
David Brazdil62a4bcf2018-12-13 17:00:06 +00001004 std::map<std::string, ApiList> api_flag_map;
David Brazdil91690d32018-11-04 18:07:23 +00001005
David Brazdil90faceb2018-12-14 14:36:15 +00001006 size_t line_number = 1;
Mathew Inwoodb62f6f12019-01-07 14:02:52 +00001007 for (std::string line; std::getline(api_file, line); line_number++) {
Andrei Onea370a0642019-03-01 17:48:27 +00001008 // Every line contains a comma separated list with the signature as the
1009 // first element and the api flags as the rest
David Brazdil91690d32018-11-04 18:07:23 +00001010 std::vector<std::string> values = android::base::Split(line, ",");
David Brazdil90faceb2018-12-14 14:36:15 +00001011 CHECK_GT(values.size(), 1u) << path << ":" << line_number
1012 << ": No flags found: " << line << kErrorHelp;
1013
David Brazdil91690d32018-11-04 18:07:23 +00001014 const std::string& signature = values[0];
Andrei Onea370a0642019-03-01 17:48:27 +00001015
David Brazdil90faceb2018-12-14 14:36:15 +00001016 CHECK(api_flag_map.find(signature) == api_flag_map.end()) << path << ":" << line_number
1017 << ": Duplicate entry: " << signature << kErrorHelp;
Mathew Inwoodb62f6f12019-01-07 14:02:52 +00001018
David Brazdil90faceb2018-12-14 14:36:15 +00001019 ApiList membership;
Andrei Onea370a0642019-03-01 17:48:27 +00001020
David Brazdil90faceb2018-12-14 14:36:15 +00001021 bool success = ApiList::FromNames(values.begin() + 1, values.end(), &membership);
1022 CHECK(success) << path << ":" << line_number
1023 << ": Some flags were not recognized: " << line << kErrorHelp;
1024 CHECK(membership.IsValid()) << path << ":" << line_number
1025 << ": Invalid combination of flags: " << line << kErrorHelp;
David Brazdil91690d32018-11-04 18:07:23 +00001026
1027 api_flag_map.emplace(signature, membership);
David Brazdil003e64b2018-06-27 13:20:52 +01001028 }
David Brazdil91690d32018-11-04 18:07:23 +00001029
David Brazdil003e64b2018-06-27 13:20:52 +01001030 api_file.close();
David Brazdil91690d32018-11-04 18:07:23 +00001031 return api_flag_map;
David Brazdil003e64b2018-06-27 13:20:52 +01001032 }
David Brazdil2b9c35b2018-01-12 15:44:43 +00001033
David Brazdil0b6de0c2018-06-28 11:56:41 +01001034 void ListApi() {
1035 if (boot_dex_paths_.empty()) {
1036 Usage("No boot DEX files specified");
David Brazdil345c0ed2018-08-03 10:26:44 +01001037 } else if (stub_classpaths_.empty()) {
David Brazdil0b6de0c2018-06-28 11:56:41 +01001038 Usage("No stub DEX files specified");
David Brazdil62a4bcf2018-12-13 17:00:06 +00001039 } else if (api_flags_path_.empty()) {
1040 Usage("No output path specified");
David Brazdil0b6de0c2018-06-28 11:56:41 +01001041 }
1042
1043 // Complete list of boot class path members. The associated boolean states
1044 // whether it is public (true) or private (false).
Andrei Onea370a0642019-03-01 17:48:27 +00001045 std::map<std::string, std::set<std::string_view>> boot_members;
David Brazdil0b6de0c2018-06-28 11:56:41 +01001046
1047 // Deduplicate errors before printing them.
1048 std::set<std::string> unresolved;
1049
1050 // Open all dex files.
Paul Duffin496b9b42021-05-17 12:23:01 +01001051 ClassPath boot_classpath(boot_dex_paths_,
1052 /* open_writable= */ false,
1053 /* ignore_empty= */ false);
David Brazdil345c0ed2018-08-03 10:26:44 +01001054 Hierarchy boot_hierarchy(boot_classpath);
David Brazdil0b6de0c2018-06-28 11:56:41 +01001055
1056 // Mark all boot dex members private.
David Brazdil62a4bcf2018-12-13 17:00:06 +00001057 boot_classpath.ForEachDexMember([&](const DexMember& boot_member) {
Andrei Onea370a0642019-03-01 17:48:27 +00001058 boot_members[boot_member.GetApiEntry()] = {};
David Brazdil0b6de0c2018-06-28 11:56:41 +01001059 });
1060
1061 // Resolve each SDK dex member against the framework and mark it white.
David Brazdil62a4bcf2018-12-13 17:00:06 +00001062 for (const auto& cp_entry : stub_classpaths_) {
Paul Duffin496b9b42021-05-17 12:23:01 +01001063 // Ignore any empty stub jars as it just means that they provide no APIs
1064 // for the current kind, e.g. framework-sdkextensions does not provide
1065 // any public APIs.
David Brazdil62a4bcf2018-12-13 17:00:06 +00001066 ClassPath stub_classpath(android::base::Split(cp_entry.first, ":"),
Paul Duffin496b9b42021-05-17 12:23:01 +01001067 /* open_writable= */ false,
1068 /* ignore_empty= */ true);
David Brazdil345c0ed2018-08-03 10:26:44 +01001069 Hierarchy stub_hierarchy(stub_classpath);
Andrei Onea370a0642019-03-01 17:48:27 +00001070 const ApiStubs::Kind stub_api = cp_entry.second;
David Brazdil62a4bcf2018-12-13 17:00:06 +00001071
David Brazdil345c0ed2018-08-03 10:26:44 +01001072 stub_classpath.ForEachDexMember(
David Brazdil62a4bcf2018-12-13 17:00:06 +00001073 [&](const DexMember& stub_member) {
David Brazdil345c0ed2018-08-03 10:26:44 +01001074 if (!stub_hierarchy.IsMemberVisible(stub_member)) {
1075 // Typically fake constructors and inner-class `this` fields.
1076 return;
1077 }
1078 bool resolved = boot_hierarchy.ForEachResolvableMember(
1079 stub_member,
David Brazdil62a4bcf2018-12-13 17:00:06 +00001080 [&](const DexMember& boot_member) {
David Brazdil345c0ed2018-08-03 10:26:44 +01001081 std::string entry = boot_member.GetApiEntry();
1082 auto it = boot_members.find(entry);
1083 CHECK(it != boot_members.end());
Andrei Onea370a0642019-03-01 17:48:27 +00001084 it->second.insert(ApiStubs::ToString(stub_api));
David Brazdil345c0ed2018-08-03 10:26:44 +01001085 });
1086 if (!resolved) {
1087 unresolved.insert(stub_member.GetApiEntry());
1088 }
1089 });
1090 }
David Brazdil0b6de0c2018-06-28 11:56:41 +01001091
1092 // Print errors.
1093 for (const std::string& str : unresolved) {
1094 LOG(WARNING) << "unresolved: " << str;
1095 }
1096
1097 // Write into public/private API files.
David Brazdil62a4bcf2018-12-13 17:00:06 +00001098 std::ofstream file_flags(api_flags_path_.c_str());
1099 for (const auto& entry : boot_members) {
Andrei Onea370a0642019-03-01 17:48:27 +00001100 if (entry.second.empty()) {
David Brazdil62a4bcf2018-12-13 17:00:06 +00001101 file_flags << entry.first << std::endl;
David Brazdil90faceb2018-12-14 14:36:15 +00001102 } else {
Andrei Onea370a0642019-03-01 17:48:27 +00001103 file_flags << entry.first << ",";
1104 file_flags << android::base::Join(entry.second, ",") << std::endl;
David Brazdil0b6de0c2018-06-28 11:56:41 +01001105 }
1106 }
David Brazdil62a4bcf2018-12-13 17:00:06 +00001107 file_flags.close();
David Brazdil0b6de0c2018-06-28 11:56:41 +01001108 }
1109
David Brazdil91690d32018-11-04 18:07:23 +00001110 // Whether to check that all dex entries have been assigned flags.
1111 // Defaults to true.
1112 bool force_assign_all_;
1113
David Brazdil2b9c35b2018-01-12 15:44:43 +00001114 // Paths to DEX files which should be processed.
David Brazdil003e64b2018-06-27 13:20:52 +01001115 std::vector<std::string> boot_dex_paths_;
David Brazdil345c0ed2018-08-03 10:26:44 +01001116
David Brazdil20c765f2018-10-27 21:45:15 +00001117 // Output paths where modified DEX files should be written.
1118 std::vector<std::string> output_dex_paths_;
1119
David Brazdil345c0ed2018-08-03 10:26:44 +01001120 // Set of public API stub classpaths. Each classpath is formed by a list
1121 // of DEX/APK files in the order they appear on the classpath.
Andrei Onea370a0642019-03-01 17:48:27 +00001122 std::vector<std::pair<std::string, ApiStubs::Kind>> stub_classpaths_;
David Brazdil2b9c35b2018-01-12 15:44:43 +00001123
David Brazdil62a4bcf2018-12-13 17:00:06 +00001124 // Path to CSV file containing the list of API members and their flags.
1125 // This could be both an input and output path.
1126 std::string api_flags_path_;
David Brazdil2b9c35b2018-01-12 15:44:43 +00001127};
1128
David Brazdil62a4bcf2018-12-13 17:00:06 +00001129} // namespace hiddenapi
David Brazdil2b9c35b2018-01-12 15:44:43 +00001130} // namespace art
1131
1132int main(int argc, char** argv) {
David Brazdil62a4bcf2018-12-13 17:00:06 +00001133 art::hiddenapi::original_argc = argc;
1134 art::hiddenapi::original_argv = argv;
David Brazdil003e64b2018-06-27 13:20:52 +01001135 android::base::InitLogging(argv);
1136 art::MemMap::Init();
David Brazdil62a4bcf2018-12-13 17:00:06 +00001137 art::hiddenapi::HiddenApi().Run(argc, argv);
David Brazdil003e64b2018-06-27 13:20:52 +01001138 return EXIT_SUCCESS;
David Brazdil2b9c35b2018-01-12 15:44:43 +00001139}