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 
72 namespace openjdkjvmti {
73 
74 // A FaultHandler that will deal with initializing ClassDefinitions when they are actually needed.
75 class TransformationFaultHandler final : public art::FaultHandler {
76  public:
TransformationFaultHandler(art::FaultManager * manager)77   explicit TransformationFaultHandler(art::FaultManager* manager)
78       : art::FaultHandler(manager),
79         uninitialized_class_definitions_lock_("JVMTI Initialized class definitions lock",
80                                               art::LockLevel::kSignalHandlingLock),
81         class_definition_initialized_cond_("JVMTI Initialized class definitions condition",
82                                            uninitialized_class_definitions_lock_) {
83     manager->AddHandler(this, /* generated_code= */ false);
84   }
85 
~TransformationFaultHandler()86   ~TransformationFaultHandler() {
87     art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
88     uninitialized_class_definitions_.clear();
89   }
90 
Action(int sig,siginfo_t * siginfo,void * context ATTRIBUTE_UNUSED)91   bool Action(int sig, siginfo_t* siginfo, void* context ATTRIBUTE_UNUSED) override {
92     DCHECK_EQ(sig, SIGSEGV);
93     art::Thread* self = art::Thread::Current();
94     uintptr_t ptr = reinterpret_cast<uintptr_t>(siginfo->si_addr);
95     if (UNLIKELY(uninitialized_class_definitions_lock_.IsExclusiveHeld(self))) {
96       // It's possible this is just some other unrelated segv that should be
97       // handled separately, continue to later handlers. This is likely due to
98       // running out of memory somewhere along the FixedUpDexFile pipeline and
99       // is likely unrecoverable. By returning false here though we will get a
100       // better, more accurate, stack-trace later that points to the actual
101       // issue.
102       LOG(WARNING) << "Recursive SEGV occurred during Transformation dequickening at 0x" << std::hex
103                    << ptr;
104       return false;
105     }
106     ArtClassDefinition* res = nullptr;
107 
108     {
109       // NB Technically using a mutex and condition variables here is non-posix compliant but
110       // everything should be fine since both glibc and bionic implementations of mutexs and
111       // condition variables work fine so long as the thread was not interrupted during a
112       // lock/unlock (which it wasn't) on all architectures we care about.
113       art::MutexLock mu(self, uninitialized_class_definitions_lock_);
114       auto it = std::find_if(uninitialized_class_definitions_.begin(),
115                              uninitialized_class_definitions_.end(),
116                              [&](const auto op) { return op->ContainsAddress(ptr); });
117       if (it != uninitialized_class_definitions_.end()) {
118         res = *it;
119         // Remove the class definition.
120         uninitialized_class_definitions_.erase(it);
121         // Put it in the initializing list
122         initializing_class_definitions_.push_back(res);
123       } else {
124         // Wait for the ptr to be initialized (if it is currently initializing).
125         while (DefinitionIsInitializing(ptr)) {
126           WaitForClassInitializationToFinish();
127         }
128         // Return true (continue with user code) if we find that the definition has been
129         // initialized. Return false (continue on to next signal handler) if the definition is not
130         // initialized or found.
131         return std::find_if(initialized_class_definitions_.begin(),
132                             initialized_class_definitions_.end(),
133                             [&](const auto op) { return op->ContainsAddress(ptr); }) !=
134             initialized_class_definitions_.end();
135       }
136     }
137 
138     if (LIKELY(self != nullptr)) {
139       CHECK_EQ(self->GetState(), art::ThreadState::kNative)
140           << "Transformation fault handler occurred outside of native mode";
141     }
142 
143     VLOG(signals) << "Lazy initialization of dex file for transformation of " << res->GetName()
144                   << " during SEGV";
145     res->InitializeMemory();
146 
147     {
148       art::MutexLock mu(self, uninitialized_class_definitions_lock_);
149       // Move to initialized state and notify waiters.
150       initializing_class_definitions_.erase(std::find(initializing_class_definitions_.begin(),
151                                                       initializing_class_definitions_.end(),
152                                                       res));
153       initialized_class_definitions_.push_back(res);
154       class_definition_initialized_cond_.Broadcast(self);
155     }
156 
157     return true;
158   }
159 
RemoveDefinition(ArtClassDefinition * def)160   void RemoveDefinition(ArtClassDefinition* def) REQUIRES(!uninitialized_class_definitions_lock_) {
161     art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
162     auto it = std::find(uninitialized_class_definitions_.begin(),
163                         uninitialized_class_definitions_.end(),
164                         def);
165     if (it != uninitialized_class_definitions_.end()) {
166       uninitialized_class_definitions_.erase(it);
167       return;
168     }
169     while (std::find(initializing_class_definitions_.begin(),
170                      initializing_class_definitions_.end(),
171                      def) != initializing_class_definitions_.end()) {
172       WaitForClassInitializationToFinish();
173     }
174     it = std::find(initialized_class_definitions_.begin(),
175                    initialized_class_definitions_.end(),
176                    def);
177     CHECK(it != initialized_class_definitions_.end()) << "Could not find class definition for "
178                                                       << def->GetName();
179     initialized_class_definitions_.erase(it);
180   }
181 
AddArtDefinition(ArtClassDefinition * def)182   void AddArtDefinition(ArtClassDefinition* def) REQUIRES(!uninitialized_class_definitions_lock_) {
183     DCHECK(def->IsLazyDefinition());
184     art::MutexLock mu(art::Thread::Current(), uninitialized_class_definitions_lock_);
185     uninitialized_class_definitions_.push_back(def);
186   }
187 
188  private:
DefinitionIsInitializing(uintptr_t ptr)189   bool DefinitionIsInitializing(uintptr_t ptr) REQUIRES(uninitialized_class_definitions_lock_) {
190     return std::find_if(initializing_class_definitions_.begin(),
191                         initializing_class_definitions_.end(),
192                         [&](const auto op) { return op->ContainsAddress(ptr); }) !=
193         initializing_class_definitions_.end();
194   }
195 
WaitForClassInitializationToFinish()196   void WaitForClassInitializationToFinish() REQUIRES(uninitialized_class_definitions_lock_) {
197     class_definition_initialized_cond_.Wait(art::Thread::Current());
198   }
199 
200   art::Mutex uninitialized_class_definitions_lock_ ACQUIRED_BEFORE(art::Locks::abort_lock_);
201   art::ConditionVariable class_definition_initialized_cond_
202       GUARDED_BY(uninitialized_class_definitions_lock_);
203 
204   // A list of the class definitions that have a non-readable map.
205   std::vector<ArtClassDefinition*> uninitialized_class_definitions_
206       GUARDED_BY(uninitialized_class_definitions_lock_);
207 
208   // A list of class definitions that are currently undergoing unquickening. Threads should wait
209   // until the definition is no longer in this before returning.
210   std::vector<ArtClassDefinition*> initializing_class_definitions_
211       GUARDED_BY(uninitialized_class_definitions_lock_);
212 
213   // A list of class definitions that are already unquickened. Threads should immediately return if
214   // it is here.
215   std::vector<ArtClassDefinition*> initialized_class_definitions_
216       GUARDED_BY(uninitialized_class_definitions_lock_);
217 };
218 
219 static TransformationFaultHandler* gTransformFaultHandler = nullptr;
220 static EventHandler* gEventHandler = nullptr;
221 
222 
Register(EventHandler * eh)223 void Transformer::Register(EventHandler* eh) {
224   // Although we create this the fault handler is actually owned by the 'art::fault_manager' which
225   // will take care of destroying it.
226   if (art::MemMap::kCanReplaceMapping && ArtClassDefinition::kEnableOnDemandDexDequicken) {
227     gTransformFaultHandler = new TransformationFaultHandler(&art::fault_manager);
228   }
229   gEventHandler = eh;
230 }
231 
232 // Simple helper to add and remove the class definition from the fault handler.
233 class ScopedDefinitionHandler {
234  public:
ScopedDefinitionHandler(ArtClassDefinition * def)235   explicit ScopedDefinitionHandler(ArtClassDefinition* def)
236       : def_(def), is_lazy_(def_->IsLazyDefinition()) {
237     if (is_lazy_) {
238       gTransformFaultHandler->AddArtDefinition(def_);
239     }
240   }
241 
~ScopedDefinitionHandler()242   ~ScopedDefinitionHandler() {
243     if (is_lazy_) {
244       gTransformFaultHandler->RemoveDefinition(def_);
245     }
246   }
247 
248  private:
249   ArtClassDefinition* def_;
250   bool is_lazy_;
251 };
252 
253 // Initialize templates.
254 template
255 void Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
256     EventHandler* event_handler, art::Thread* self, /*in-out*/ArtClassDefinition* def);
257 template
258 void Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
259     EventHandler* event_handler, art::Thread* self, /*in-out*/ArtClassDefinition* def);
260 template
261 void Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kStructuralDexFileLoadHook>(
262     EventHandler* event_handler, art::Thread* self, /*in-out*/ArtClassDefinition* def);
263 
264 template<ArtJvmtiEvent kEvent>
TransformSingleClassDirect(EventHandler * event_handler,art::Thread * self,ArtClassDefinition * def)265 void Transformer::TransformSingleClassDirect(EventHandler* event_handler,
266                                              art::Thread* self,
267                                              /*in-out*/ArtClassDefinition* def) {
268   static_assert(kEvent == ArtJvmtiEvent::kClassFileLoadHookNonRetransformable ||
269                 kEvent == ArtJvmtiEvent::kClassFileLoadHookRetransformable ||
270                 kEvent == ArtJvmtiEvent::kStructuralDexFileLoadHook,
271                 "bad event type");
272   // We don't want to do transitions between calling the event and setting the new data so change to
273   // native state early. This also avoids any problems that the FaultHandler might have in
274   // determining if an access to the dex_data is from generated code or not.
275   art::ScopedThreadStateChange stsc(self, art::ThreadState::kNative);
276   ScopedDefinitionHandler handler(def);
277   jint new_len = -1;
278   unsigned char* new_data = nullptr;
279   art::ArrayRef<const unsigned char> dex_data = def->GetDexData();
280   event_handler->DispatchEvent<kEvent>(
281       self,
282       static_cast<JNIEnv*>(self->GetJniEnv()),
283       def->GetClass(),
284       def->GetLoader(),
285       def->GetName().c_str(),
286       def->GetProtectionDomain(),
287       static_cast<jint>(dex_data.size()),
288       dex_data.data(),
289       /*out*/&new_len,
290       /*out*/&new_data);
291   def->SetNewDexData(new_len, new_data, kEvent);
292 }
293 
294 template <RedefinitionType kType>
RetransformClassesDirect(art::Thread * self,std::vector<ArtClassDefinition> * definitions)295 void Transformer::RetransformClassesDirect(
296     art::Thread* self,
297     /*in-out*/ std::vector<ArtClassDefinition>* definitions) {
298   constexpr ArtJvmtiEvent kEvent = kType == RedefinitionType::kNormal
299                                        ? ArtJvmtiEvent::kClassFileLoadHookRetransformable
300                                        : ArtJvmtiEvent::kStructuralDexFileLoadHook;
301   for (ArtClassDefinition& def : *definitions) {
302     TransformSingleClassDirect<kEvent>(gEventHandler, self, &def);
303   }
304 }
305 
306 template void Transformer::RetransformClassesDirect<RedefinitionType::kNormal>(
307       art::Thread* self, /*in-out*/std::vector<ArtClassDefinition>* definitions);
308 template void Transformer::RetransformClassesDirect<RedefinitionType::kStructural>(
309       art::Thread* self, /*in-out*/std::vector<ArtClassDefinition>* definitions);
310 
RetransformClasses(jvmtiEnv * env,jint class_count,const jclass * classes)311 jvmtiError Transformer::RetransformClasses(jvmtiEnv* env,
312                                            jint class_count,
313                                            const jclass* classes) {
314   if (class_count < 0) {
315     JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM class_count was less then 0";
316     return ERR(ILLEGAL_ARGUMENT);
317   } else if (class_count == 0) {
318     // We don't actually need to do anything. Just return OK.
319     return OK;
320   } else if (classes == nullptr) {
321     JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM null classes!";
322     return ERR(NULL_POINTER);
323   }
324   art::Thread* self = art::Thread::Current();
325   art::Runtime* runtime = art::Runtime::Current();
326   // A holder that will Deallocate all the class bytes buffers on destruction.
327   std::string error_msg;
328   std::vector<ArtClassDefinition> definitions;
329   jvmtiError res = OK;
330   for (jint i = 0; i < class_count; i++) {
331     res = Redefiner::GetClassRedefinitionError<RedefinitionType::kNormal>(classes[i], &error_msg);
332     if (res != OK) {
333       JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM " << error_msg;
334       return res;
335     }
336     ArtClassDefinition def;
337     res = def.Init(self, classes[i]);
338     if (res != OK) {
339       JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM definition init failed";
340       return res;
341     }
342     definitions.push_back(std::move(def));
343   }
344   RetransformClassesDirect<RedefinitionType::kStructural>(self, &definitions);
345   RetransformClassesDirect<RedefinitionType::kNormal>(self, &definitions);
346   RedefinitionType redef_type =
347       std::any_of(definitions.cbegin(),
348                   definitions.cend(),
349                   [](const auto& it) { return it.HasStructuralChanges(); })
350           ? RedefinitionType::kStructural
351           : RedefinitionType::kNormal;
352   res = Redefiner::RedefineClassesDirect(
353       ArtJvmTiEnv::AsArtJvmTiEnv(env), runtime, self, definitions, redef_type, &error_msg);
354   if (res != OK) {
355     JVMTI_LOG(WARNING, env) << "FAILURE TO RETRANSFORM " << error_msg;
356   }
357   return res;
358 }
359 
360 // TODO Move this somewhere else, ti_class?
GetClassLocation(ArtJvmTiEnv * env,jclass klass,std::string * location)361 jvmtiError GetClassLocation(ArtJvmTiEnv* env, jclass klass, /*out*/std::string* location) {
362   JNIEnv* jni_env = nullptr;
363   jint ret = env->art_vm->GetEnv(reinterpret_cast<void**>(&jni_env), JNI_VERSION_1_1);
364   if (ret != JNI_OK) {
365     // TODO Different error might be better?
366     return ERR(INTERNAL);
367   }
368   art::ScopedObjectAccess soa(jni_env);
369   art::StackHandleScope<1> hs(art::Thread::Current());
370   art::Handle<art::mirror::Class> hs_klass(hs.NewHandle(soa.Decode<art::mirror::Class>(klass)));
371   const art::DexFile& dex = hs_klass->GetDexFile();
372   *location = dex.GetLocation();
373   return OK;
374 }
375 
376 }  // namespace openjdkjvmti
377