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 "ti_class_definition.h"
33 
34 #include "base/array_slice.h"
35 #include "base/logging.h"
36 #include "class_linker-inl.h"
37 #include "class_root-inl.h"
38 #include "dex/dex_file.h"
39 #include "fixed_up_dex_file.h"
40 #include "handle.h"
41 #include "handle_scope-inl.h"
42 #include "mirror/class-inl.h"
43 #include "mirror/class_ext-inl.h"
44 #include "mirror/object-inl.h"
45 #include "reflection.h"
46 #include "thread.h"
47 
48 namespace openjdkjvmti {
49 
InitializeMemory() const50 void ArtClassDefinition::InitializeMemory() const {
51   DCHECK(art::MemMap::kCanReplaceMapping);
52   VLOG(signals) << "Initializing de-quickened memory for dex file of " << name_;
53   CHECK(dex_data_mmap_.IsValid());
54   CHECK(temp_mmap_.IsValid());
55   CHECK_EQ(dex_data_mmap_.GetProtect(), PROT_NONE);
56   CHECK_EQ(temp_mmap_.GetProtect(), PROT_READ | PROT_WRITE);
57 
58   std::string desc = std::string("L") + name_ + ";";
59   std::unique_ptr<FixedUpDexFile>
60       fixed_dex_file(FixedUpDexFile::Create(*initial_dex_file_unquickened_, desc.c_str()));
61   CHECK(fixed_dex_file.get() != nullptr);
62   CHECK_LE(fixed_dex_file->Size(), temp_mmap_.Size());
63   CHECK_EQ(temp_mmap_.Size(), dex_data_mmap_.Size());
64   // Copy the data to the temp mmap.
65   memcpy(temp_mmap_.Begin(), fixed_dex_file->Begin(), fixed_dex_file->Size());
66 
67   // Move the mmap atomically.
68   art::MemMap source;
69   source.swap(temp_mmap_);
70   std::string error;
71   CHECK(dex_data_mmap_.ReplaceWith(&source, &error)) << "Failed to replace mmap for "
72                                                      << name_ << " because " << error;
73   CHECK(dex_data_mmap_.Protect(PROT_READ));
74 }
75 
IsModified() const76 bool ArtClassDefinition::IsModified() const {
77   // RedefineClasses calls always are 'modified' since they need to change the current_dex_file of
78   // the class.
79   if (redefined_) {
80     return true;
81   }
82 
83   // Check to see if any change has taken place.
84   if (current_dex_file_.data() == dex_data_.data()) {
85     // no change at all.
86     return false;
87   }
88 
89   // The dex_data_ was never touched by the agents.
90   if (dex_data_mmap_.IsValid() && dex_data_mmap_.GetProtect() == PROT_NONE) {
91     if (current_dex_file_.data() == dex_data_mmap_.Begin()) {
92       // the dex_data_ looks like it changed (not equal to current_dex_file_) but we never
93       // initialized the dex_data_mmap_. This means the new_dex_data was filled in without looking
94       // at the initial dex_data_.
95       return true;
96     } else if (dex_data_.data() == dex_data_mmap_.Begin()) {
97       // The dex file used to have modifications but they were not added again.
98       return true;
99     } else {
100       // It's not clear what happened. It's possible that the agent got the current dex file data
101       // from some other source so we need to initialize everything to see if it is the same.
102       VLOG(signals) << "Lazy dex file for " << name_ << " was never touched but the dex_data_ is "
103                     << "changed! Need to initialize the memory to see if anything changed";
104       InitializeMemory();
105     }
106   }
107 
108   // We can definitely read current_dex_file_ and dex_file_ without causing page faults.
109 
110   // Check if the dex file we want to set is the same as the current one.
111   // Unfortunately we need to do this check even if no modifications have been done since it could
112   // be that agents were removed in the mean-time so we still have a different dex file. The dex
113   // checksum means this is likely to be fairly fast.
114   return current_dex_file_.size() != dex_data_.size() ||
115       memcmp(current_dex_file_.data(), dex_data_.data(), current_dex_file_.size()) != 0;
116 }
117 
InitCommon(art::Thread * self,jclass klass)118 jvmtiError ArtClassDefinition::InitCommon(art::Thread* self, jclass klass) {
119   art::ScopedObjectAccess soa(self);
120   art::ObjPtr<art::mirror::Class> m_klass(soa.Decode<art::mirror::Class>(klass));
121   if (m_klass.IsNull()) {
122     return ERR(INVALID_CLASS);
123   }
124   initialized_ = true;
125   klass_ = klass;
126   loader_ = soa.AddLocalReference<jobject>(m_klass->GetClassLoader());
127   std::string descriptor_store;
128   std::string descriptor(m_klass->GetDescriptor(&descriptor_store));
129   name_ = descriptor.substr(1, descriptor.size() - 2);
130   // Android doesn't really have protection domains.
131   protection_domain_ = nullptr;
132   return OK;
133 }
134 
DequickenDexFile(const art::DexFile * dex_file,const char * descriptor,std::vector<unsigned char> * dex_data)135 static void DequickenDexFile(const art::DexFile* dex_file,
136                              const char* descriptor,
137                              /*out*/std::vector<unsigned char>* dex_data)
138     REQUIRES_SHARED(art::Locks::mutator_lock_) {
139   std::unique_ptr<FixedUpDexFile> fixed_dex_file(
140       FixedUpDexFile::Create(*dex_file, descriptor));
141   dex_data->resize(fixed_dex_file->Size());
142   memcpy(dex_data->data(), fixed_dex_file->Begin(), fixed_dex_file->Size());
143 }
144 
145 // Gets the data surrounding the given class.
GetDexDataForRetransformation(art::Handle<art::mirror::Class> klass,std::vector<unsigned char> * dex_data)146 static void GetDexDataForRetransformation(art::Handle<art::mirror::Class> klass,
147                                           /*out*/std::vector<unsigned char>* dex_data)
148     REQUIRES_SHARED(art::Locks::mutator_lock_) {
149   art::StackHandleScope<3> hs(art::Thread::Current());
150   art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->GetExtData()));
151   const art::DexFile* dex_file = nullptr;
152   if (!ext.IsNull()) {
153     art::Handle<art::mirror::Object> orig_dex(hs.NewHandle(ext->GetOriginalDexFile()));
154     if (!orig_dex.IsNull()) {
155       if (orig_dex->IsArrayInstance()) {
156         DCHECK(orig_dex->GetClass()->GetComponentType()->IsPrimitiveByte());
157         art::Handle<art::mirror::ByteArray> orig_dex_bytes(hs.NewHandle(orig_dex->AsByteArray()));
158         dex_data->resize(orig_dex_bytes->GetLength());
159         memcpy(dex_data->data(), orig_dex_bytes->GetData(), dex_data->size());
160         return;
161       } else if (orig_dex->IsDexCache()) {
162         dex_file = orig_dex->AsDexCache()->GetDexFile();
163       } else {
164         DCHECK(orig_dex->GetClass()->DescriptorEquals("Ljava/lang/Long;"))
165             << "Expected java/lang/Long but found object of type "
166             << orig_dex->GetClass()->PrettyClass();
167         art::ObjPtr<art::mirror::Class> prim_long_class(
168             art::GetClassRoot(art::ClassRoot::kPrimitiveLong));
169         art::JValue val;
170         if (!art::UnboxPrimitiveForResult(orig_dex.Get(), prim_long_class, &val)) {
171           // This should never happen.
172           LOG(FATAL) << "Unable to unbox a primitive long value!";
173         }
174         dex_file = reinterpret_cast<const art::DexFile*>(static_cast<uintptr_t>(val.GetJ()));
175       }
176     }
177   }
178   if (dex_file == nullptr) {
179     dex_file = &klass->GetDexFile();
180   }
181   std::string storage;
182   DequickenDexFile(dex_file, klass->GetDescriptor(&storage), dex_data);
183 }
184 
DexNeedsDequickening(art::Handle<art::mirror::Class> klass,bool * from_class_ext)185 static bool DexNeedsDequickening(art::Handle<art::mirror::Class> klass,
186                                  /*out*/ bool* from_class_ext)
187     REQUIRES_SHARED(art::Locks::mutator_lock_) {
188   art::ObjPtr<art::mirror::ClassExt> ext(klass->GetExtData());
189   if (ext.IsNull()) {
190     // We don't seem to have ever been redefined so be conservative and say we need de-quickening.
191     *from_class_ext = false;
192     return true;
193   }
194   art::ObjPtr<art::mirror::Object> orig_dex(ext->GetOriginalDexFile());
195   if (orig_dex.IsNull()) {
196     // We don't seem to have ever been redefined so be conservative and say we need de-quickening.
197     *from_class_ext = false;
198     return true;
199   } else if (!orig_dex->IsArrayInstance()) {
200     // We were redefined but the original is held in a dex-cache or dex file. This means that the
201     // original dex file is the one from the disk, which might be quickened.
202     DCHECK(orig_dex->IsDexCache() || orig_dex->GetClass()->DescriptorEquals("Ljava/lang/Long;"));
203     *from_class_ext = true;
204     return true;
205   } else {
206     // An array instance means the original-dex-file is from a redefineClasses which cannot have any
207     // quickening, so it's fine to use directly.
208     DCHECK(orig_dex->GetClass()->GetComponentType()->IsPrimitiveByte());
209     *from_class_ext = true;
210     return false;
211   }
212 }
213 
GetQuickenedDexFile(art::Handle<art::mirror::Class> klass)214 static const art::DexFile* GetQuickenedDexFile(art::Handle<art::mirror::Class> klass)
215     REQUIRES_SHARED(art::Locks::mutator_lock_) {
216   art::ObjPtr<art::mirror::ClassExt> ext(klass->GetExtData());
217   if (ext.IsNull() || ext->GetOriginalDexFile() == nullptr) {
218     return &klass->GetDexFile();
219   }
220 
221   art::ObjPtr<art::mirror::Object> orig_dex(ext->GetOriginalDexFile());
222   DCHECK(!orig_dex->IsArrayInstance());
223   if (orig_dex->IsDexCache()) {
224     return orig_dex->AsDexCache()->GetDexFile();
225   }
226 
227   DCHECK(orig_dex->GetClass()->DescriptorEquals("Ljava/lang/Long;"))
228       << "Expected java/lang/Long but found object of type "
229       << orig_dex->GetClass()->PrettyClass();
230   art::ObjPtr<art::mirror::Class> prim_long_class(
231       art::GetClassRoot(art::ClassRoot::kPrimitiveLong));
232   art::JValue val;
233   if (!art::UnboxPrimitiveForResult(orig_dex.Ptr(), prim_long_class, &val)) {
234     LOG(FATAL) << "Unable to unwrap a long value!";
235   }
236   return reinterpret_cast<const art::DexFile*>(static_cast<uintptr_t>(val.GetJ()));
237 }
238 
239 template<typename GetOriginalDexFile>
InitWithDex(GetOriginalDexFile get_original,const art::DexFile * quick_dex)240 void ArtClassDefinition::InitWithDex(GetOriginalDexFile get_original,
241                                      const art::DexFile* quick_dex) {
242   art::Thread* self = art::Thread::Current();
243   DCHECK(quick_dex != nullptr);
244   if (art::MemMap::kCanReplaceMapping && kEnableOnDemandDexDequicken) {
245     size_t dequick_size = quick_dex->GetDequickenedSize();
246     std::string mmap_name("anon-mmap-for-redefine: ");
247     mmap_name += name_;
248     std::string error;
249     dex_data_mmap_ = art::MemMap::MapAnonymous(mmap_name.c_str(),
250                                                dequick_size,
251                                                PROT_NONE,
252                                                /*low_4gb=*/ false,
253                                                &error);
254     mmap_name += "-TEMP";
255     temp_mmap_ = art::MemMap::MapAnonymous(mmap_name.c_str(),
256                                            dequick_size,
257                                            PROT_READ | PROT_WRITE,
258                                            /*low_4gb=*/ false,
259                                            &error);
260     if (UNLIKELY(dex_data_mmap_.IsValid() && temp_mmap_.IsValid())) {
261       // Need to save the initial dexfile so we don't need to search for it in the fault-handler.
262       initial_dex_file_unquickened_ = quick_dex;
263       dex_data_ = art::ArrayRef<const unsigned char>(dex_data_mmap_.Begin(),
264                                                      dex_data_mmap_.Size());
265       if (from_class_ext_) {
266         // We got initial from class_ext so the current one must have undergone redefinition so no
267         // cdex or quickening stuff.
268         // We can only do this if it's not a first load.
269         DCHECK(klass_ != nullptr);
270         const art::DexFile& cur_dex = self->DecodeJObject(klass_)->AsClass()->GetDexFile();
271         current_dex_file_ = art::ArrayRef<const unsigned char>(cur_dex.Begin(), cur_dex.Size());
272       } else {
273         // This class hasn't been redefined before. The dequickened current data is the same as the
274         // dex_data_mmap_ when it's filled it. We don't need to copy anything because the mmap will
275         // not be cleared until after everything is done.
276         current_dex_file_ = art::ArrayRef<const unsigned char>(dex_data_mmap_.Begin(),
277                                                                dequick_size);
278       }
279       return;
280     }
281   }
282   dex_data_mmap_.Reset();
283   temp_mmap_.Reset();
284   // Failed to mmap a large enough area (or on-demand dequickening was disabled). This is
285   // unfortunate. Since currently the size is just a guess though we might as well try to do it
286   // manually.
287   get_original(/*out*/&dex_data_memory_);
288   dex_data_ = art::ArrayRef<const unsigned char>(dex_data_memory_);
289   if (from_class_ext_) {
290     // We got initial from class_ext so the current one must have undergone redefinition so no
291     // cdex or quickening stuff.
292     // We can only do this if it's not a first load.
293     DCHECK(klass_ != nullptr);
294     const art::DexFile& cur_dex = self->DecodeJObject(klass_)->AsClass()->GetDexFile();
295     current_dex_file_ = art::ArrayRef<const unsigned char>(cur_dex.Begin(), cur_dex.Size());
296   } else {
297     // No redefinition must have ever happened so the (dequickened) cur_dex is the same as the
298     // initial dex_data. We need to copy it into another buffer to keep it around if we have a
299     // real redefinition.
300     current_dex_memory_.resize(dex_data_.size());
301     memcpy(current_dex_memory_.data(), dex_data_.data(), current_dex_memory_.size());
302     current_dex_file_ = art::ArrayRef<const unsigned char>(current_dex_memory_);
303   }
304 }
305 
Init(art::Thread * self,jclass klass)306 jvmtiError ArtClassDefinition::Init(art::Thread* self, jclass klass) {
307   jvmtiError res = InitCommon(self, klass);
308   if (res != OK) {
309     return res;
310   }
311   art::ScopedObjectAccess soa(self);
312   art::StackHandleScope<1> hs(self);
313   art::Handle<art::mirror::Class> m_klass(hs.NewHandle(self->DecodeJObject(klass)->AsClass()));
314   if (!DexNeedsDequickening(m_klass, &from_class_ext_)) {
315     // We don't need to do any dequickening. We want to copy the data just so we don't need to deal
316     // with the GC moving it around.
317     art::ObjPtr<art::mirror::ByteArray> orig_dex(
318         m_klass->GetExtData()->GetOriginalDexFile()->AsByteArray());
319     dex_data_memory_.resize(orig_dex->GetLength());
320     memcpy(dex_data_memory_.data(), orig_dex->GetData(), dex_data_memory_.size());
321     dex_data_ = art::ArrayRef<const unsigned char>(dex_data_memory_);
322 
323     // Since we are here we must not have any quickened instructions since we were redefined.
324     const art::DexFile& cur_dex = m_klass->GetDexFile();
325     DCHECK(from_class_ext_);
326     current_dex_file_ = art::ArrayRef<const unsigned char>(cur_dex.Begin(), cur_dex.Size());
327     return OK;
328   }
329 
330   // We need to dequicken stuff. This is often super slow (10's of ms). Instead we will do it
331   // dynamically.
332   const art::DexFile* quick_dex = GetQuickenedDexFile(m_klass);
333   auto get_original = [&](/*out*/std::vector<unsigned char>* dex_data)
334       REQUIRES_SHARED(art::Locks::mutator_lock_) {
335     GetDexDataForRetransformation(m_klass, dex_data);
336   };
337   InitWithDex(get_original, quick_dex);
338   return OK;
339 }
340 
Init(art::Thread * self,const jvmtiClassDefinition & def)341 jvmtiError ArtClassDefinition::Init(art::Thread* self, const jvmtiClassDefinition& def) {
342   jvmtiError res = InitCommon(self, def.klass);
343   if (res != OK) {
344     return res;
345   }
346   // We are being directly redefined.
347   redefined_ = true;
348   current_dex_file_ = art::ArrayRef<const unsigned char>(def.class_bytes, def.class_byte_count);
349   dex_data_ = art::ArrayRef<const unsigned char>(def.class_bytes, def.class_byte_count);
350   return OK;
351 }
352 
InitFirstLoad(const char * descriptor,art::Handle<art::mirror::ClassLoader> klass_loader,const art::DexFile & dex_file)353 void ArtClassDefinition::InitFirstLoad(const char* descriptor,
354                                        art::Handle<art::mirror::ClassLoader> klass_loader,
355                                        const art::DexFile& dex_file) {
356   art::Thread* self = art::Thread::Current();
357   art::ScopedObjectAccess soa(self);
358   initialized_ = true;
359   // No Class
360   klass_ = nullptr;
361   loader_ = soa.AddLocalReference<jobject>(klass_loader.Get());
362   std::string descriptor_str(descriptor);
363   name_ = descriptor_str.substr(1, descriptor_str.size() - 2);
364   // Android doesn't really have protection domains.
365   protection_domain_ = nullptr;
366   auto get_original = [&](/*out*/std::vector<unsigned char>* dex_data)
367       REQUIRES_SHARED(art::Locks::mutator_lock_) {
368     DequickenDexFile(&dex_file, descriptor, dex_data);
369   };
370   InitWithDex(get_original, &dex_file);
371 }
372 
373 }  // namespace openjdkjvmti
374