blob: 43b8fe94f4d1f9cecb7d6d67982b2995b3512651 [file] [log] [blame]
Alex Light9c20a142016-08-23 15:05:12 -07001/* 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
Alex Lightca97ada2018-02-02 09:25:31 -080032#include <stddef.h>
33#include <sys/types.h>
34
Alex Lighta01de592016-11-15 10:43:06 -080035#include <unordered_map>
36#include <unordered_set>
37
Alex Light9c20a142016-08-23 15:05:12 -070038#include "transform.h"
39
Alex Lighta01de592016-11-15 10:43:06 -080040#include "art_method.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010041#include "base/array_ref.h"
Alex Light9c20a142016-08-23 15:05:12 -070042#include "class_linker.h"
David Sehr9e734c72018-01-04 17:56:19 -080043#include "dex/dex_file.h"
44#include "dex/dex_file_types.h"
David Sehr0225f8e2018-01-31 08:52:24 +000045#include "dex/utf.h"
Alex Light6ac57502017-01-19 15:05:06 -080046#include "events-inl.h"
Alex Lightca97ada2018-02-02 09:25:31 -080047#include "fault_handler.h"
Alex Light9c20a142016-08-23 15:05:12 -070048#include "gc_root-inl.h"
49#include "globals.h"
50#include "jni_env_ext-inl.h"
Alex Light6a656312017-03-29 17:18:00 -070051#include "jvalue.h"
Alex Light9c20a142016-08-23 15:05:12 -070052#include "jvmti.h"
53#include "linear_alloc.h"
54#include "mem_map.h"
55#include "mirror/array.h"
56#include "mirror/class-inl.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080057#include "mirror/class_ext.h"
Alex Light9c20a142016-08-23 15:05:12 -070058#include "mirror/class_loader-inl.h"
59#include "mirror/string-inl.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010060#include "oat_file.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070061#include "scoped_thread_state_change-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080062#include "stack.h"
Alex Light9c20a142016-08-23 15:05:12 -070063#include "thread_list.h"
Alex Light6ac57502017-01-19 15:05:06 -080064#include "ti_redefine.h"
Alex Light9c20a142016-08-23 15:05:12 -070065#include "transform.h"
Alex Light9c20a142016-08-23 15:05:12 -070066#include "utils/dex_cache_arrays_layout-inl.h"
67
68namespace openjdkjvmti {
69
Alex Lightca97ada2018-02-02 09:25:31 -080070// A FaultHandler that will deal with initializing ClassDefinitions when they are actually needed.
71class TransformationFaultHandler FINAL : public art::FaultHandler {
72 public:
73 explicit TransformationFaultHandler(art::FaultManager* manager)
74 : art::FaultHandler(manager),
75 uninitialized_class_definitions_lock_("JVMTI Initialized class definitions lock",
76 art::LockLevel::kSignalHandlingLock),
77 class_definition_initialized_cond_("JVMTI Initialized class definitions condition",
78 uninitialized_class_definitions_lock_) {
79 manager->AddHandler(this, /* generated_code */ false);
80 }
81
82 ~TransformationFaultHandler() {
83 art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
84 uninitialized_class_definitions_.clear();
85 }
86
87 bool Action(int sig, siginfo_t* siginfo, void* context ATTRIBUTE_UNUSED) OVERRIDE {
88 DCHECK_EQ(sig, SIGSEGV);
89 art::Thread* self = art::Thread::Current();
90 if (UNLIKELY(uninitialized_class_definitions_lock_.IsExclusiveHeld(self))) {
91 if (self != nullptr) {
92 LOG(FATAL) << "Recursive call into Transformation fault handler!";
93 UNREACHABLE();
94 } else {
95 LOG(ERROR) << "Possible deadlock due to recursive signal delivery of segv.";
96 }
97 }
98 uintptr_t ptr = reinterpret_cast<uintptr_t>(siginfo->si_addr);
99 ArtClassDefinition* res = nullptr;
100
101 {
102 // NB Technically using a mutex and condition variables here is non-posix compliant but
103 // everything should be fine since both glibc and bionic implementations of mutexs and
104 // condition variables work fine so long as the thread was not interrupted during a
105 // lock/unlock (which it wasn't) on all architectures we care about.
106 art::MutexLock mu(self, uninitialized_class_definitions_lock_);
107 auto it = std::find_if(uninitialized_class_definitions_.begin(),
108 uninitialized_class_definitions_.end(),
109 [&](const auto op) { return op->ContainsAddress(ptr); });
110 if (it != uninitialized_class_definitions_.end()) {
111 res = *it;
112 // Remove the class definition.
113 uninitialized_class_definitions_.erase(it);
114 // Put it in the initializing list
115 initializing_class_definitions_.push_back(res);
116 } else {
117 // Wait for the ptr to be initialized (if it is currently initializing).
118 while (DefinitionIsInitializing(ptr)) {
119 WaitForClassInitializationToFinish();
120 }
121 // Return true (continue with user code) if we find that the definition has been
122 // initialized. Return false (continue on to next signal handler) if the definition is not
123 // initialized or found.
124 return std::find_if(initialized_class_definitions_.begin(),
125 initialized_class_definitions_.end(),
126 [&](const auto op) { return op->ContainsAddress(ptr); }) !=
Alex Light12ee56b2018-02-12 13:00:34 -0800127 initialized_class_definitions_.end();
Alex Lightca97ada2018-02-02 09:25:31 -0800128 }
129 }
130
Alex Lightfe2a39d2018-02-05 11:08:08 -0800131 if (LIKELY(self != nullptr)) {
132 CHECK_EQ(self->GetState(), art::ThreadState::kNative)
133 << "Transformation fault handler occurred outside of native mode";
134 }
135
Alex Lightca97ada2018-02-02 09:25:31 -0800136 VLOG(signals) << "Lazy initialization of dex file for transformation of " << res->GetName()
137 << " during SEGV";
138 res->InitializeMemory();
139
140 {
141 art::MutexLock mu(self, uninitialized_class_definitions_lock_);
142 // Move to initialized state and notify waiters.
143 initializing_class_definitions_.erase(std::find(initializing_class_definitions_.begin(),
144 initializing_class_definitions_.end(),
145 res));
146 initialized_class_definitions_.push_back(res);
147 class_definition_initialized_cond_.Broadcast(self);
148 }
149
150 return true;
151 }
152
153 void RemoveDefinition(ArtClassDefinition* def) REQUIRES(!uninitialized_class_definitions_lock_) {
154 art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
155 auto it = std::find(uninitialized_class_definitions_.begin(),
156 uninitialized_class_definitions_.end(),
157 def);
158 if (it != uninitialized_class_definitions_.end()) {
159 uninitialized_class_definitions_.erase(it);
160 return;
161 }
162 while (std::find(initializing_class_definitions_.begin(),
163 initializing_class_definitions_.end(),
164 def) != initializing_class_definitions_.end()) {
165 WaitForClassInitializationToFinish();
166 }
167 it = std::find(initialized_class_definitions_.begin(),
168 initialized_class_definitions_.end(),
169 def);
170 CHECK(it != initialized_class_definitions_.end()) << "Could not find class definition for "
171 << def->GetName();
172 initialized_class_definitions_.erase(it);
173 }
174
175 void AddArtDefinition(ArtClassDefinition* def) REQUIRES(!uninitialized_class_definitions_lock_) {
176 DCHECK(def->IsLazyDefinition());
177 art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
178 uninitialized_class_definitions_.push_back(def);
179 }
180
181 private:
182 bool DefinitionIsInitializing(uintptr_t ptr) REQUIRES(uninitialized_class_definitions_lock_) {
183 return std::find_if(initializing_class_definitions_.begin(),
184 initializing_class_definitions_.end(),
185 [&](const auto op) { return op->ContainsAddress(ptr); }) !=
186 initializing_class_definitions_.end();
187 }
188
189 void WaitForClassInitializationToFinish() REQUIRES(uninitialized_class_definitions_lock_) {
190 class_definition_initialized_cond_.Wait(art::Thread::Current());
191 }
192
193 art::Mutex uninitialized_class_definitions_lock_ ACQUIRED_BEFORE(art::Locks::abort_lock_);
194 art::ConditionVariable class_definition_initialized_cond_
195 GUARDED_BY(uninitialized_class_definitions_lock_);
196
197 // A list of the class definitions that have a non-readable map.
198 std::vector<ArtClassDefinition*> uninitialized_class_definitions_
199 GUARDED_BY(uninitialized_class_definitions_lock_);
200
201 // A list of class definitions that are currently undergoing unquickening. Threads should wait
202 // until the definition is no longer in this before returning.
203 std::vector<ArtClassDefinition*> initializing_class_definitions_
204 GUARDED_BY(uninitialized_class_definitions_lock_);
205
206 // A list of class definitions that are already unquickened. Threads should immediately return if
207 // it is here.
208 std::vector<ArtClassDefinition*> initialized_class_definitions_
209 GUARDED_BY(uninitialized_class_definitions_lock_);
210};
211
212static TransformationFaultHandler* gTransformFaultHandler = nullptr;
213
214void Transformer::Setup() {
215 // Although we create this the fault handler is actually owned by the 'art::fault_manager' which
216 // will take care of destroying it.
217 if (art::MemMap::kCanReplaceMapping && ArtClassDefinition::kEnableOnDemandDexDequicken) {
218 gTransformFaultHandler = new TransformationFaultHandler(&art::fault_manager);
219 }
220}
221
222// Simple helper to add and remove the class definition from the fault handler.
223class ScopedDefinitionHandler {
224 public:
225 explicit ScopedDefinitionHandler(ArtClassDefinition* def)
226 : def_(def), is_lazy_(def_->IsLazyDefinition()) {
227 if (is_lazy_) {
228 gTransformFaultHandler->AddArtDefinition(def_);
229 }
230 }
231
232 ~ScopedDefinitionHandler() {
233 if (is_lazy_) {
234 gTransformFaultHandler->RemoveDefinition(def_);
235 }
236 }
237
238 private:
239 ArtClassDefinition* def_;
240 bool is_lazy_;
241};
242
Alex Light64e4c142018-01-30 13:46:37 -0800243// Initialize templates.
244template
245void Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
246 EventHandler* event_handler, art::Thread* self, /*in-out*/ArtClassDefinition* def);
247template
248void Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
249 EventHandler* event_handler, art::Thread* self, /*in-out*/ArtClassDefinition* def);
250
251template<ArtJvmtiEvent kEvent>
252void Transformer::TransformSingleClassDirect(EventHandler* event_handler,
253 art::Thread* self,
254 /*in-out*/ArtClassDefinition* def) {
255 static_assert(kEvent == ArtJvmtiEvent::kClassFileLoadHookNonRetransformable ||
256 kEvent == ArtJvmtiEvent::kClassFileLoadHookRetransformable,
257 "bad event type");
Alex Lightfe2a39d2018-02-05 11:08:08 -0800258 // We don't want to do transitions between calling the event and setting the new data so change to
259 // native state early. This also avoids any problems that the FaultHandler might have in
260 // determining if an access to the dex_data is from generated code or not.
261 art::ScopedThreadStateChange stsc(self, art::ThreadState::kNative);
Alex Lightca97ada2018-02-02 09:25:31 -0800262 ScopedDefinitionHandler handler(def);
Alex Light64e4c142018-01-30 13:46:37 -0800263 jint new_len = -1;
264 unsigned char* new_data = nullptr;
265 art::ArrayRef<const unsigned char> dex_data = def->GetDexData();
266 event_handler->DispatchEvent<kEvent>(
267 self,
268 static_cast<JNIEnv*>(self->GetJniEnv()),
269 def->GetClass(),
270 def->GetLoader(),
271 def->GetName().c_str(),
272 def->GetProtectionDomain(),
273 static_cast<jint>(dex_data.size()),
274 dex_data.data(),
275 /*out*/&new_len,
276 /*out*/&new_data);
277 def->SetNewDexData(new_len, new_data);
278}
279
Alex Light6ac57502017-01-19 15:05:06 -0800280jvmtiError Transformer::RetransformClassesDirect(
Andreas Gampede19eb92017-02-24 16:21:18 -0800281 EventHandler* event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800282 art::Thread* self,
283 /*in-out*/std::vector<ArtClassDefinition>* definitions) {
284 for (ArtClassDefinition& def : *definitions) {
Alex Light64e4c142018-01-30 13:46:37 -0800285 TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(event_handler,
286 self,
287 &def);
Alex Light6ac57502017-01-19 15:05:06 -0800288 }
289 return OK;
290}
291
292jvmtiError Transformer::RetransformClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800293 EventHandler* event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800294 art::Runtime* runtime,
295 art::Thread* self,
296 jint class_count,
297 const jclass* classes,
298 /*out*/std::string* error_msg) {
299 if (env == nullptr) {
300 *error_msg = "env was null!";
301 return ERR(INVALID_ENVIRONMENT);
302 } else if (class_count < 0) {
303 *error_msg = "class_count was less then 0";
304 return ERR(ILLEGAL_ARGUMENT);
305 } else if (class_count == 0) {
306 // We don't actually need to do anything. Just return OK.
307 return OK;
308 } else if (classes == nullptr) {
309 *error_msg = "null classes!";
310 return ERR(NULL_POINTER);
311 }
312 // A holder that will Deallocate all the class bytes buffers on destruction.
313 std::vector<ArtClassDefinition> definitions;
314 jvmtiError res = OK;
315 for (jint i = 0; i < class_count; i++) {
Alex Lightce6ee702017-03-06 15:46:43 -0800316 jboolean is_modifiable = JNI_FALSE;
317 res = env->IsModifiableClass(classes[i], &is_modifiable);
318 if (res != OK) {
319 return res;
320 } else if (!is_modifiable) {
321 return ERR(UNMODIFIABLE_CLASS);
322 }
Alex Light6ac57502017-01-19 15:05:06 -0800323 ArtClassDefinition def;
Alex Light64e4c142018-01-30 13:46:37 -0800324 res = def.Init(self, classes[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800325 if (res != OK) {
326 return res;
327 }
328 definitions.push_back(std::move(def));
329 }
Alex Light64e4c142018-01-30 13:46:37 -0800330 res = RetransformClassesDirect(event_handler, self, &definitions);
Alex Light6ac57502017-01-19 15:05:06 -0800331 if (res != OK) {
332 return res;
333 }
334 return Redefiner::RedefineClassesDirect(env, runtime, self, definitions, error_msg);
335}
336
337// TODO Move this somewhere else, ti_class?
Alex Light1e07ca62016-12-02 11:40:56 -0800338jvmtiError GetClassLocation(ArtJvmTiEnv* env, jclass klass, /*out*/std::string* location) {
339 JNIEnv* jni_env = nullptr;
340 jint ret = env->art_vm->GetEnv(reinterpret_cast<void**>(&jni_env), JNI_VERSION_1_1);
341 if (ret != JNI_OK) {
342 // TODO Different error might be better?
343 return ERR(INTERNAL);
344 }
345 art::ScopedObjectAccess soa(jni_env);
346 art::StackHandleScope<1> hs(art::Thread::Current());
347 art::Handle<art::mirror::Class> hs_klass(hs.NewHandle(soa.Decode<art::mirror::Class>(klass)));
348 const art::DexFile& dex = hs_klass->GetDexFile();
349 *location = dex.GetLocation();
350 return OK;
351}
352
Alex Light9c20a142016-08-23 15:05:12 -0700353} // namespace openjdkjvmti