1 /* Copyright (C) 2017 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_search.h"
33 
34 #include "jni.h"
35 
36 #include "art_field-inl.h"
37 #include "art_jvmti.h"
38 #include "base/enums.h"
39 #include "base/macros.h"
40 #include "class_linker.h"
41 #include "dex/art_dex_file_loader.h"
42 #include "dex/dex_file.h"
43 #include "dex/dex_file_loader.h"
44 #include "jni_internal.h"
45 #include "mirror/class-inl.h"
46 #include "mirror/object.h"
47 #include "mirror/string.h"
48 #include "nativehelper/scoped_local_ref.h"
49 #include "obj_ptr-inl.h"
50 #include "runtime.h"
51 #include "runtime_callbacks.h"
52 #include "scoped_thread_state_change-inl.h"
53 #include "thread-current-inl.h"
54 #include "thread_list.h"
55 #include "ti_phase.h"
56 #include "well_known_classes.h"
57 
58 namespace openjdkjvmti {
59 
60 static std::vector<std::string> gSystemOnloadSegments;
61 
GetSystemProperties(art::Thread * self,art::ClassLinker * class_linker)62 static art::ObjPtr<art::mirror::Object> GetSystemProperties(art::Thread* self,
63                                                             art::ClassLinker* class_linker)
64     REQUIRES_SHARED(art::Locks::mutator_lock_) {
65   art::ObjPtr<art::mirror::Class> system_class =
66       class_linker->LookupClass(self, "Ljava/lang/System;", nullptr);
67   DCHECK(system_class != nullptr);
68   DCHECK(system_class->IsInitialized());
69 
70   art::ArtField* props_field =
71       system_class->FindDeclaredStaticField("props", "Ljava/util/Properties;");
72   DCHECK(props_field != nullptr);
73 
74   art::ObjPtr<art::mirror::Object> props_obj = props_field->GetObject(system_class);
75   DCHECK(props_obj != nullptr);
76 
77   return props_obj;
78 }
79 
Update()80 static void Update() REQUIRES_SHARED(art::Locks::mutator_lock_) {
81   if (gSystemOnloadSegments.empty()) {
82     return;
83   }
84 
85   // In the on-load phase we have to modify java.class.path to influence the system classloader.
86   // As this is an unmodifiable system property, we have to access the "defaults" field.
87   art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
88   DCHECK(class_linker != nullptr);
89   art::Thread* self = art::Thread::Current();
90 
91   // Prepare: collect classes, fields and methods.
92   art::ObjPtr<art::mirror::Class> properties_class =
93       class_linker->LookupClass(self, "Ljava/util/Properties;", nullptr);
94   DCHECK(properties_class != nullptr);
95 
96   ScopedLocalRef<jobject> defaults_jobj(self->GetJniEnv(), nullptr);
97   {
98     art::ObjPtr<art::mirror::Object> props_obj = GetSystemProperties(self, class_linker);
99 
100     art::ArtField* defaults_field =
101         properties_class->FindDeclaredInstanceField("defaults", "Ljava/util/Properties;");
102     DCHECK(defaults_field != nullptr);
103 
104     art::ObjPtr<art::mirror::Object> defaults_obj = defaults_field->GetObject(props_obj);
105     DCHECK(defaults_obj != nullptr);
106     defaults_jobj.reset(self->GetJniEnv()->AddLocalReference<jobject>(defaults_obj));
107   }
108 
109   art::ArtMethod* get_property =
110       properties_class->FindClassMethod(
111           "getProperty",
112           "(Ljava/lang/String;)Ljava/lang/String;",
113           art::kRuntimePointerSize);
114   DCHECK(get_property != nullptr);
115   DCHECK(!get_property->IsDirect());
116   DCHECK(get_property->GetDeclaringClass() == properties_class);
117   art::ArtMethod* set_property =
118       properties_class->FindClassMethod(
119           "setProperty",
120           "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;",
121           art::kRuntimePointerSize);
122   DCHECK(set_property != nullptr);
123   DCHECK(!set_property->IsDirect());
124   DCHECK(set_property->GetDeclaringClass() == properties_class);
125 
126   // This is an allocation. Do this late to avoid the need for handles.
127   ScopedLocalRef<jobject> cp_jobj(self->GetJniEnv(), nullptr);
128   {
129     art::ObjPtr<art::mirror::Object> cp_key =
130         art::mirror::String::AllocFromModifiedUtf8(self, "java.class.path");
131     if (cp_key == nullptr) {
132       self->AssertPendingOOMException();
133       self->ClearException();
134       return;
135     }
136     cp_jobj.reset(self->GetJniEnv()->AddLocalReference<jobject>(cp_key));
137   }
138 
139   // OK, now get the current value.
140   std::string str_value;
141   {
142     ScopedLocalRef<jobject> old_value(self->GetJniEnv(),
143                                       self->GetJniEnv()->CallObjectMethod(
144                                           defaults_jobj.get(),
145                                           art::jni::EncodeArtMethod(get_property),
146                                           cp_jobj.get()));
147     DCHECK(old_value.get() != nullptr);
148 
149     str_value = self->DecodeJObject(old_value.get())->AsString()->ToModifiedUtf8();
150     self->GetJniEnv()->DeleteLocalRef(old_value.release());
151   }
152 
153   // Update the value by appending the new segments.
154   for (const std::string& segment : gSystemOnloadSegments) {
155     if (!str_value.empty()) {
156       str_value += ":";
157     }
158     str_value += segment;
159   }
160   gSystemOnloadSegments.clear();
161 
162   // Create the new value object.
163   ScopedLocalRef<jobject> new_val_jobj(self->GetJniEnv(), nullptr);
164   {
165     art::ObjPtr<art::mirror::Object> new_value =
166         art::mirror::String::AllocFromModifiedUtf8(self, str_value.c_str());
167     if (new_value == nullptr) {
168       self->AssertPendingOOMException();
169       self->ClearException();
170       return;
171     }
172 
173     new_val_jobj.reset(self->GetJniEnv()->AddLocalReference<jobject>(new_value));
174   }
175 
176   // Write to the defaults.
177   ScopedLocalRef<jobject> res_obj(self->GetJniEnv(),
178                                   self->GetJniEnv()->CallObjectMethod(defaults_jobj.get(),
179                                       art::jni::EncodeArtMethod(set_property),
180                                       cp_jobj.get(),
181                                       new_val_jobj.get()));
182   if (self->IsExceptionPending()) {
183     self->ClearException();
184     return;
185   }
186 }
187 
188 struct SearchCallback : public art::RuntimePhaseCallback {
NextRuntimePhaseopenjdkjvmti::SearchCallback189   void NextRuntimePhase(RuntimePhase phase) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
190     if (phase == RuntimePhase::kStart) {
191       // It's time to update the system properties.
192       Update();
193     }
194   }
195 };
196 
197 static SearchCallback gSearchCallback;
198 
Register()199 void SearchUtil::Register() {
200   art::Runtime* runtime = art::Runtime::Current();
201 
202   art::ScopedThreadStateChange stsc(art::Thread::Current(),
203                                     art::ThreadState::kWaitingForDebuggerToAttach);
204   art::ScopedSuspendAll ssa("Add search callback");
205   runtime->GetRuntimeCallbacks()->AddRuntimePhaseCallback(&gSearchCallback);
206 }
207 
Unregister()208 void SearchUtil::Unregister() {
209   art::ScopedThreadStateChange stsc(art::Thread::Current(),
210                                     art::ThreadState::kWaitingForDebuggerToAttach);
211   art::ScopedSuspendAll ssa("Remove search callback");
212   art::Runtime* runtime = art::Runtime::Current();
213   runtime->GetRuntimeCallbacks()->RemoveRuntimePhaseCallback(&gSearchCallback);
214 }
215 
AddToBootstrapClassLoaderSearch(jvmtiEnv * env ATTRIBUTE_UNUSED,const char * segment)216 jvmtiError SearchUtil::AddToBootstrapClassLoaderSearch(jvmtiEnv* env ATTRIBUTE_UNUSED,
217                                                        const char* segment) {
218   art::Runtime* current = art::Runtime::Current();
219   if (current == nullptr) {
220     return ERR(WRONG_PHASE);
221   }
222   if (current->GetClassLinker() == nullptr) {
223     return ERR(WRONG_PHASE);
224   }
225   if (segment == nullptr) {
226     return ERR(NULL_POINTER);
227   }
228 
229   std::string error_msg;
230   std::vector<std::unique_ptr<const art::DexFile>> dex_files;
231   const art::ArtDexFileLoader dex_file_loader;
232   if (!dex_file_loader.Open(
233         segment, segment, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files)) {
234     LOG(WARNING) << "Could not open " << segment << " for boot classpath extension: " << error_msg;
235     return ERR(ILLEGAL_ARGUMENT);
236   }
237 
238   art::ScopedObjectAccess soa(art::Thread::Current());
239   for (std::unique_ptr<const art::DexFile>& dex_file : dex_files) {
240     current->GetClassLinker()->AppendToBootClassPath(art::Thread::Current(), *dex_file.release());
241   }
242 
243   return ERR(NONE);
244 }
245 
AddToSystemClassLoaderSearch(jvmtiEnv * jvmti_env ATTRIBUTE_UNUSED,const char * segment)246 jvmtiError SearchUtil::AddToSystemClassLoaderSearch(jvmtiEnv* jvmti_env ATTRIBUTE_UNUSED,
247                                                     const char* segment) {
248   if (segment == nullptr) {
249     return ERR(NULL_POINTER);
250   }
251 
252   jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
253 
254   if (phase == jvmtiPhase::JVMTI_PHASE_ONLOAD) {
255     // We could try and see whether it is a valid path. We could also try to allocate Java
256     // objects to avoid later OOME.
257     gSystemOnloadSegments.push_back(segment);
258     return ERR(NONE);
259   } else if (phase != jvmtiPhase::JVMTI_PHASE_LIVE) {
260     return ERR(WRONG_PHASE);
261   }
262 
263   jobject sys_class_loader = art::Runtime::Current()->GetSystemClassLoader();
264   if (sys_class_loader == nullptr) {
265     // This is unexpected.
266     return ERR(INTERNAL);
267   }
268 
269   // We'll use BaseDexClassLoader.addDexPath, as it takes care of array resizing etc. As a downside,
270   // exceptions are swallowed.
271 
272   art::Thread* self = art::Thread::Current();
273   JNIEnv* env = self->GetJniEnv();
274   if (!env->IsInstanceOf(sys_class_loader,
275                          art::WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
276     return ERR(INTERNAL);
277   }
278 
279   jmethodID add_dex_path_id = env->GetMethodID(
280       art::WellKnownClasses::dalvik_system_BaseDexClassLoader,
281       "addDexPath",
282       "(Ljava/lang/String;)V");
283   if (add_dex_path_id == nullptr) {
284     return ERR(INTERNAL);
285   }
286 
287   ScopedLocalRef<jstring> dex_path(env, env->NewStringUTF(segment));
288   if (dex_path.get() == nullptr) {
289     return ERR(INTERNAL);
290   }
291   env->CallVoidMethod(sys_class_loader, add_dex_path_id, dex_path.get());
292 
293   if (env->ExceptionCheck()) {
294     env->ExceptionClear();
295     return ERR(ILLEGAL_ARGUMENT);
296   }
297   return ERR(NONE);
298 }
299 
300 }  // namespace openjdkjvmti
301