2098 lines · 78.3 KB · Java
RawDownload
/* * Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.example.debug.tty; import com.sun.jdi.*;import com.sun.jdi.connect.Connector;import com.sun.jdi.request.*;import com.sun.tools.example.debug.expr.ExpressionParser;import com.sun.tools.example.debug.expr.ParseException; import java.text.*;import java.util.*;import java.io.*; class Commands {     abstract class AsyncExecution {        abstract void action();         AsyncExecution() {            execute();        }         void execute() {            /*             * Save current thread and stack frame. (BugId 4296031)             */            final ThreadInfo threadInfo = ThreadInfo.getCurrentThreadInfo();            final int stackFrame = threadInfo == null? 0 : threadInfo.getCurrentFrameIndex();            Thread thread = new Thread("asynchronous jdb command") {                    @Override                    public void run() {                        try {                            action();                        } catch (UnsupportedOperationException uoe) {                            //(BugId 4453329)                            MessageOutput.println("Operation is not supported on the target VM");                        } catch (Exception e) {                            MessageOutput.println("Internal exception during operation:",                                                  e.getMessage());                        } finally {                            /*                             * This was an asynchronous command.  Events may have been                             * processed while it was running.  Restore the thread and                             * stack frame the user was looking at.  (BugId 4296031)                             */                            if (threadInfo != null) {                                ThreadInfo.setCurrentThreadInfo(threadInfo);                                try {                                    threadInfo.setCurrentFrameIndex(stackFrame);                                } catch (IncompatibleThreadStateException e) {                                    MessageOutput.println("Current thread isnt suspended.");                                } catch (ArrayIndexOutOfBoundsException e) {                                    MessageOutput.println("Requested stack frame is no longer active:",                                                          new Object []{new Integer(stackFrame)});                                }                            }                            MessageOutput.printPrompt();                        }                    }                };            thread.start();        }    }     Commands() {    }     private Value evaluate(String expr) {        Value result = null;        ExpressionParser.GetFrame frameGetter = null;        try {            final ThreadInfo threadInfo = ThreadInfo.getCurrentThreadInfo();            if ((threadInfo != null) && (threadInfo.getCurrentFrame() != null)) {                frameGetter = new ExpressionParser.GetFrame() {                        @Override                        public StackFrame get() throws IncompatibleThreadStateException {                            return threadInfo.getCurrentFrame();                        }                    };            }            result = ExpressionParser.evaluate(expr, Env.vm(), frameGetter);        } catch (InvocationException ie) {            MessageOutput.println("Exception in expression:",                                  ie.exception().referenceType().name());        } catch (Exception ex) {            String exMessage = ex.getMessage();            if (exMessage == null) {                MessageOutput.printException(exMessage, ex);            } else {                String s;                try {                    s = MessageOutput.format(exMessage);                } catch (MissingResourceException mex) {                    s = ex.toString();                }                MessageOutput.printDirectln(s);// Special case: use printDirectln()            }        }        return result;    }     private String getStringValue() {         Value val = null;         String valStr = null;         try {              val = ExpressionParser.getMassagedValue();              valStr = val.toString();         } catch (ParseException e) {              String msg = e.getMessage();              if (msg == null) {                  MessageOutput.printException(msg, e);              } else {                  String s;                  try {                      s = MessageOutput.format(msg);                  } catch (MissingResourceException mex) {                      s = e.toString();                  }                  MessageOutput.printDirectln(s);              }         }         return valStr;    }     private ThreadInfo doGetThread(String idToken) {        ThreadInfo threadInfo = ThreadInfo.getThreadInfo(idToken);        if (threadInfo == null) {            MessageOutput.println("is not a valid thread id", idToken);        }        return threadInfo;    }     String typedName(Method method) {        StringBuffer buf = new StringBuffer();        buf.append(method.name());        buf.append("(");         List<String> args = method.argumentTypeNames();        int lastParam = args.size() - 1;        // output param types except for the last        for (int ii = 0; ii < lastParam; ii++) {            buf.append(args.get(ii));            buf.append(", ");        }        if (lastParam >= 0) {            // output the last param            String lastStr = args.get(lastParam);            if (method.isVarArgs()) {                // lastParam is an array.  Replace the [] with ...                buf.append(lastStr.substring(0, lastStr.length() - 2));                buf.append("...");            } else {                buf.append(lastStr);            }        }        buf.append(")");        return buf.toString();    }     void commandConnectors(VirtualMachineManager vmm) {        Collection<Connector> ccs = vmm.allConnectors();        if (ccs.isEmpty()) {            MessageOutput.println("Connectors available");        }        for (Connector cc : ccs) {            String transportName =                cc.transport() == null ? "null" : cc.transport().name();            MessageOutput.println();            MessageOutput.println("Connector and Transport name",                                  new Object [] {cc.name(), transportName});            MessageOutput.println("Connector description", cc.description());             for (Connector.Argument aa : cc.defaultArguments().values()) {                    MessageOutput.println();                     boolean requiredArgument = aa.mustSpecify();                    if (aa.value() == null || aa.value() == "") {                        //no current value and no default.                        MessageOutput.println(requiredArgument ?                                              "Connector required argument nodefault" :                                              "Connector argument nodefault", aa.name());                    } else {                        MessageOutput.println(requiredArgument ?                                              "Connector required argument default" :                                              "Connector argument default",                                              new Object [] {aa.name(), aa.value()});                    }                    MessageOutput.println("Connector description", aa.description());                 }            }     }     void commandClasses() {        StringBuffer classList = new StringBuffer();        for (ReferenceType refType : Env.vm().allClasses()) {            classList.append(refType.name());            classList.append("\n");        }        MessageOutput.print("** classes list **", classList.toString());    }     void commandClass(StringTokenizer t) {         if (!t.hasMoreTokens()) {            MessageOutput.println("No class specified.");            return;        }         String idClass = t.nextToken();        boolean showAll = false;         if (t.hasMoreTokens()) {            if (t.nextToken().toLowerCase().equals("all")) {                showAll = true;            } else {                MessageOutput.println("Invalid option on class command");                return;            }        }        ReferenceType type = Env.getReferenceTypeFromToken(idClass);        if (type == null) {            MessageOutput.println("is not a valid id or class name", idClass);            return;        }        if (type instanceof ClassType) {            ClassType clazz = (ClassType)type;            MessageOutput.println("Class:", clazz.name());             ClassType superclass = clazz.superclass();            while (superclass != null) {                MessageOutput.println("extends:", superclass.name());                superclass = showAll ? superclass.superclass() : null;            }             List<InterfaceType> interfaces =                showAll ? clazz.allInterfaces() : clazz.interfaces();            for (InterfaceType interfaze : interfaces) {                MessageOutput.println("implements:", interfaze.name());            }             for (ClassType sub : clazz.subclasses()) {                MessageOutput.println("subclass:", sub.name());            }            for (ReferenceType nest : clazz.nestedTypes()) {                MessageOutput.println("nested:", nest.name());            }        } else if (type instanceof InterfaceType) {            InterfaceType interfaze = (InterfaceType)type;            MessageOutput.println("Interface:", interfaze.name());            for (InterfaceType superinterface : interfaze.superinterfaces()) {                MessageOutput.println("extends:", superinterface.name());            }            for (InterfaceType sub : interfaze.subinterfaces()) {                MessageOutput.println("subinterface:", sub.name());            }            for (ClassType implementor : interfaze.implementors()) {                MessageOutput.println("implementor:", implementor.name());            }            for (ReferenceType nest : interfaze.nestedTypes()) {                MessageOutput.println("nested:", nest.name());            }        } else {  // array type            ArrayType array = (ArrayType)type;            MessageOutput.println("Array:", array.name());        }    }     void commandMethods(StringTokenizer t) {        if (!t.hasMoreTokens()) {            MessageOutput.println("No class specified.");            return;        }         String idClass = t.nextToken();        ReferenceType cls = Env.getReferenceTypeFromToken(idClass);        if (cls != null) {            StringBuffer methodsList = new StringBuffer();            for (Method method : cls.allMethods()) {                methodsList.append(method.declaringType().name());                methodsList.append(" ");                methodsList.append(typedName(method));                methodsList.append('\n');            }            MessageOutput.print("** methods list **", methodsList.toString());        } else {            MessageOutput.println("is not a valid id or class name", idClass);        }    }     void commandFields(StringTokenizer t) {        if (!t.hasMoreTokens()) {            MessageOutput.println("No class specified.");            return;        }         String idClass = t.nextToken();        ReferenceType cls = Env.getReferenceTypeFromToken(idClass);        if (cls != null) {            List<Field> fields = cls.allFields();            List<Field> visible = cls.visibleFields();            StringBuffer fieldsList = new StringBuffer();            for (Field field : fields) {                String s;                if (!visible.contains(field)) {                    s = MessageOutput.format("list field typename and name hidden",                                             new Object [] {field.typeName(),                                                            field.name()});                } else if (!field.declaringType().equals(cls)) {                    s = MessageOutput.format("list field typename and name inherited",                                             new Object [] {field.typeName(),                                                            field.name(),                                                            field.declaringType().name()});                } else {                    s = MessageOutput.format("list field typename and name",                                             new Object [] {field.typeName(),                                                            field.name()});                }                fieldsList.append(s);            }            MessageOutput.print("** fields list **", fieldsList.toString());        } else {            MessageOutput.println("is not a valid id or class name", idClass);        }    }     private void printThreadGroup(ThreadGroupReference tg) {        ThreadIterator threadIter = new ThreadIterator(tg);         MessageOutput.println("Thread Group:", tg.name());        int maxIdLength = 0;        int maxNameLength = 0;        while (threadIter.hasNext()) {            ThreadReference thr = threadIter.next();            maxIdLength = Math.max(maxIdLength,                                   Env.description(thr).length());            maxNameLength = Math.max(maxNameLength,                                     thr.name().length());        }         threadIter = new ThreadIterator(tg);        while (threadIter.hasNext()) {            ThreadReference thr = threadIter.next();            if (thr.threadGroup() == null) {                continue;            }            // Note any thread group changes            if (!thr.threadGroup().equals(tg)) {                tg = thr.threadGroup();                MessageOutput.println("Thread Group:", tg.name());            }             /*             * Do a bit of filling with whitespace to get thread ID             * and thread names to line up in the listing, and also             * allow for proper localization.  This also works for             * very long thread names, at the possible cost of lines             * being wrapped by the display device.             */            StringBuffer idBuffer = new StringBuffer(Env.description(thr));            for (int i = idBuffer.length(); i < maxIdLength; i++) {                idBuffer.append(" ");            }            StringBuffer nameBuffer = new StringBuffer(thr.name());            for (int i = nameBuffer.length(); i < maxNameLength; i++) {                nameBuffer.append(" ");            }             /*             * Select the output format to use based on thread status             * and breakpoint.             */            String statusFormat;            switch (thr.status()) {            case ThreadReference.THREAD_STATUS_UNKNOWN:                if (thr.isAtBreakpoint()) {                    statusFormat = "Thread description name unknownStatus BP";                } else {                    statusFormat = "Thread description name unknownStatus";                }                break;            case ThreadReference.THREAD_STATUS_ZOMBIE:                if (thr.isAtBreakpoint()) {                    statusFormat = "Thread description name zombieStatus BP";                } else {                    statusFormat = "Thread description name zombieStatus";                }                break;            case ThreadReference.THREAD_STATUS_RUNNING:                if (thr.isAtBreakpoint()) {                    statusFormat = "Thread description name runningStatus BP";                } else {                    statusFormat = "Thread description name runningStatus";                }                break;            case ThreadReference.THREAD_STATUS_SLEEPING:                if (thr.isAtBreakpoint()) {                    statusFormat = "Thread description name sleepingStatus BP";                } else {                    statusFormat = "Thread description name sleepingStatus";                }                break;            case ThreadReference.THREAD_STATUS_MONITOR:                if (thr.isAtBreakpoint()) {                    statusFormat = "Thread description name waitingStatus BP";                } else {                    statusFormat = "Thread description name waitingStatus";                }                break;            case ThreadReference.THREAD_STATUS_WAIT:                if (thr.isAtBreakpoint()) {                    statusFormat = "Thread description name condWaitstatus BP";                } else {                    statusFormat = "Thread description name condWaitstatus";                }                break;            default:                throw new InternalError(MessageOutput.format("Invalid thread status."));            }            MessageOutput.println(statusFormat,                                  new Object [] {idBuffer.toString(),                                                 nameBuffer.toString()});        }    }     void commandThreads(StringTokenizer t) {        if (!t.hasMoreTokens()) {            printThreadGroup(ThreadInfo.group());            return;        }        String name = t.nextToken();        ThreadGroupReference tg = ThreadGroupIterator.find(name);        if (tg == null) {            MessageOutput.println("is not a valid threadgroup name", name);        } else {            printThreadGroup(tg);        }    }     void commandThreadGroups() {        ThreadGroupIterator it = new ThreadGroupIterator();        int cnt = 0;        while (it.hasNext()) {            ThreadGroupReference tg = it.nextThreadGroup();            ++cnt;            MessageOutput.println("thread group number description name",                                  new Object [] { new Integer (cnt),                                                  Env.description(tg),                                                  tg.name()});        }    }     void commandThread(StringTokenizer t) {        if (!t.hasMoreTokens()) {            MessageOutput.println("Thread number not specified.");            return;        }        ThreadInfo threadInfo = doGetThread(t.nextToken());        if (threadInfo != null) {            ThreadInfo.setCurrentThreadInfo(threadInfo);        }    }     void commandThreadGroup(StringTokenizer t) {        if (!t.hasMoreTokens()) {            MessageOutput.println("Threadgroup name not specified.");            return;        }        String name = t.nextToken();        ThreadGroupReference tg = ThreadGroupIterator.find(name);        if (tg == null) {            MessageOutput.println("is not a valid threadgroup name", name);        } else {            ThreadInfo.setThreadGroup(tg);        }

Lines 1–500 of 2098.