1 /*
  2  * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 package sun.jvm.hotspot.oops;
 26 
 27 import java.util.*;
 28 
 29 import sun.jvm.hotspot.debugger.*;
 30 import sun.jvm.hotspot.memory.*;
 31 import sun.jvm.hotspot.runtime.*;
 32 import sun.jvm.hotspot.types.TypeDataBase;
 33 import sun.jvm.hotspot.utilities.*;
 34 import sun.jvm.hotspot.utilities.Observable;
 35 import sun.jvm.hotspot.utilities.Observer;
 36 
 37 /** A utility class encapsulating useful oop operations */
 38 
 39 public class OopUtilities {
 40 
 41   // FIXME: access should be synchronized and cleared when VM is
 42   // resumed
 43   // String fields
 44   private static ByteField coderField;
 45   private static OopField valueField;
 46   // ThreadGroup fields
 47   private static OopField threadGroupParentField;
 48   private static OopField threadGroupNameField;
 49   private static IntField threadGroupNThreadsField;
 50   private static OopField threadGroupThreadsField;
 51   private static IntField threadGroupNGroupsField;
 52   private static OopField threadGroupGroupsField;
 53   // Thread fields
 54   private static OopField threadNameField;
 55   private static OopField threadGroupField;
 56   private static LongField threadEETopField;
 57   //tid field is new since 1.5
 58   private static LongField threadTIDField;
 59   // threadStatus field is new since 1.5
 60   private static IntField threadStatusField;
 61   // parkBlocker field is new since 1.6
 62   private static OopField threadParkBlockerField;
 63 
 64   private static IntField threadPriorityField;
 65   private static BooleanField threadDaemonField;
 66 
 67   // possible values of JavaThreadStatus
 68   public static int THREAD_STATUS_NEW;
 69 
 70   public static int THREAD_STATUS_RUNNABLE;
 71   public static int THREAD_STATUS_SLEEPING;
 72   public static int THREAD_STATUS_IN_OBJECT_WAIT;
 73   public static int THREAD_STATUS_IN_OBJECT_WAIT_TIMED;
 74   public static int THREAD_STATUS_PARKED;
 75   public static int THREAD_STATUS_PARKED_TIMED;
 76   public static int THREAD_STATUS_BLOCKED_ON_MONITOR_ENTER;
 77   public static int THREAD_STATUS_TERMINATED;
 78 
 79   // java.util.concurrent.locks.AbstractOwnableSynchronizer fields
 80   private static OopField absOwnSyncOwnerThreadField;
 81 
 82   private static final int JVMTI_THREAD_STATE_ALIVE = 0x0001;
 83 
 84   static {
 85     VM.registerVMInitializedObserver(new Observer() {
 86         public void update(Observable o, Object data) {
 87           initialize(VM.getVM().getTypeDataBase());
 88         }
 89       });
 90   }
 91 
 92   private static synchronized void initialize(TypeDataBase db) {
 93     // FIXME: don't need this observer; however, do need a VM resumed
 94     // and suspended observer to refetch fields
 95   }
 96 
 97   public static String charArrayToString(TypeArray charArray) {
 98     if (charArray == null) {
 99       return null;
100     }
101     int length = (int)charArray.getLength();
102     StringBuilder buf = new StringBuilder(length);
103     for (int i = 0; i < length; i++) {
104       buf.append(charArray.getCharAt(i));
105     }
106     return buf.toString();
107   }
108 
109   public static String byteArrayToString(TypeArray byteArray, byte coder) {
110     if (byteArray == null) {
111       return null;
112     }
113     int length = (int)byteArray.getLength() >> coder;
114     StringBuilder buf = new StringBuilder(length);
115     if (coder == 0) {
116       // Latin1 encoded
117       for (int i = 0; i < length; i++) {
118         buf.append((char)(byteArray.getByteAt(i) & 0xff));
119       }
120     } else {
121       // UTF16 encoded
122       for (int i = 0; i < length; i++) {
123         buf.append(byteArray.getCharAt(i));
124       }
125     }
126     return buf.toString();
127   }
128 
129   public static String escapeString(String s) {
130     StringBuilder sb = null;
131     for (int index = 0; index < s.length(); index++) {
132       char value = s.charAt(index);
133       if (value >= 32 && value < 127 || value == '\'' || value == '\\') {
134         if (sb != null) {
135           sb.append(value);
136         }
137       } else {
138         if (sb == null) {
139           sb = new StringBuilder(s.length() * 2);
140           sb.append(s, 0, index);
141         }
142         sb.append("\\u");
143         if (value < 0x10) sb.append("000");
144         else if (value < 0x100) sb.append("00");
145         else if (value < 0x1000) sb.append("0");
146         sb.append(Integer.toHexString(value));
147       }
148     }
149     if (sb != null) {
150       return sb.toString();
151     }
152     return s;
153   }
154 
155   public static String stringOopToString(Oop stringOop) {
156     InstanceKlass k = (InstanceKlass) stringOop.getKlass();
157     coderField  = (ByteField) k.findField("coder", "B");
158     valueField  = (OopField) k.findField("value",  "[B");
159     if (Assert.ASSERTS_ENABLED) {
160        Assert.that(coderField != null, "Field \'coder\' of java.lang.String not found");
161        Assert.that(valueField != null, "Field \'value\' of java.lang.String not found");
162     }
163     return byteArrayToString((TypeArray) valueField.getValue(stringOop), coderField.getValue(stringOop));
164   }
165 
166   public static String stringOopToEscapedString(Oop stringOop) {
167     return escapeString(stringOopToString(stringOop));
168   }
169 
170   private static void initThreadGroupFields() {
171     if (threadGroupParentField == null) {
172       SystemDictionary sysDict = VM.getVM().getSystemDictionary();
173       InstanceKlass k = sysDict.getThreadGroupKlass();
174       threadGroupParentField   = (OopField) k.findField("parent",   "Ljava/lang/ThreadGroup;");
175       threadGroupNameField     = (OopField) k.findField("name",     "Ljava/lang/String;");
176       threadGroupNThreadsField = (IntField) k.findField("nthreads", "I");
177       threadGroupThreadsField  = (OopField) k.findField("threads",  "[Ljava/lang/Thread;");
178       threadGroupNGroupsField  = (IntField) k.findField("ngroups",  "I");
179       threadGroupGroupsField   = (OopField) k.findField("groups",   "[Ljava/lang/ThreadGroup;");
180       if (Assert.ASSERTS_ENABLED) {
181         Assert.that(threadGroupParentField   != null &&
182                     threadGroupNameField     != null &&
183                     threadGroupNThreadsField != null &&
184                     threadGroupThreadsField  != null &&
185                     threadGroupNGroupsField  != null &&
186                     threadGroupGroupsField   != null, "must find all java.lang.ThreadGroup fields");
187       }
188     }
189   }
190 
191   public static Oop threadGroupOopGetParent(Oop threadGroupOop) {
192     initThreadGroupFields();
193     return threadGroupParentField.getValue(threadGroupOop);
194   }
195 
196   public static String threadGroupOopGetName(Oop threadGroupOop) {
197     initThreadGroupFields();
198     return stringOopToString(threadGroupNameField.getValue(threadGroupOop));
199   }
200 
201   public static Oop[] threadGroupOopGetThreads(Oop threadGroupOop) {
202     initThreadGroupFields();
203     int nthreads = threadGroupNThreadsField.getValue(threadGroupOop);
204     Oop[] result = new Oop[nthreads];
205     ObjArray threads = (ObjArray) threadGroupThreadsField.getValue(threadGroupOop);
206     for (int i = 0; i < nthreads; i++) {
207       result[i] = threads.getObjAt(i);
208     }
209     return result;
210   }
211 
212   public static Oop[] threadGroupOopGetGroups(Oop threadGroupOop) {
213     initThreadGroupFields();
214     int ngroups = threadGroupNGroupsField.getValue(threadGroupOop);
215     Oop[] result = new Oop[ngroups];
216     ObjArray groups = (ObjArray) threadGroupGroupsField.getValue(threadGroupOop);
217     for (int i = 0; i < ngroups; i++) {
218       result[i] = groups.getObjAt(i);
219     }
220     return result;
221   }
222 
223   private static void initThreadFields() {
224     if (threadNameField == null) {
225       SystemDictionary sysDict = VM.getVM().getSystemDictionary();
226       InstanceKlass k = sysDict.getThreadKlass();
227       threadNameField  = (OopField) k.findField("name", "Ljava/lang/String;");
228       threadGroupField = (OopField) k.findField("group", "Ljava/lang/ThreadGroup;");
229       threadEETopField = (LongField) k.findField("eetop", "J");
230       threadTIDField = (LongField) k.findField("tid", "J");
231       threadStatusField = (IntField) k.findField("threadStatus", "I");
232       threadParkBlockerField = (OopField) k.findField("parkBlocker",
233                                      "Ljava/lang/Object;");
234       threadPriorityField = (IntField) k.findField("priority", "I");
235       threadDaemonField = (BooleanField) k.findField("daemon", "Z");
236       TypeDataBase db = VM.getVM().getTypeDataBase();
237       THREAD_STATUS_NEW = db.lookupIntConstant("JavaThreadStatus::NEW").intValue();
238 
239       THREAD_STATUS_RUNNABLE = db.lookupIntConstant("JavaThreadStatus::RUNNABLE").intValue();
240       THREAD_STATUS_SLEEPING = db.lookupIntConstant("JavaThreadStatus::SLEEPING").intValue();
241       THREAD_STATUS_IN_OBJECT_WAIT = db.lookupIntConstant("JavaThreadStatus::IN_OBJECT_WAIT").intValue();
242       THREAD_STATUS_IN_OBJECT_WAIT_TIMED = db.lookupIntConstant("JavaThreadStatus::IN_OBJECT_WAIT_TIMED").intValue();
243       THREAD_STATUS_PARKED = db.lookupIntConstant("JavaThreadStatus::PARKED").intValue();
244       THREAD_STATUS_PARKED_TIMED = db.lookupIntConstant("JavaThreadStatus::PARKED_TIMED").intValue();
245       THREAD_STATUS_BLOCKED_ON_MONITOR_ENTER = db.lookupIntConstant("JavaThreadStatus::BLOCKED_ON_MONITOR_ENTER").intValue();
246       THREAD_STATUS_TERMINATED = db.lookupIntConstant("JavaThreadStatus::TERMINATED").intValue();
247 
248       if (Assert.ASSERTS_ENABLED) {
249         // it is okay to miss threadStatusField, because this was
250         // introduced only in 1.5 JDK.
251         Assert.that(threadNameField   != null &&
252                     threadGroupField  != null &&
253                     threadEETopField  != null, "must find all java.lang.Thread fields");
254       }
255     }
256   }
257 
258   public static Oop threadOopGetThreadGroup(Oop threadOop) {
259     initThreadFields();
260     return threadGroupField.getValue(threadOop);
261   }
262 
263   public static String threadOopGetName(Oop threadOop) {
264     initThreadFields();
265     return stringOopToString(threadNameField.getValue(threadOop));
266   }
267 
268   /** May return null if, e.g., thread was not started */
269   public static JavaThread threadOopGetJavaThread(Oop threadOop) {
270     initThreadFields();
271     Address addr = threadOop.getHandle().getAddressAt(threadEETopField.getOffset());
272     if (addr == null) {
273       return null;
274     }
275     return VM.getVM().getThreads().createJavaThreadWrapper(addr);
276   }
277 
278   public static long threadOopGetTID(Oop threadOop) {
279     initThreadFields();
280     if (threadTIDField != null) {
281       return threadTIDField.getValue(threadOop);
282     } else {
283       return 0;
284     }
285   }
286 
287   /** returns value of java.lang.Thread.threadStatus field */
288   public static int threadOopGetThreadStatus(Oop threadOop) {
289     initThreadFields();
290     // The threadStatus is only present starting in 1.5
291     if (threadStatusField != null) {
292       return (int) threadStatusField.getValue(threadOop);
293     } else {
294       // All we can easily figure out is if it is alive, but that is
295       // enough info for a valid unknown status.
296       JavaThread thr = threadOopGetJavaThread(threadOop);
297       if (thr == null) {
298         // the thread hasn't run yet or is in the process of exiting
299         return THREAD_STATUS_NEW;
300       } else {
301         return JVMTI_THREAD_STATE_ALIVE;
302       }
303     }
304   }
305 
306   /** returns value of java.lang.Thread.parkBlocker field */
307   public static Oop threadOopGetParkBlocker(Oop threadOop) {
308     initThreadFields();
309     if (threadParkBlockerField != null) {
310       return threadParkBlockerField.getValue(threadOop);
311     }
312     return null;
313   }
314 
315   // initialize fields for j.u.c.l AbstractOwnableSynchornizer class
316   private static void initAbsOwnSyncFields() {
317     if (absOwnSyncOwnerThreadField == null) {
318        SystemDictionary sysDict = VM.getVM().getSystemDictionary();
319        InstanceKlass k = sysDict.getAbstractOwnableSynchronizerKlass();
320        absOwnSyncOwnerThreadField =
321            (OopField) k.findField("exclusiveOwnerThread",
322                                   "Ljava/lang/Thread;");
323     }
324   }
325 
326   // return exclusiveOwnerThread field of AbstractOwnableSynchronizer class
327   public static Oop abstractOwnableSynchronizerGetOwnerThread(Oop oop) {
328     initAbsOwnSyncFields();
329     if (absOwnSyncOwnerThreadField == null) {
330       return null; // pre-1.6 VM?
331     } else {
332       return absOwnSyncOwnerThreadField.getValue(oop);
333     }
334   }
335 
336   public static int threadOopGetPriority(Oop threadOop) {
337     initThreadFields();
338     if (threadPriorityField != null) {
339       return threadPriorityField.getValue(threadOop);
340     } else {
341       return 0;
342     }
343   }
344 
345   public static boolean threadOopGetDaemon(Oop threadOop) {
346     initThreadFields();
347     if (threadDaemonField != null) {
348       return threadDaemonField.getValue(threadOop);
349     } else {
350       return false;
351     }
352   }
353 
354   public static String threadOopGetThreadStatusName(Oop threadOop) {
355     int status = OopUtilities.threadOopGetThreadStatus(threadOop);
356     if(status == THREAD_STATUS_NEW){
357       return "NEW";
358     }else if(status == THREAD_STATUS_RUNNABLE){
359       return "RUNNABLE";
360     }else if(status == THREAD_STATUS_SLEEPING){
361       return "TIMED_WAITING (sleeping)";
362     }else if(status == THREAD_STATUS_IN_OBJECT_WAIT){
363       return "WAITING (on object monitor)";
364     }else if(status == THREAD_STATUS_IN_OBJECT_WAIT_TIMED){
365       return "TIMED_WAITING (on object monitor)";
366     }else if(status == THREAD_STATUS_PARKED){
367       return "WAITING (parking)";
368     }else if(status == THREAD_STATUS_PARKED_TIMED){
369       return "TIMED_WAITING (parking)";
370     }else if(status == THREAD_STATUS_BLOCKED_ON_MONITOR_ENTER){
371       return "BLOCKED (on object monitor)";
372     }else if(status == THREAD_STATUS_TERMINATED){
373       return "TERMINATED";
374     }
375     return "UNKNOWN";
376   }
377 }