Home | History | Annotate | Download | only in runtime
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef ART_RUNTIME_JNI_ENV_EXT_H_
     18 #define ART_RUNTIME_JNI_ENV_EXT_H_
     19 
     20 #include <jni.h>
     21 
     22 #include "base/macros.h"
     23 #include "base/mutex.h"
     24 #include "indirect_reference_table.h"
     25 #include "obj_ptr.h"
     26 #include "reference_table.h"
     27 
     28 namespace art {
     29 
     30 class JavaVMExt;
     31 
     32 namespace mirror {
     33 class Object;
     34 }  // namespace mirror
     35 
     36 // Number of local references in the indirect reference table. The value is arbitrary but
     37 // low enough that it forces sanity checks.
     38 static constexpr size_t kLocalsInitial = 512;
     39 
     40 class JNIEnvExt : public JNIEnv {
     41  public:
     42   // Creates a new JNIEnvExt. Returns null on error, in which case error_msg
     43   // will contain a description of the error.
     44   static JNIEnvExt* Create(Thread* self, JavaVMExt* vm, std::string* error_msg);
     45   static Offset SegmentStateOffset(size_t pointer_size);
     46   static Offset LocalRefCookieOffset(size_t pointer_size);
     47   static Offset SelfOffset(size_t pointer_size);
     48   static jint GetEnvHandler(JavaVMExt* vm, /*out*/void** out, jint version);
     49 
     50   ~JNIEnvExt();
     51 
     52   void DumpReferenceTables(std::ostream& os)
     53       REQUIRES_SHARED(Locks::mutator_lock_)
     54       REQUIRES(!Locks::alloc_tracker_lock_);
     55 
     56   void SetCheckJniEnabled(bool enabled) REQUIRES(!Locks::jni_function_table_lock_);
     57 
     58   void PushFrame(int capacity) REQUIRES_SHARED(Locks::mutator_lock_);
     59   void PopFrame() REQUIRES_SHARED(Locks::mutator_lock_);
     60 
     61   template<typename T>
     62   T AddLocalReference(ObjPtr<mirror::Object> obj)
     63       REQUIRES_SHARED(Locks::mutator_lock_)
     64       REQUIRES(!Locks::alloc_tracker_lock_);
     65 
     66   void UpdateLocal(IndirectRef iref, ObjPtr<mirror::Object> obj) REQUIRES_SHARED(Locks::mutator_lock_) {
     67     locals_.Update(iref, obj);
     68   }
     69 
     70   jobject NewLocalRef(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_);
     71   void DeleteLocalRef(jobject obj) REQUIRES_SHARED(Locks::mutator_lock_);
     72 
     73   void TrimLocals() REQUIRES_SHARED(Locks::mutator_lock_) {
     74     locals_.Trim();
     75   }
     76   void AssertLocalsEmpty() REQUIRES_SHARED(Locks::mutator_lock_) {
     77     locals_.AssertEmpty();
     78   }
     79   size_t GetLocalsCapacity() REQUIRES_SHARED(Locks::mutator_lock_) {
     80     return locals_.Capacity();
     81   }
     82 
     83   IRTSegmentState GetLocalRefCookie() const { return local_ref_cookie_; }
     84   void SetLocalRefCookie(IRTSegmentState new_cookie) { local_ref_cookie_ = new_cookie; }
     85 
     86   IRTSegmentState GetLocalsSegmentState() const REQUIRES_SHARED(Locks::mutator_lock_) {
     87     return locals_.GetSegmentState();
     88   }
     89   void SetLocalSegmentState(IRTSegmentState new_state) REQUIRES_SHARED(Locks::mutator_lock_) {
     90     locals_.SetSegmentState(new_state);
     91   }
     92 
     93   void VisitJniLocalRoots(RootVisitor* visitor, const RootInfo& root_info)
     94       REQUIRES_SHARED(Locks::mutator_lock_) {
     95     locals_.VisitRoots(visitor, root_info);
     96   }
     97 
     98   Thread* GetSelf() const { return self_; }
     99   uint32_t GetCritical() const { return critical_; }
    100   void SetCritical(uint32_t new_critical) { critical_ = new_critical; }
    101   uint64_t GetCriticalStartUs() const { return critical_start_us_; }
    102   void SetCriticalStartUs(uint64_t new_critical_start_us) {
    103     critical_start_us_ = new_critical_start_us;
    104   }
    105   const JNINativeInterface* GetUncheckedFunctions() const {
    106     return unchecked_functions_;
    107   }
    108   JavaVMExt* GetVm() const { return vm_; }
    109 
    110   bool IsRuntimeDeleted() const { return runtime_deleted_; }
    111   bool IsCheckJniEnabled() const { return check_jni_; }
    112 
    113 
    114   // Functions to keep track of monitor lock and unlock operations. Used to ensure proper locking
    115   // rules in CheckJNI mode.
    116 
    117   // Record locking of a monitor.
    118   void RecordMonitorEnter(jobject obj) REQUIRES_SHARED(Locks::mutator_lock_);
    119 
    120   // Check the release, that is, that the release is performed in the same JNI "segment."
    121   void CheckMonitorRelease(jobject obj) REQUIRES_SHARED(Locks::mutator_lock_);
    122 
    123   // Check that no monitors are held that have been acquired in this JNI "segment."
    124   void CheckNoHeldMonitors() REQUIRES_SHARED(Locks::mutator_lock_);
    125 
    126   void VisitMonitorRoots(RootVisitor* visitor, const RootInfo& root_info)
    127       REQUIRES_SHARED(Locks::mutator_lock_) {
    128     monitors_.VisitRoots(visitor, root_info);
    129   }
    130 
    131   // Set the functions to the runtime shutdown functions.
    132   void SetFunctionsToRuntimeShutdownFunctions();
    133 
    134   // Set the function table override. This will install the override (or original table, if null)
    135   // to all threads.
    136   // Note: JNI function table overrides are sensitive to the order of operations wrt/ CheckJNI.
    137   //       After overriding the JNI function table, CheckJNI toggling is ignored.
    138   static void SetTableOverride(const JNINativeInterface* table_override)
    139       REQUIRES(!Locks::thread_list_lock_, !Locks::jni_function_table_lock_);
    140 
    141   // Return either the regular, or the CheckJNI function table. Will return table_override_ instead
    142   // if it is not null.
    143   static const JNINativeInterface* GetFunctionTable(bool check_jni)
    144       REQUIRES(Locks::jni_function_table_lock_);
    145 
    146  private:
    147   // Checking "locals" requires the mutator lock, but at creation time we're
    148   // really only interested in validity, which isn't changing. To avoid grabbing
    149   // the mutator lock, factored out and tagged with NO_THREAD_SAFETY_ANALYSIS.
    150   static bool CheckLocalsValid(JNIEnvExt* in) NO_THREAD_SAFETY_ANALYSIS;
    151 
    152   // Override of function tables. This applies to both default as well as instrumented (CheckJNI)
    153   // function tables.
    154   static const JNINativeInterface* table_override_ GUARDED_BY(Locks::jni_function_table_lock_);
    155 
    156   // The constructor should not be called directly. It may leave the object in an erroneous state,
    157   // and the result needs to be checked.
    158   JNIEnvExt(Thread* self, JavaVMExt* vm, std::string* error_msg)
    159       REQUIRES(!Locks::jni_function_table_lock_);
    160 
    161   // Link to Thread::Current().
    162   Thread* const self_;
    163 
    164   // The invocation interface JavaVM.
    165   JavaVMExt* const vm_;
    166 
    167   // Cookie used when using the local indirect reference table.
    168   IRTSegmentState local_ref_cookie_;
    169 
    170   // JNI local references.
    171   IndirectReferenceTable locals_ GUARDED_BY(Locks::mutator_lock_);
    172 
    173   // Stack of cookies corresponding to PushLocalFrame/PopLocalFrame calls.
    174   // TODO: to avoid leaks (and bugs), we need to clear this vector on entry (or return)
    175   // to a native method.
    176   std::vector<IRTSegmentState> stacked_local_ref_cookies_;
    177 
    178   // Entered JNI monitors, for bulk exit on thread detach.
    179   ReferenceTable monitors_;
    180 
    181   // Used by -Xcheck:jni.
    182   const JNINativeInterface* unchecked_functions_;
    183 
    184   // All locked objects, with the (Java caller) stack frame that locked them. Used in CheckJNI
    185   // to ensure that only monitors locked in this native frame are being unlocked, and that at
    186   // the end all are unlocked.
    187   std::vector<std::pair<uintptr_t, jobject>> locked_objects_;
    188 
    189   // Start time of "critical" JNI calls to ensure that their use doesn't
    190   // excessively block the VM with CheckJNI.
    191   uint64_t critical_start_us_;
    192 
    193   // How many nested "critical" JNI calls are we in? Used by CheckJNI to ensure that criticals are
    194   uint32_t critical_;
    195 
    196   // Frequently-accessed fields cached from JavaVM.
    197   bool check_jni_;
    198 
    199   // If we are a JNI env for a daemon thread with a deleted runtime.
    200   bool runtime_deleted_;
    201 
    202   friend class JNI;
    203   friend class ScopedJniEnvLocalRefState;
    204   friend class Thread;
    205   ART_FRIEND_TEST(JniInternalTest, JNIEnvExtOffsets);
    206 };
    207 
    208 // Used to save and restore the JNIEnvExt state when not going through code created by the JNI
    209 // compiler.
    210 class ScopedJniEnvLocalRefState {
    211  public:
    212   explicit ScopedJniEnvLocalRefState(JNIEnvExt* env) :
    213       env_(env),
    214       saved_local_ref_cookie_(env->local_ref_cookie_) {
    215     env->local_ref_cookie_ = env->locals_.GetSegmentState();
    216   }
    217 
    218   ~ScopedJniEnvLocalRefState() {
    219     env_->locals_.SetSegmentState(env_->local_ref_cookie_);
    220     env_->local_ref_cookie_ = saved_local_ref_cookie_;
    221   }
    222 
    223  private:
    224   JNIEnvExt* const env_;
    225   const IRTSegmentState saved_local_ref_cookie_;
    226 
    227   DISALLOW_COPY_AND_ASSIGN(ScopedJniEnvLocalRefState);
    228 };
    229 
    230 }  // namespace art
    231 
    232 #endif  // ART_RUNTIME_JNI_ENV_EXT_H_
    233