예제 #1
0
 private void commandMethods(StringTokenizer t) throws NoSessionException {
   if (!t.hasMoreTokens()) {
     env.error("No class specified.");
     return;
   }
   String idClass = t.nextToken();
   ReferenceType cls = findClass(idClass);
   if (cls != null) {
     List<Method> methods = cls.allMethods();
     OutputSink out = env.getOutputSink();
     for (int i = 0; i < methods.size(); i++) {
       Method method = methods.get(i);
       out.print(method.declaringType().name() + " " + method.name() + "(");
       Iterator<String> it = method.argumentTypeNames().iterator();
       if (it.hasNext()) {
         while (true) {
           out.print(it.next());
           if (!it.hasNext()) {
             break;
           }
           out.print(", ");
         }
       }
       out.println(")");
     }
     out.show();
   } else {
     // ### Should validate class name syntax.
     env.failure("\"" + idClass + "\" is not a valid id or class name.");
   }
 }
예제 #2
0
  public void exceptionEvent(ExceptionEvent event) {
    ObjectReference or = event.exception();
    ReferenceType rt = or.referenceType();
    String exceptionName = rt.name();
    // Field messageField = Throwable.class.getField("detailMessage");
    Field messageField = rt.fieldByName("detailMessage");
    //    System.out.println("field " + messageField);
    Value messageValue = or.getValue(messageField);
    //    System.out.println("mess val " + messageValue);

    // "java.lang.ArrayIndexOutOfBoundsException"
    int last = exceptionName.lastIndexOf('.');
    String message = exceptionName.substring(last + 1);
    if (messageValue != null) {
      String messageStr = messageValue.toString();
      if (messageStr.startsWith("\"")) {
        messageStr = messageStr.substring(1, messageStr.length() - 1);
      }
      message += ": " + messageStr;
    }
    //    System.out.println("mess type " + messageValue.type());
    // StringReference messageReference = (StringReference) messageValue.type();

    // First just report the exception and its placement
    reportException(message, or, event.thread());
    // Then try to pretty it up with a better message
    handleCommonErrors(exceptionName, message, listener);

    if (editor != null) {
      editor.deactivateRun();
    }
  }
예제 #3
0
파일: Env.java 프로젝트: NathanEEvans/api
 static ReferenceType getReferenceTypeFromToken(String idToken) {
   ReferenceType cls = null;
   if (Character.isDigit(idToken.charAt(0))) {
     cls = null;
   } else if (idToken.startsWith("*.")) {
     // This notation saves typing by letting the user omit leading
     // package names. The first
     // loaded class whose name matches this limited regular
     // expression is selected.
     idToken = idToken.substring(1);
     for (ReferenceType type : Env.vm().allClasses()) {
       if (type.name().endsWith(idToken)) {
         cls = type;
         break;
       }
     }
   } else {
     // It's a class name
     List<ReferenceType> classes = Env.vm().classesByName(idToken);
     if (classes.size() > 0) {
       // TO DO: handle multiples
       cls = classes.get(0);
     }
   }
   return cls;
 }
예제 #4
0
 private void commandClasses() throws NoSessionException {
   OutputSink out = env.getOutputSink();
   // out.println("** classes list **");
   for (ReferenceType refType : runtime.allClasses()) {
     out.println(refType.name());
   }
   out.show();
 }
예제 #5
0
 public static String getLocationMethodQName(@NotNull Location location) {
   StringBuilder res = new StringBuilder();
   ReferenceType type = location.declaringType();
   if (type != null) {
     res.append(type.name()).append('.');
   }
   res.append(location.method().name());
   return res.toString();
 }
예제 #6
0
파일: Env.java 프로젝트: NathanEEvans/api
 /** Return a description of an object. */
 static String description(ObjectReference ref) {
   ReferenceType clazz = ref.referenceType();
   long id = ref.uniqueID();
   if (clazz == null) {
     return toHex(id);
   } else {
     return MessageOutput.format(
         "object description and hex id", new Object[] {clazz.name(), toHex(id)});
   }
 }
예제 #7
0
 /** ******** test assist ********* */
 Method getMethod(String className, String methodName) {
   List refs = vm().classesByName(className);
   if (refs.size() != 1) {
     failure("Test failure: " + refs.size() + " ReferenceTypes named: " + className);
     return null;
   }
   ReferenceType refType = (ReferenceType) refs.get(0);
   List meths = refType.methodsByName(methodName);
   if (meths.size() != 1) {
     failure("Test failure: " + meths.size() + " methods named: " + methodName);
     return null;
   }
   return (Method) meths.get(0);
 }
예제 #8
0
  public List<ReferenceType> nestedTypes(ReferenceType refType) {
    List<ReferenceType> nestedTypes = myNestedClassesCache.get(refType);
    if (nestedTypes == null) {
      List<ReferenceType> list = Collections.emptyList();
      try {
        list = refType.nestedTypes();
      } catch (Throwable e) {
        // sometimes some strange errors are thrown from JDI. Do not crash debugger because of this.
        // Example:
        // java.lang.StringIndexOutOfBoundsException: String index out of range: 487700285
        //	at java.lang.String.checkBounds(String.java:375)
        //	at java.lang.String.<init>(String.java:415)
        //	at com.sun.tools.jdi.PacketStream.readString(PacketStream.java:392)
        //	at
        // com.sun.tools.jdi.JDWP$VirtualMachine$AllClassesWithGeneric$ClassInfo.<init>(JDWP.java:1644)
        LOG.info(e);
      }
      if (!list.isEmpty()) {
        final Set<ReferenceType> candidates = new HashSet<>();
        final ClassLoaderReference outerLoader = refType.classLoader();
        for (ReferenceType nested : list) {
          try {
            if (outerLoader == null
                ? nested.classLoader() == null
                : outerLoader.equals(nested.classLoader())) {
              candidates.add(nested);
            }
          } catch (ObjectCollectedException ignored) {
          }
        }

        if (!candidates.isEmpty()) {
          // keep only direct nested types
          final Set<ReferenceType> nested2 = new HashSet<>();
          for (final ReferenceType candidate : candidates) {
            nested2.addAll(nestedTypes(candidate));
          }
          candidates.removeAll(nested2);
        }

        nestedTypes = candidates.isEmpty() ? Collections.emptyList() : new ArrayList<>(candidates);
      } else {
        nestedTypes = Collections.emptyList();
      }
      myNestedClassesCache.put(refType, nestedTypes);
    }
    return nestedTypes;
  }
예제 #9
0
  /**
   * @ast method
   * @aspect AccessControl
   * @declaredat /home/uoji/JastAddJ/Java1.4Frontend/AccessControl.jrag:167
   */
  public void accessControl() {
    super.accessControl();

    if (!isCircular()) {
      // 9.1.2
      HashSet set = new HashSet();
      for (int i = 0; i < getNumSuperInterfaceId(); i++) {
        TypeDecl decl = getSuperInterfaceId(i).type();

        if (!decl.isInterfaceDecl() && !decl.isUnknown())
          error(
              "interface " + fullName() + " tries to extend non interface type " + decl.fullName());
        if (!decl.isCircular() && !decl.accessibleFrom(this))
          error(
              "interface " + fullName() + " can not extend non accessible type " + decl.fullName());

        if (set.contains(decl))
          error(
              "extended interface "
                  + decl.fullName()
                  + " mentionened multiple times in extends clause");
        set.add(decl);
      }
    }
  }
예제 #10
0
  public static ReferenceType getSuperClass(
      final String baseQualifiedName, ReferenceType checkedType) {
    if (baseQualifiedName.equals(checkedType.name())) {
      return checkedType;
    }

    if (checkedType instanceof ClassType) {
      ClassType classType = (ClassType) checkedType;
      ClassType superClassType = classType.superclass();
      if (superClassType != null) {
        ReferenceType superClass = getSuperClass(baseQualifiedName, superClassType);
        if (superClass != null) {
          return superClass;
        }
      }
      List<InterfaceType> interfaces = classType.allInterfaces();
      for (InterfaceType iface : interfaces) {
        ReferenceType superClass = getSuperClass(baseQualifiedName, iface);
        if (superClass != null) {
          return superClass;
        }
      }
    }

    if (checkedType instanceof InterfaceType) {
      List<InterfaceType> list = ((InterfaceType) checkedType).superinterfaces();
      for (InterfaceType superInterface : list) {
        ReferenceType superClass = getSuperClass(baseQualifiedName, superInterface);
        if (superClass != null) {
          return superClass;
        }
      }
    }
    return null;
  }
예제 #11
0
 /** Get source object associated with a class or interface. Returns null if not available. */
 public SourceModel sourceForClass(ReferenceType refType) {
   SourceModel sm = classToSource.get(refType);
   if (sm != null) {
     return sm;
   }
   try {
     String filename = refType.sourceName();
     String refName = refType.name();
     int iDot = refName.lastIndexOf('.');
     String pkgName = (iDot >= 0) ? refName.substring(0, iDot + 1) : "";
     String full = pkgName.replace('.', File.separatorChar) + filename;
     File path = sourcePath.resolve(full);
     if (path != null) {
       sm = sourceForFile(path);
       classToSource.put(refType, sm);
       return sm;
     }
     return null;
   } catch (AbsentInformationException e) {
     return null;
   }
 }
예제 #12
0
 private void dump(
     OutputSink out, ObjectReference obj, ReferenceType refType, ReferenceType refTypeBase) {
   for (Field field : refType.fields()) {
     out.print("    ");
     if (!refType.equals(refTypeBase)) {
       out.print(refType.name() + ".");
     }
     out.print(field.name() + ": ");
     Object o = obj.getValue(field);
     out.println((o == null) ? "null" : o.toString()); // Bug ID 4374471
   }
   if (refType instanceof ClassType) {
     ClassType sup = ((ClassType) refType).superclass();
     if (sup != null) {
       dump(out, obj, sup, refTypeBase);
     }
   } else if (refType instanceof InterfaceType) {
     for (InterfaceType sup : ((InterfaceType) refType).superinterfaces()) {
       dump(out, obj, sup, refTypeBase);
     }
   }
 }
예제 #13
0
 /** @apilevel low-level */
 public void flushCache() {
   super.flushCache();
   methodsSignatureMap_computed = false;
   methodsSignatureMap_value = null;
   ancestorMethods_String_values = null;
   memberTypes_String_values = null;
   memberFieldsMap_computed = false;
   memberFieldsMap_value = null;
   memberFields_String_values = null;
   isStatic_computed = false;
   castingConversionTo_TypeDecl_values = null;
   instanceOf_TypeDecl_values = null;
   isCircular_visited = -1;
   isCircular_computed = false;
   isCircular_initialized = false;
   typeDescriptor_computed = false;
   typeDescriptor_value = null;
 }
예제 #14
0
 /**
  * @ast method
  * @aspect TypeHierarchyCheck
  * @declaredat /home/uoji/JastAddJ/Java1.4Frontend/TypeHierarchyCheck.jrag:312
  */
 public void nameCheck() {
   super.nameCheck();
   if (isCircular()) error("circular inheritance dependency in " + typeName());
   else {
     for (int i = 0; i < getNumSuperInterfaceId(); i++) {
       TypeDecl typeDecl = getSuperInterfaceId(i).type();
       if (typeDecl.isCircular()) error("circular inheritance dependency in " + typeName());
     }
   }
   for (Iterator iter = methodsSignatureMap().values().iterator(); iter.hasNext(); ) {
     SimpleSet set = (SimpleSet) iter.next();
     if (set.size() > 1) {
       Iterator i2 = set.iterator();
       MethodDecl m = (MethodDecl) i2.next();
       while (i2.hasNext()) {
         MethodDecl n = (MethodDecl) i2.next();
         if (!n.mayOverrideReturn(m) && !m.mayOverrideReturn(n))
           error(
               "multiply inherited methods with the same signature must have the same return type");
       }
     }
   }
 }
  // copied from FrameVariablesTree
  private void buildVariables(
      DebuggerContextImpl debuggerContext,
      final EvaluationContextImpl evaluationContext,
      @NotNull DebugProcessImpl debugProcess,
      XValueChildrenList children,
      ObjectReference thisObjectReference,
      Location location)
      throws EvaluateException {
    final Set<String> visibleLocals = new HashSet<String>();
    if (NodeRendererSettings.getInstance().getClassRenderer().SHOW_VAL_FIELDS_AS_LOCAL_VARIABLES) {
      if (thisObjectReference != null
          && debugProcess.getVirtualMachineProxy().canGetSyntheticAttribute()) {
        final ReferenceType thisRefType = thisObjectReference.referenceType();
        if (thisRefType instanceof ClassType
            && location != null
            && thisRefType.equals(location.declaringType())
            && thisRefType.name().contains("$")) { // makes sense for nested classes only
          for (Field field : thisRefType.fields()) {
            if (DebuggerUtils.isSynthetic(field)
                && StringUtil.startsWith(
                    field.name(), FieldDescriptorImpl.OUTER_LOCAL_VAR_FIELD_PREFIX)) {
              final FieldDescriptorImpl fieldDescriptor =
                  myNodeManager.getFieldDescriptor(myDescriptor, thisObjectReference, field);
              children.add(JavaValue.create(fieldDescriptor, evaluationContext, myNodeManager));
              visibleLocals.add(fieldDescriptor.calcValueName());
            }
          }
        }
      }
    }

    boolean myAutoWatchMode = DebuggerSettings.getInstance().AUTO_VARIABLES_MODE;
    if (evaluationContext == null) {
      return;
    }
    final SourcePosition sourcePosition = debuggerContext.getSourcePosition();
    if (sourcePosition == null) {
      return;
    }

    try {
      if (!XDebuggerSettingsManager.getInstance().getDataViewSettings().isAutoExpressions()
          && !myAutoWatchMode) {
        // optimization
        superBuildVariables(evaluationContext, children);
      } else {
        final Map<String, LocalVariableProxyImpl> visibleVariables =
            getVisibleVariables(getStackFrameProxy());
        final Pair<Set<String>, Set<TextWithImports>> usedVars =
            ApplicationManager.getApplication()
                .runReadAction(
                    new Computable<Pair<Set<String>, Set<TextWithImports>>>() {
                      @Override
                      public Pair<Set<String>, Set<TextWithImports>> compute() {
                        return findReferencedVars(
                            ContainerUtil.union(visibleVariables.keySet(), visibleLocals),
                            sourcePosition);
                      }
                    });
        // add locals
        if (myAutoWatchMode) {
          for (String var : usedVars.first) {
            LocalVariableProxyImpl local = visibleVariables.get(var);
            if (local != null) {
              children.add(
                  JavaValue.create(
                      myNodeManager.getLocalVariableDescriptor(null, local),
                      evaluationContext,
                      myNodeManager));
            }
          }
        } else {
          superBuildVariables(evaluationContext, children);
        }
        final EvaluationContextImpl evalContextCopy =
            evaluationContext.createEvaluationContext(evaluationContext.getThisObject());
        evalContextCopy.setAutoLoadClasses(false);

        final Set<TextWithImports> extraVars =
            computeExtraVars(usedVars, sourcePosition, evaluationContext);

        // add extra vars
        addToChildrenFrom(extraVars, children, evaluationContext);

        // add expressions
        addToChildrenFrom(usedVars.second, children, evalContextCopy);
      }
    } catch (EvaluateException e) {
      if (e.getCause() instanceof AbsentInformationException) {
        children.add(
            new DummyMessageValueNode(
                MessageDescriptor.LOCAL_VARIABLES_INFO_UNAVAILABLE.getLabel(),
                XDebuggerUIConstants.INFORMATION_MESSAGE_ICON));
        // trying to collect values from variable slots
        try {
          for (Map.Entry<DecompiledLocalVariable, Value> entry :
              LocalVariablesUtil.fetchValues(getStackFrameProxy(), debugProcess).entrySet()) {
            children.add(
                JavaValue.create(
                    myNodeManager.getArgumentValueDescriptor(
                        null, entry.getKey(), entry.getValue()),
                    evaluationContext,
                    myNodeManager));
          }
        } catch (Exception ex) {
          LOG.info(ex);
        }
      } else {
        throw e;
      }
    }
  }
예제 #16
0
 private void commandList(StringTokenizer t) throws NoSessionException {
   ThreadReference current = context.getCurrentThread();
   if (current == null) {
     env.error("No thread specified.");
     return;
   }
   Location loc;
   try {
     StackFrame frame = context.getCurrentFrame(current);
     if (frame == null) {
       env.failure("Thread has not yet begun execution.");
       return;
     }
     loc = frame.location();
   } catch (VMNotInterruptedException e) {
     env.failure("Target VM must be in interrupted state.");
     return;
   }
   SourceModel source = sourceManager.sourceForLocation(loc);
   if (source == null) {
     if (loc.method().isNative()) {
       env.failure("Current method is native.");
       return;
     }
     env.failure("No source available for " + Utils.locationString(loc) + ".");
     return;
   }
   ReferenceType refType = loc.declaringType();
   int lineno = loc.lineNumber();
   if (t.hasMoreTokens()) {
     String id = t.nextToken();
     // See if token is a line number.
     try {
       lineno = Integer.valueOf(id).intValue();
     } catch (NumberFormatException nfe) {
       // It isn't -- see if it's a method name.
       List<Method> meths = refType.methodsByName(id);
       if (meths == null || meths.size() == 0) {
         env.failure(
             id + " is not a valid line number or " + "method name for class " + refType.name());
         return;
       } else if (meths.size() > 1) {
         env.failure(id + " is an ambiguous method name in" + refType.name());
         return;
       }
       loc = meths.get(0).location();
       lineno = loc.lineNumber();
     }
   }
   int startLine = (lineno > 4) ? lineno - 4 : 1;
   int endLine = startLine + 9;
   String sourceLine = source.sourceLine(lineno);
   if (sourceLine == null) {
     env.failure("" + lineno + " is an invalid line number for " + refType.name());
   } else {
     OutputSink out = env.getOutputSink();
     for (int i = startLine; i <= endLine; i++) {
       sourceLine = source.sourceLine(i);
       if (sourceLine == null) {
         break;
       }
       out.print(i);
       out.print("\t");
       if (i == lineno) {
         out.print("=> ");
       } else {
         out.print("   ");
       }
       out.println(sourceLine);
     }
     out.show();
   }
 }
예제 #17
0
 /**
  * @ast method
  * @aspect Modifiers
  * @declaredat /home/uoji/JastAddJ/Java1.4Frontend/Modifiers.jrag:104
  */
 public void checkModifiers() {
   super.checkModifiers();
 }
예제 #18
0
  /**
   * @ast method
   * @aspect GenerateClassfile
   * @declaredat /home/uoji/JastAddJ/Java1.4Backend/GenerateClassfile.jrag:142
   */
  public void generateClassfile() {
    super.generateClassfile();
    String fileName = destinationPath() + File.separator + constantPoolName() + ".class";
    if (options().verbose()) System.out.println("Writing class file to " + fileName);
    try {
      ConstantPool cp = constantPool();
      // force building of constant pool
      cp.addClass(constantPoolName());
      cp.addClass("java/lang/Object");
      for (int i = 0; i < getNumSuperInterfaceId(); i++) {
        cp.addClass(getSuperInterfaceId(i).type().constantPoolName());
      }
      for (Iterator iter = bcFields().iterator(); iter.hasNext(); ) {
        FieldDeclaration field = (FieldDeclaration) iter.next();
        cp.addUtf8(field.name());
        cp.addUtf8(field.type().typeDescriptor());
        field.attributes();
      }
      for (Iterator iter = bcMethods().iterator(); iter.hasNext(); ) {
        Object obj = iter.next();
        if (obj instanceof MethodDecl) {
          MethodDecl m = (MethodDecl) obj;
          cp.addUtf8(m.name());
          cp.addUtf8(m.descName());
          m.attributes();
        }
      }
      attributes();

      if (hasClinit()) {
        cp.addUtf8("<clinit>");
        cp.addUtf8("()V");
        clinit_attributes();
      }

      // actual classfile generation
      File dest = new File(fileName);
      File parentFile = dest.getParentFile();
      if (parentFile != null) parentFile.mkdirs();

      FileOutputStream f = new FileOutputStream(fileName);
      DataOutputStream out = new DataOutputStream(new BufferedOutputStream(f));
      out.writeInt(magicHeader());
      out.writeChar(minorVersion());
      out.writeChar(majorVersion());
      cp.emit(out);
      int flags = flags();
      if (isNestedType()) flags = mangledFlags(flags);
      if (isInterfaceDecl()) flags |= Modifiers.ACC_INTERFACE;
      out.writeChar(flags);
      out.writeChar(cp.addClass(constantPoolName()));
      out.writeChar(cp.addClass("java/lang/Object"));
      if (getNumSuperInterfaceId() == 1 && getSuperInterfaceId(0).type().isObject())
        out.writeChar(0);
      else out.writeChar(getNumSuperInterfaceId());
      for (int i = 0; i < getNumSuperInterfaceId(); i++) {
        TypeDecl typeDecl = getSuperInterfaceId(i).type();
        if (typeDecl.isInterfaceDecl()) out.writeChar(cp.addClass(typeDecl.constantPoolName()));
      }
      Collection fields = bcFields();
      out.writeChar(fields.size());
      for (Iterator iter = fields.iterator(); iter.hasNext(); ) {
        FieldDeclaration field = (FieldDeclaration) iter.next();
        out.writeChar(field.flags());
        out.writeChar(cp.addUtf8(field.name()));
        out.writeChar(cp.addUtf8(field.type().typeDescriptor()));
        out.writeChar(field.attributes().size());
        for (Iterator itera = field.attributes().iterator(); itera.hasNext(); )
          ((Attribute) itera.next()).emit(out);
      }
      Collection methods = bcMethods();
      out.writeChar(methods.size() + (hasClinit() ? 1 : 0));
      for (Iterator iter = methods.iterator(); iter.hasNext(); ) {
        BodyDecl b = (BodyDecl) iter.next();
        b.generateMethod(out, cp);
      }
      if (hasClinit()) {
        out.writeChar(Modifiers.ACC_STATIC);
        out.writeChar(cp.addUtf8("<clinit>"));
        out.writeChar(cp.addUtf8("()V"));
        out.writeChar(clinit_attributes().size());
        for (Iterator itera = clinit_attributes().iterator(); itera.hasNext(); )
          ((Attribute) itera.next()).emit(out);
      }
      out.writeChar(attributes().size());
      for (Iterator itera = attributes().iterator(); itera.hasNext(); )
        ((Attribute) itera.next()).emit(out);

      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #19
0
 /** @apilevel internal */
 public void flushCollectionCache() {
   super.flushCollectionCache();
 }