blob: 2bed1d5b2d0b6c58dae03382b4cf368d0c0cc000 [file] [log] [blame]
Calin Juravle87e2cb62017-06-13 21:48:45 -07001/*
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 "class_loader_context.h"
18
19#include "base/dchecked_vector.h"
20#include "base/stl_util.h"
21#include "class_linker.h"
22#include "dex_file.h"
23#include "oat_file_assistant.h"
24#include "runtime.h"
25#include "scoped_thread_state_change-inl.h"
26#include "thread.h"
27
28namespace art {
29
30static constexpr char kPathClassLoaderString[] = "PCL";
31static constexpr char kDelegateLastClassLoaderString[] = "DLC";
32static constexpr char kClassLoaderOpeningMark = '[';
33static constexpr char kClassLoaderClosingMark = ']';
Calin Juravle7b0648a2017-07-07 18:40:50 -070034static constexpr char kClassLoaderSeparator = ';';
35static constexpr char kClasspathSeparator = ':';
36static constexpr char kDexFileChecksumSeparator = '*';
Calin Juravle87e2cb62017-06-13 21:48:45 -070037
38ClassLoaderContext::ClassLoaderContext()
39 : special_shared_library_(false),
40 dex_files_open_attempted_(false),
41 dex_files_open_result_(false) {}
42
43std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
44 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
45 if (result->Parse(spec)) {
46 return result;
47 } else {
48 return nullptr;
49 }
50}
51
Calin Juravle7b0648a2017-07-07 18:40:50 -070052// The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
53// The checksum part of the format is expected only if parse_cheksums is true.
Calin Juravle87e2cb62017-06-13 21:48:45 -070054bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
Calin Juravle7b0648a2017-07-07 18:40:50 -070055 ClassLoaderType class_loader_type,
56 bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -070057 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
58 size_t type_str_size = strlen(class_loader_type_str);
59
60 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
61
62 // Check the opening and closing markers.
63 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
64 return false;
65 }
66 if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
67 return false;
68 }
69
70 // At this point we know the format is ok; continue and extract the classpath.
71 // Note that class loaders with an empty class path are allowed.
72 std::string classpath = class_loader_spec.substr(type_str_size + 1,
73 class_loader_spec.length() - type_str_size - 2);
74
75 class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -070076
77 if (!parse_checksums) {
78 Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
79 } else {
80 std::vector<std::string> classpath_elements;
81 Split(classpath, kClasspathSeparator, &classpath_elements);
82 for (const std::string& element : classpath_elements) {
83 std::vector<std::string> dex_file_with_checksum;
84 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
85 if (dex_file_with_checksum.size() != 2) {
86 return false;
87 }
88 uint32_t checksum = 0;
89 if (!ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
90 return false;
91 }
92 class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
93 class_loader_chain_.back().checksums.push_back(checksum);
94 }
95 }
Calin Juravle87e2cb62017-06-13 21:48:45 -070096
97 return true;
98}
99
100// Extracts the class loader type from the given spec.
101// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
102// recognized.
103ClassLoaderContext::ClassLoaderType
104ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
105 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
106 for (const ClassLoaderType& type : kValidTypes) {
107 const char* type_str = GetClassLoaderTypeName(type);
108 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
109 return type;
110 }
111 }
112 return kInvalidClassLoader;
113}
114
115// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
116// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
117// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700118bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700119 if (spec.empty()) {
Calin Juravle7b0648a2017-07-07 18:40:50 -0700120 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700121 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700122
Calin Juravle87e2cb62017-06-13 21:48:45 -0700123 // Stop early if we detect the special shared library, which may be passed as the classpath
124 // for dex2oat when we want to skip the shared libraries check.
125 if (spec == OatFile::kSpecialSharedLibrary) {
126 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
127 special_shared_library_ = true;
128 return true;
129 }
130
131 std::vector<std::string> class_loaders;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700132 Split(spec, kClassLoaderSeparator, &class_loaders);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700133
134 for (const std::string& class_loader : class_loaders) {
135 ClassLoaderType type = ExtractClassLoaderType(class_loader);
136 if (type == kInvalidClassLoader) {
137 LOG(ERROR) << "Invalid class loader type: " << class_loader;
138 return false;
139 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700140 if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700141 LOG(ERROR) << "Invalid class loader spec: " << class_loader;
142 return false;
143 }
144 }
145 return true;
146}
147
148// Opens requested class path files and appends them to opened_dex_files. If the dex files have
149// been stripped, this opens them from their oat files (which get added to opened_oat_files).
150bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
151 CHECK(!dex_files_open_attempted_) << "OpenDexFiles should not be called twice";
152
153 dex_files_open_attempted_ = true;
154 // Assume we can open all dex files. If not, we will set this to false as we go.
155 dex_files_open_result_ = true;
156
157 if (special_shared_library_) {
158 // Nothing to open if the context is a special shared library.
159 return true;
160 }
161
162 // Note that we try to open all dex files even if some fail.
163 // We may get resource-only apks which we cannot load.
164 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
165 // no dex files. So that we can distinguish the real failures...
166 for (ClassLoaderInfo& info : class_loader_chain_) {
167 for (const std::string& cp_elem : info.classpath) {
168 // If path is relative, append it to the provided base directory.
169 std::string location = cp_elem;
170 if (location[0] != '/') {
171 location = classpath_dir + '/' + location;
172 }
173 std::string error_msg;
174 // When opening the dex files from the context we expect their checksum to match their
175 // contents. So pass true to verify_checksum.
176 if (!DexFile::Open(location.c_str(),
177 location.c_str(),
178 /*verify_checksum*/ true,
179 &error_msg,
180 &info.opened_dex_files)) {
181 // If we fail to open the dex file because it's been stripped, try to open the dex file
182 // from its corresponding oat file.
183 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
184 // (for example, if the pre-build is only quicken and we want to re-compile it
185 // speed-profile).
186 // TODO(calin): Use the vdex directly instead of going through the oat file.
187 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
188 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
189 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
190 if (oat_file != nullptr &&
191 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
192 info.opened_oat_files.push_back(std::move(oat_file));
193 info.opened_dex_files.insert(info.opened_dex_files.end(),
194 std::make_move_iterator(oat_dex_files.begin()),
195 std::make_move_iterator(oat_dex_files.end()));
196 } else {
197 LOG(WARNING) << "Could not open dex files from location: " << location;
198 dex_files_open_result_ = false;
199 }
200 }
201 }
202 }
203
204 return dex_files_open_result_;
205}
206
207bool ClassLoaderContext::RemoveLocationsFromClassPaths(
208 const dchecked_vector<std::string>& locations) {
209 CHECK(!dex_files_open_attempted_)
210 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
211
212 std::set<std::string> canonical_locations;
213 for (const std::string& location : locations) {
214 canonical_locations.insert(DexFile::GetDexCanonicalLocation(location.c_str()));
215 }
216 bool removed_locations = false;
217 for (ClassLoaderInfo& info : class_loader_chain_) {
218 size_t initial_size = info.classpath.size();
219 auto kept_it = std::remove_if(
220 info.classpath.begin(),
221 info.classpath.end(),
222 [canonical_locations](const std::string& location) {
223 return ContainsElement(canonical_locations,
224 DexFile::GetDexCanonicalLocation(location.c_str()));
225 });
226 info.classpath.erase(kept_it, info.classpath.end());
227 if (initial_size != info.classpath.size()) {
228 removed_locations = true;
229 }
230 }
231 return removed_locations;
232}
233
234std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir) const {
235 CheckDexFilesOpened("EncodeContextForOatFile");
236 if (special_shared_library_) {
237 return OatFile::kSpecialSharedLibrary;
238 }
239
240 if (class_loader_chain_.empty()) {
241 return "";
242 }
243
Calin Juravle7b0648a2017-07-07 18:40:50 -0700244 std::ostringstream out;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700245
Calin Juravle7b0648a2017-07-07 18:40:50 -0700246 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
247 const ClassLoaderInfo& info = class_loader_chain_[i];
248 if (i > 0) {
249 out << kClassLoaderSeparator;
250 }
251 out << GetClassLoaderTypeName(info.type);
252 out << kClassLoaderOpeningMark;
253 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
254 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
255 const std::string& location = dex_file->GetLocation();
256 if (k > 0) {
257 out << kClasspathSeparator;
258 }
259 // Find paths that were relative and convert them back from absolute.
260 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
261 out << location.substr(base_dir.length() + 1).c_str();
262 } else {
263 out << dex_file->GetLocation().c_str();
264 }
265 out << kDexFileChecksumSeparator;
266 out << dex_file->GetLocationChecksum();
267 }
268 out << kClassLoaderClosingMark;
269 }
270 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700271}
272
273jobject ClassLoaderContext::CreateClassLoader(
274 const std::vector<const DexFile*>& compilation_sources) const {
275 CheckDexFilesOpened("CreateClassLoader");
276
277 Thread* self = Thread::Current();
278 ScopedObjectAccess soa(self);
279
280 std::vector<const DexFile*> class_path_files;
281
282 // TODO(calin): Transition period: assume we only have a classloader until
283 // the oat file assistant implements the full class loader check.
284 if (!class_loader_chain_.empty()) {
285 CHECK_EQ(1u, class_loader_chain_.size());
286 CHECK_EQ(kPathClassLoader, class_loader_chain_[0].type);
287 class_path_files = MakeNonOwningPointerVector(class_loader_chain_[0].opened_dex_files);
288 }
289
290 // Classpath: first the class-path given; then the dex files we'll compile.
291 // Thus we'll resolve the class-path first.
292 class_path_files.insert(class_path_files.end(),
293 compilation_sources.begin(),
294 compilation_sources.end());
295
296 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
297 return class_linker->CreatePathClassLoader(self, class_path_files);
298}
299
300std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
301 CheckDexFilesOpened("FlattenOpenedDexFiles");
302
303 std::vector<const DexFile*> result;
304 for (const ClassLoaderInfo& info : class_loader_chain_) {
305 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
306 result.push_back(dex_file.get());
307 }
308 }
309 return result;
310}
311
312const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
313 switch (type) {
314 case kPathClassLoader: return kPathClassLoaderString;
315 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
316 default:
317 LOG(FATAL) << "Invalid class loader type " << type;
318 UNREACHABLE();
319 }
320}
321
322void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
323 CHECK(dex_files_open_attempted_)
324 << "Dex files were not successfully opened before the call to " << calling_method
325 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
326}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700327
328bool ClassLoaderContext::DecodePathClassLoaderContextFromOatFileKey(
329 const std::string& context_spec,
330 std::vector<std::string>* out_classpath,
331 std::vector<uint32_t>* out_checksums,
332 bool* out_is_special_shared_library) {
333 ClassLoaderContext context;
334 if (!context.Parse(context_spec, /*parse_checksums*/ true)) {
335 LOG(ERROR) << "Invalid class loader context: " << context_spec;
336 return false;
337 }
338
339 *out_is_special_shared_library = context.special_shared_library_;
340 if (context.special_shared_library_) {
341 return true;
342 }
343
344 if (context.class_loader_chain_.empty()) {
345 return true;
346 }
347
348 // TODO(calin): assert that we only have a PathClassLoader until the logic for
349 // checking the context covers all case.
350 CHECK_EQ(1u, context.class_loader_chain_.size());
351 const ClassLoaderInfo& info = context.class_loader_chain_[0];
352 CHECK_EQ(kPathClassLoader, info.type);
353 DCHECK_EQ(info.classpath.size(), info.checksums.size());
354
355 *out_classpath = info.classpath;
356 *out_checksums = info.checksums;
357 return true;
358}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700359} // namespace art
360