1 /* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32 #include <error.h>
33 #include <stddef.h>
34 #include <sys/types.h>
35
36 #include <unordered_map>
37 #include <unordered_set>
38
39 #include "transform.h"
40
41 #include "art_method.h"
42 #include "base/array_ref.h"
43 #include "base/globals.h"
44 #include "base/logging.h"
45 #include "base/mem_map.h"
46 #include "class_linker.h"
47 #include "dex/dex_file.h"
48 #include "dex/dex_file_types.h"
49 #include "dex/utf.h"
50 #include "events-inl.h"
51 #include "events.h"
52 #include "fault_handler.h"
53 #include "gc_root-inl.h"
54 #include "handle_scope-inl.h"
55 #include "jni/jni_env_ext-inl.h"
56 #include "jvalue.h"
57 #include "jvmti.h"
58 #include "linear_alloc.h"
59 #include "mirror/array.h"
60 #include "mirror/class-inl.h"
61 #include "mirror/class_ext.h"
62 #include "mirror/class_loader-inl.h"
63 #include "mirror/string-inl.h"
64 #include "oat_file.h"
65 #include "scoped_thread_state_change-inl.h"
66 #include "stack.h"
67 #include "thread_list.h"
68 #include "ti_redefine.h"
69 #include "ti_logging.h"
70 #include "transform.h"
71 #include "utils/dex_cache_arrays_layout-inl.h"
72
73 namespace openjdkjvmti {
74
75 // A FaultHandler that will deal with initializing ClassDefinitions when they are actually needed.
76 class TransformationFaultHandler final : public art::FaultHandler {
77 public:
TransformationFaultHandler(art::FaultManager * manager)78 explicit TransformationFaultHandler(art::FaultManager* manager)
79 : art::FaultHandler(manager),
80 uninitialized_class_definitions_lock_("JVMTI Initialized class definitions lock",
81 art::LockLevel::kSignalHandlingLock),
82 class_definition_initialized_cond_("JVMTI Initialized class definitions condition",
83 uninitialized_class_definitions_lock_) {
84 manager->AddHandler(this, /* generated_code= */ false);
85 }
86
~TransformationFaultHandler()87 ~TransformationFaultHandler() {
88 art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
89 uninitialized_class_definitions_.clear();
90 }
91
Action(int sig,siginfo_t * siginfo,void * context ATTRIBUTE_UNUSED)92 bool Action(int sig, siginfo_t* siginfo, void* context ATTRIBUTE_UNUSED) override {
93 DCHECK_EQ(sig, SIGSEGV);
94 art::Thread* self = art::Thread::Current();
95 uintptr_t ptr = reinterpret_cast<uintptr_t>(siginfo->si_addr);
96 if (UNLIKELY(uninitialized_class_definitions_lock_.IsExclusiveHeld(self))) {
97 // It's possible this is just some other unrelated segv that should be
98 // handled separately, continue to later handlers. This is likely due to
99 // running out of memory somewhere along the FixedUpDexFile pipeline and
100 // is likely unrecoverable. By returning false here though we will get a
101 // better, more accurate, stack-trace later that points to the actual
102 // issue.
103 LOG(WARNING) << "Recursive SEGV occurred during Transformation dequickening at 0x" << std::hex
104 << ptr;
105 return false;
106 }
107 ArtClassDefinition* res = nullptr;
108
109 {
110 // NB Technically using a mutex and condition variables here is non-posix compliant but
111 // everything should be fine since both glibc and bionic implementations of mutexs and
112 // condition variables work fine so long as the thread was not interrupted during a
113 // lock/unlock (which it wasn't) on all architectures we care about.
114 art::MutexLock mu(self, uninitialized_class_definitions_lock_);
115 auto it = std::find_if(uninitialized_class_definitions_.begin(),
116 uninitialized_class_definitions_.end(),
117 [&](const auto op) { return op->ContainsAddress(ptr); });
118 if (it != uninitialized_class_definitions_.end()) {
119 res = *it;
120 // Remove the class definition.
121 uninitialized_class_definitions_.erase(it);
122 // Put it in the initializing list
123 initializing_class_definitions_.push_back(res);
124 } else {
125 // Wait for the ptr to be initialized (if it is currently initializing).
126 while (DefinitionIsInitializing(ptr)) {
127 WaitForClassInitializationToFinish();
128 }
129 // Return true (continue with user code) if we find that the definition has been
130 // initialized. Return false (continue on to next signal handler) if the definition is not
131 // initialized or found.
132 return std::find_if(initialized_class_definitions_.begin(),
133 initialized_class_definitions_.end(),
134 [&](const auto op) { return op->ContainsAddress(ptr); }) !=
135 initialized_class_definitions_.end();
136 }
137 }
138
139 if (LIKELY(self != nullptr)) {
140 CHECK_EQ(self->GetState(), art::ThreadState::kNative)
141 << "Transformation fault handler occurred outside of native mode";
142 }
143
144 VLOG(signals) << "Lazy initialization of dex file for transformation of " << res->GetName()
145 << " during SEGV";
146 res->InitializeMemory();
147
148 {
149 art::MutexLock mu(self, uninitialized_class_definitions_lock_);
150 // Move to initialized state and notify waiters.
151 initializing_class_definitions_.erase(std::find(initializing_class_definitions_.begin(),
152 initializing_class_definitions_.end(),
153 res));
154 initialized_class_definitions_.push_back(res);
155 class_definition_initialized_cond_.Broadcast(self);
156 }
157
158 return true;
159 }
160
RemoveDefinition(ArtClassDefinition * def)161 void RemoveDefinition(ArtClassDefinition* def) REQUIRES(!uninitialized_class_definitions_lock_) {
162 art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
163 auto it = std::find(uninitialized_class_definitions_.begin(),
164 uninitialized_class_definitions_.end(),
165 def);
166 if (it != uninitialized_class_definitions_.end()) {
167 uninitialized_class_definitions_.erase(it);
168 return;
169 }
170 while (std::find(initializing_class_definitions_.begin(),
171 initializing_class_definitions_.end(),
172 def) != initializing_class_definitions_.end()) {
173 WaitForClassInitializationToFinish();
174 }
175 it = std::find(initialized_class_definitions_.begin(),
176 initialized_class_definitions_.end(),
177 def);
178 CHECK(it != initialized_class_definitions_.end()) << "Could not find class definition for "
179 << def->GetName();
180 initialized_class_definitions_.erase(it);
181 }
182
AddArtDefinition(ArtClassDefinition * def)183 void AddArtDefinition(ArtClassDefinition* def) REQUIRES(!uninitialized_class_definitions_lock_) {
184 DCHECK(def->IsLazyDefinition());
185 art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
186 uninitialized_class_definitions_.push_back(def);
187 }
188
189 private:
DefinitionIsInitializing(uintptr_t ptr)190 bool DefinitionIsInitializing(uintptr_t ptr) REQUIRES(uninitialized_class_definitions_lock_) {
191 return std::find_if(initializing_class_definitions_.begin(),
192 initializing_class_definitions_.end(),
193 [&](const auto op) { return op->ContainsAddress(ptr); }) !=
194 initializing_class_definitions_.end();
195 }
196
WaitForClassInitializationToFinish()197 void WaitForClassInitializationToFinish() REQUIRES(uninitialized_class_definitions_lock_) {
198 class_definition_initialized_cond_.Wait(art::Thread::Current());
199 }
200
201 art::Mutex uninitialized_class_definitions_lock_ ACQUIRED_BEFORE(art::Locks::abort_lock_);
202 art::ConditionVariable class_definition_initialized_cond_
203 GUARDED_BY(uninitialized_class_definitions_lock_);
204
205 // A list of the class definitions that have a non-readable map.
206 std::vector<ArtClassDefinition*> uninitialized_class_definitions_
207 GUARDED_BY(uninitialized_class_definitions_lock_);
208
209 // A list of class definitions that are currently undergoing unquickening. Threads should wait
210 // until the definition is no longer in this before returning.
211 std::vector<ArtClassDefinition*> initializing_class_definitions_
212 GUARDED_BY(uninitialized_class_definitions_lock_);
213
214 // A list of class definitions that are already unquickened. Threads should immediately return if
215 // it is here.
216 std::vector<ArtClassDefinition*> initialized_class_definitions_
217 GUARDED_BY(uninitialized_class_definitions_lock_);
218 };
219
220 static TransformationFaultHandler* gTransformFaultHandler = nullptr;
221 static EventHandler* gEventHandler = nullptr;
222
223
Register(EventHandler * eh)224 void Transformer::Register(EventHandler* eh) {
225 // Although we create this the fault handler is actually owned by the 'art::fault_manager' which
226 // will take care of destroying it.
227 if (art::MemMap::kCanReplaceMapping && ArtClassDefinition::kEnableOnDemandDexDequicken) {
228 gTransformFaultHandler = new TransformationFaultHandler(&art::fault_manager);
229 }
230 gEventHandler = eh;
231 }
232
233 // Simple helper to add and remove the class definition from the fault handler.
234 class ScopedDefinitionHandler {
235 public:
ScopedDefinitionHandler(ArtClassDefinition * def)236 explicit ScopedDefinitionHandler(ArtClassDefinition* def)
237 : def_(def), is_lazy_(def_->IsLazyDefinition()) {
238 if (is_lazy_) {
239 gTransformFaultHandler->AddArtDefinition(def_);
240 }
241 }
242
~ScopedDefinitionHandler()243 ~ScopedDefinitionHandler() {
244 if (is_lazy_) {
245 gTransformFaultHandler->RemoveDefinition(def_);
246 }
247 }
248
249 private:
250 ArtClassDefinition* def_;
251 bool is_lazy_;
252 };
253
254 // Initialize templates.
255 template
256 void Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
257 EventHandler* event_handler, art::Thread* self, /*in-out*/ArtClassDefinition* def);
258 template
259 void Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
260 EventHandler* event_handler, art::Thread* self, /*in-out*/ArtClassDefinition* def);
261 template
262 void Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kStructuralDexFileLoadHook>(
263 EventHandler* event_handler, art::Thread* self, /*in-out*/ArtClassDefinition* def);
264
265 template<ArtJvmtiEvent kEvent>
TransformSingleClassDirect(EventHandler * event_handler,art::Thread * self,ArtClassDefinition * def)266 void Transformer::TransformSingleClassDirect(EventHandler* event_handler,
267 art::Thread* self,
268 /*in-out*/ArtClassDefinition* def) {
269 static_assert(kEvent == ArtJvmtiEvent::kClassFileLoadHookNonRetransformable ||
270 kEvent == ArtJvmtiEvent::kClassFileLoadHookRetransformable ||
271 kEvent == ArtJvmtiEvent::kStructuralDexFileLoadHook,
272 "bad event type");
273 // We don't want to do transitions between calling the event and setting the new data so change to
274 // native state early. This also avoids any problems that the FaultHandler might have in
275 // determining if an access to the dex_data is from generated code or not.
276 art::ScopedThreadStateChange stsc(self, art::ThreadState::kNative);
277 ScopedDefinitionHandler handler(def);
278 jint new_len = -1;
279 unsigned char* new_data = nullptr;
280 art::ArrayRef<const unsigned char> dex_data = def->GetDexData();
281 event_handler->DispatchEvent<kEvent>(
282 self,
283 static_cast<JNIEnv*>(self->GetJniEnv()),
284 def->GetClass(),
285 def->GetLoader(),
286 def->GetName().c_str(),
287 def->GetProtectionDomain(),
288 static_cast<jint>(dex_data.size()),
289 dex_data.data(),
290 /*out*/&new_len,
291 /*out*/&new_data);
292 def->SetNewDexData(new_len, new_data, kEvent);
293 }
294
295 template <RedefinitionType kType>
RetransformClassesDirect(art::Thread * self,std::vector<ArtClassDefinition> * definitions)296 void Transformer::RetransformClassesDirect(
297 art::Thread* self,
298 /*in-out*/ std::vector<ArtClassDefinition>* definitions) {
299 constexpr ArtJvmtiEvent kEvent = kType == RedefinitionType::kNormal
300 ? ArtJvmtiEvent::kClassFileLoadHookRetransformable
301 : ArtJvmtiEvent::kStructuralDexFileLoadHook;
302 for (ArtClassDefinition& def : *definitions) {
303 TransformSingleClassDirect<kEvent>(gEventHandler, self, &def);
304 }
305 }
306
307 template void Transformer::RetransformClassesDirect<RedefinitionType::kNormal>(
308 art::Thread* self, /*in-out*/std::vector<ArtClassDefinition>* definitions);
309 template void Transformer::RetransformClassesDirect<RedefinitionType::kStructural>(
310 art::Thread* self, /*in-out*/std::vector<ArtClassDefinition>* definitions);
311
RetransformClasses(jvmtiEnv * env,jint class_count,const jclass * classes)312 jvmtiError Transformer::RetransformClasses(jvmtiEnv* env,
313 jint class_count,
314 const jclass* classes) {
315 if (class_count < 0) {
316 JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM class_count was less then 0";
317 return ERR(ILLEGAL_ARGUMENT);
318 } else if (class_count == 0) {
319 // We don't actually need to do anything. Just return OK.
320 return OK;
321 } else if (classes == nullptr) {
322 JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM null classes!";
323 return ERR(NULL_POINTER);
324 }
325 art::Thread* self = art::Thread::Current();
326 art::Runtime* runtime = art::Runtime::Current();
327 // A holder that will Deallocate all the class bytes buffers on destruction.
328 std::string error_msg;
329 std::vector<ArtClassDefinition> definitions;
330 jvmtiError res = OK;
331 for (jint i = 0; i < class_count; i++) {
332 res = Redefiner::GetClassRedefinitionError<RedefinitionType::kNormal>(classes[i], &error_msg);
333 if (res != OK) {
334 JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM " << error_msg;
335 return res;
336 }
337 ArtClassDefinition def;
338 res = def.Init(self, classes[i]);
339 if (res != OK) {
340 JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM definition init failed";
341 return res;
342 }
343 definitions.push_back(std::move(def));
344 }
345 RetransformClassesDirect<RedefinitionType::kStructural>(self, &definitions);
346 RetransformClassesDirect<RedefinitionType::kNormal>(self, &definitions);
347 RedefinitionType redef_type =
348 std::any_of(definitions.cbegin(),
349 definitions.cend(),
350 [](const auto& it) { return it.HasStructuralChanges(); })
351 ? RedefinitionType::kStructural
352 : RedefinitionType::kNormal;
353 res = Redefiner::RedefineClassesDirect(
354 ArtJvmTiEnv::AsArtJvmTiEnv(env), runtime, self, definitions, redef_type, &error_msg);
355 if (res != OK) {
356 JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM " << error_msg;
357 }
358 return res;
359 }
360
361 // TODO Move this somewhere else, ti_class?
GetClassLocation(ArtJvmTiEnv * env,jclass klass,std::string * location)362 jvmtiError GetClassLocation(ArtJvmTiEnv* env, jclass klass, /*out*/std::string* location) {
363 JNIEnv* jni_env = nullptr;
364 jint ret = env->art_vm->GetEnv(reinterpret_cast<void**>(&jni_env), JNI_VERSION_1_1);
365 if (ret != JNI_OK) {
366 // TODO Different error might be better?
367 return ERR(INTERNAL);
368 }
369 art::ScopedObjectAccess soa(jni_env);
370 art::StackHandleScope<1> hs(art::Thread::Current());
371 art::Handle<art::mirror::Class> hs_klass(hs.NewHandle(soa.Decode<art::mirror::Class>(klass)));
372 const art::DexFile& dex = hs_klass->GetDexFile();
373 *location = dex.GetLocation();
374 return OK;
375 }
376
377 } // namespace openjdkjvmti
378