/**
  * Returns whether or not this is a standard main method (static, name is 'main', and one argument
  * of string array
  */
 public static boolean is_main(MethodGen mg) {
   Type[] arg_types = mg.getArgumentTypes();
   return (mg.isStatic()
       && mg.getName().equals("main")
       && (arg_types.length == 1)
       && arg_types[0].equals(string_array));
 }
 public SearchResult run(RSClient data, HashMap<String, ClassGen> classes) {
   for (ClassGen c : classes.values()) {
     ConstantPoolGen cpg = c.getConstantPool();
     if (cpg.lookupFloat(16384.0000f) != -1) {
       for (Method m : c.getMethods()) {
         if (m.isStatic()) {
           MethodGen gen = new MethodGen(m, c.getClassName(), cpg);
           InstructionList il = gen.getInstructionList();
           if (il == null) continue;
           InstructionFinder f = new InstructionFinder(il);
           Iterator e = f.search("GETSTATIC LDC FSUB PUTSTATIC");
           if (e.hasNext()) {
             InstructionHandle[] handles = (InstructionHandle[]) e.next();
             data.addField(
                 "MapAngle",
                 ((GETSTATIC) handles[0].getInstruction()).getClassName(cpg)
                     + "."
                     + ((GETSTATIC) handles[0].getInstruction()).getFieldName(cpg));
             return SearchResult.Success;
           }
         }
       }
     }
   }
   return SearchResult.Failure;
 }
示例#3
0
  /**
   * Returns true iff mgen is a constructor
   *
   * @return true iff mgen is a constructor
   */
  private boolean is_constructor(MethodGen mgen) {

    if (mgen.getName().equals("<init>") || mgen.getName().equals("")) {
      // log ("method '%s' is a constructor%n", mgen.getName());
      return (true);
    } else return (false);
  }
  /**
   * Runs through specified class and find index of method specified by methodName. The index is
   * than used as key to obtain handlers. Note: Not the best solution
   *
   * @param fullyQualifiedClassName
   * @param methodName
   * @return
   */
  private InstructionList provideHandlersToMethod(
      String fullyQualifiedClassName, String methodName) {

    InstructionList handlers = null;
    try {
      JavaClass cl = Repository.lookupClass(fullyQualifiedClassName);
      ClassGen cg = new ClassGen(cl);
      Method[] methods = cg.getMethods();
      int methodIndex = 0;
      for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().equals(methodName)) {
          methodIndex = i;
        }
      }
      MethodGen mg = new MethodGen(cg.getMethodAt(methodIndex), null, cg.getConstantPool());
      handlers = mg.getInstructionList();

    } catch (ClassNotFoundException ex) {
      Logger.getLogger(BugPatternDetectorImpl.class.getName())
          .log(
              Level.SEVERE,
              "The method "
                  + methodName
                  + " was not found in "
                  + fullyQualifiedClassName
                  + " class.");
    }
    return handlers;
  }
示例#5
0
 Method generate(String currentClass, ConstantPoolGen cpg) {
   InstructionList il = new InstructionList();
   int instanceOffset = 0;
   short flags = Constants.ACC_PUBLIC;
   if (invokeKind != INVOKESTATIC) {
     instanceOffset = 1;
     il.append(InstructionFactory.createThis());
   } else {
     flags |= Constants.ACC_STATIC;
   }
   int pos = 0;
   for (int i = 0; i < args.length; i++) {
     il.append(InstructionFactory.createLoad(args[i], pos + instanceOffset));
     pos += args[i].getSize();
   }
   il.append(
       new InstructionFactory(cpg)
           .createInvoke(targetClass, methodName, returnType, args, invokeKind));
   il.append(InstructionFactory.createReturn(returnType));
   MethodGen newMethod =
       new MethodGen(
           flags, returnType, args, /*argNames*/ null, accessorName, currentClass, il, cpg);
   newMethod.setMaxLocals();
   newMethod.setMaxStack();
   return newMethod.getMethod();
 }
示例#6
0
  @Override
  public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock, LockSet fact)
      throws DataflowAnalysisException {

    Instruction ins = handle.getInstruction();
    short opcode = ins.getOpcode();
    if (opcode == Constants.MONITORENTER || opcode == Constants.MONITOREXIT) {
      ValueNumberFrame frame = vnaDataflow.getFactAtLocation(new Location(handle, basicBlock));

      modifyLock(frame, fact, opcode == Constants.MONITORENTER ? 1 : -1);

    } else if (opcode == Constants.INVOKEVIRTUAL || opcode == Constants.INVOKEINTERFACE) {

      InvokeInstruction inv = (InvokeInstruction) ins;
      String name = inv.getMethodName(methodGen.getConstantPool());
      String sig = inv.getSignature(methodGen.getConstantPool());
      ValueNumberFrame frame = vnaDataflow.getFactAtLocation(new Location(handle, basicBlock));

      if ("()V".equals(sig) && ("lock".equals(name) || "lockInterruptibly".equals(name))) {
        modifyLock(frame, fact, 1);
      } else if ("()V".equals(sig) && ("unlock".equals(name))) {
        modifyLock(frame, fact, -1);
      }

    } else if ((ins instanceof ReturnInstruction) && isSynchronized && !isStatic) {

      lockOp(fact, vna.getThisValue().getNumber(), -1);
    }
  }
示例#7
0
  public static void main(String[] argv) throws Exception {
    JavaClass clazz = null;

    if ((clazz = Repository.lookupClass(argv[0])) == null) {
      clazz = new ClassParser(argv[0]).parse(); // May throw IOException
    }

    ClassGen cg = new ClassGen(clazz);

    Method[] methods = clazz.getMethods();

    for (int i = 0; i < methods.length; i++) {
      MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cg.getConstantPool());
      cg.replaceMethod(methods[i], mg.getMethod());
    }

    Field[] fields = clazz.getFields();

    for (int i = 0; i < fields.length; i++) {
      FieldGen fg = new FieldGen(fields[i], cg.getConstantPool());
      cg.replaceField(fields[i], fg.getField());
    }

    cg.getJavaClass().dump(clazz.getClassName() + ".clazz");
  }
示例#8
0
  private void createMethod(Element method) throws IllegalXMLVMException {
    il = new InstructionList();
    instructionHandlerManager = new InstructionHandlerManager(il);
    String methodName = method.getAttributeValue("name");

    Element signature = method.getChild("signature", nsXMLVM);
    Type retType = collectReturnType(signature);
    Type[] argTypes = collectArgumentTypes(signature);
    short accessFlags = getAccessFlags(method);

    if (methodName.equals(
        ".cctor")) // Same concept, different names in .net/JVM.  Note we are doing init of statics
                   // for a class
    {
      System.out.println("Changed name to clinit");
      methodName = "<clinit>";
      accessFlags = 0x8; // static
    }

    MethodGen m =
        new MethodGen(
            accessFlags, retType, argTypes, null, methodName, fullQualifiedClassName, il, _cp);
    Element code = method.getChild("code", nsXMLVM);
    createCode(code);
    instructionHandlerManager.checkConsistency();
    m.setMaxLocals();
    m.setMaxStack();
    _cg.addMethod(m.getMethod());
    il.dispose();
  }
示例#9
0
  CFG createCFG(String className) throws ClassNotFoundException {
    CFG cfg = new CFG();
    JavaClass jc = Repository.lookupClass(className);
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cpg = cg.getConstantPool();
    for (Method m : cg.getMethods()) {
      MethodGen mg = new MethodGen(m, cg.getClassName(), cpg);
      InstructionList il = mg.getInstructionList();
      InstructionHandle[] handles = il.getInstructionHandles();
      int prev = 0;
      for (InstructionHandle ih : handles) {
        int position = ih.getPosition();
        cfg.addNode(position, m, jc);
        Instruction inst = ih.getInstruction();

        boolean br = inst.getName().contains("if") || inst.getName().contains("goto");
        boolean ret = inst.getName().contains("return");
        boolean stat = inst.getName().contains("invokestatic");
        int len = inst.getLength();

        if (stat) {
          int index = inst.toString(true).indexOf(" ");
          String name = inst.toString(true).substring(index + 1);
          int tar = Integer.valueOf(name);
          INVOKESTATIC inv = new INVOKESTATIC(tar);
          name = inv.getMethodName(cpg);

          Method m2 = null;
          Method[] tm = cg.getMethods();
          for (int i = 0; i < tm.length; i++) {
            if (tm[i].getName().equals(name)) {
              m2 = tm[i];
            }
          }
          cfg.addEdge(position, m, jc, 0, m2, jc);
          cfg.addEdge(-1, m2, jc, position + len, m, jc);
        }

        if (!ret && !stat) {
          cfg.addEdge(position, position + len, m, jc);
        }
        if (br) {
          cfg.addEdge(position, position + len, m, jc);
          IF_ICMPGE comp = new IF_ICMPGE(ih);
          String name = comp.getTarget().toString(false);
          int index = name.indexOf(">");
          name = name.substring(index + 2);
          int tar = Integer.valueOf(name);
          cfg.addEdge(position, tar, m, jc);
        }
        if (ret) {
          cfg.addEdge(position, -1, m, jc);
        }

        prev = position;
      }
      System.out.println(cfg.toString());
    }
    return cfg;
  }
  /**
   * Remove the local variable type table attribute (LVTT) from mg. Evidently some changes require
   * this to be updated, but without BCEL support that would be hard to do. It should be safe to
   * just delete it since it is optional and really only of use to a debugger.
   */
  public static void remove_local_variable_type_tables(MethodGen mg) {

    for (Attribute a : mg.getCodeAttributes()) {
      if (is_local_variable_type_table(a, mg.getConstantPool())) {
        mg.removeCodeAttribute(a);
      }
    }
  }
  /**
   * Empties the method of all code (except for a return). This includes line numbers, exceptions,
   * local variables, etc.
   */
  public static void empty_method(MethodGen mg) {

    mg.setInstructionList(new InstructionList(new RETURN()));
    mg.removeExceptionHandlers();
    mg.removeLineNumbers();
    mg.removeLocalVariables();
    mg.setMaxLocals();
  }
  /** Return a description of the local variables (one per line) */
  public static String local_var_descr(MethodGen mg) {

    String out = String.format("Locals for %s [cnt %d]\n", mg, mg.getMaxLocals());
    LocalVariableGen[] lvgs = mg.getLocalVariables();
    if ((lvgs != null) && (lvgs.length > 0)) {
      for (LocalVariableGen lvg : lvgs)
        out += String.format("  %s [index %d]\n", lvg, lvg.getIndex());
    }
    return (out);
  }
示例#13
0
  private Method generateSuperAccessor(
      ConstantPoolGen cpg,
      String className,
      SuperMethodDescriptor superMethod,
      InstructionFactory factory) {
    int endPos = superMethod.signature.indexOf(')');
    String segment = superMethod.signature.substring(1, endPos);
    String[] typeNames = (segment.length() > 0) ? segment.split(",") : new String[0];
    Type[] argTypes = new Type[typeNames.length];
    for (int i = 0; i < argTypes.length; i++) argTypes[i] = Type.getType(typeNames[i]);

    int index = superMethod.signature.lastIndexOf(')') + 1;
    Type returnType = Type.getType(superMethod.signature.substring(index));

    Type baseType = new ObjectType(className);
    Type[] wrapperTypes = new Type[argTypes.length + 1];
    System.arraycopy(argTypes, 0, wrapperTypes, 1, argTypes.length);
    wrapperTypes[0] = baseType;
    String[] argNames = new String[wrapperTypes.length];
    for (int i = 0; i < argNames.length; i++) {
      argNames[i] = "arg" + i;
    }
    InstructionList il = new InstructionList();
    MethodGen mg =
        new MethodGen(
            (Constants.ACC_PUBLIC | Constants.ACC_STATIC),
            returnType,
            wrapperTypes,
            argNames,
            OT_PREFIX + superMethod.methodName + "$super",
            className,
            il,
            cpg);
    il.append(InstructionFactory.createLoad(baseType, 0)); // first argument is base instance
    for (int i = 0; i < argTypes.length; i++)
      il.append(InstructionFactory.createLoad(argTypes[i], i + 1));

    // if super method is also callin bound directly invoke the orig-version
    // (to avoid that BaseMethodTransformation.checkReplaceWickedSuper() has to rewrite this code
    // again):
    String methodName =
        (CallinBindingManager.isBoundBaseMethod(
                superMethod.superClass, superMethod.methodName, superMethod.signature))
            ? genOrigMethName(superMethod.methodName)
            : superMethod.methodName;

    il.append(
        factory.createInvoke(
            superMethod.superClass, methodName, returnType, argTypes, INVOKESPECIAL));
    il.append(InstructionFactory.createReturn(returnType));
    mg.setMaxStack();
    mg.setMaxLocals();
    return mg.getMethod();
  }
  @Override
  public MethodGen analyseInternal(final MethodGen methodGen) {
    assert methodGen != null : "Parameter 'methodGen' of method 'analyseInternal' must not be null";

    if (!methodGen.getMethod().isAbstract() && null != methodGen.getInstructionList()) {
      final List<InstructionHandle> instnsHandleList =
          Arrays.asList(methodGen.getInstructionList().getInstructionHandles());
      instnsHandleList.forEach(t -> analyseAsVisiting(t, methodGen));
      return methodGen;
    }
    return null;
  }
  /**
   * Transforms the init method to create the newly added join point member field.
   *
   * @param cp the ConstantPoolGen
   * @param cg the ClassGen
   * @param init the constructor for the class
   * @param method the current method
   * @param factory the objectfactory
   * @param methodSequence the methods sequence number
   * @return the modified constructor
   */
  private MethodGen createJoinPointField(
      final ConstantPoolGen cp,
      final ClassGen cg,
      final Method init,
      final Method method,
      final InstructionFactory factory,
      final int methodSequence) {

    final MethodGen mg = new MethodGen(init, cg.getClassName(), cp);
    final InstructionList il = mg.getInstructionList();
    final InstructionHandle[] ihs = il.getInstructionHandles();

    // grab the handle to the the return instruction of the constructor
    InstructionHandle ih = ihs[0];
    for (int i = 0; i < ihs.length; i++) {
      Instruction instruction = ihs[i].getInstruction();
      if (instruction instanceof ReturnInstruction) {
        ih = ihs[i]; // set the instruction handle to the return instruction
        break;
      }
    }

    final String joinPoint = getJoinPointName(method, methodSequence);

    final InstructionHandle ihPost;
    ihPost = il.insert(ih, factory.createLoad(Type.OBJECT, 0));
    il.insert(ih, factory.createNew(TransformationUtil.THREAD_LOCAL_CLASS));

    il.insert(ih, InstructionConstants.DUP);

    il.insert(
        ih,
        factory.createInvoke(
            TransformationUtil.THREAD_LOCAL_CLASS,
            "<init>",
            Type.VOID,
            new Type[] {},
            Constants.INVOKESPECIAL));

    il.insert(
        ih,
        factory.createFieldAccess(
            cg.getClassName(),
            joinPoint,
            new ObjectType(TransformationUtil.THREAD_LOCAL_CLASS),
            Constants.PUTFIELD));
    il.redirectBranches(ih, ihPost);

    mg.setMaxStack();
    mg.setMaxLocals();

    return mg;
  }
示例#16
0
 public LockAnalysis(MethodGen methodGen, ValueNumberDataflow vnaDataflow, DepthFirstSearch dfs) {
   super(dfs);
   this.methodGen = methodGen;
   this.vnaDataflow = vnaDataflow;
   this.vna = vnaDataflow.getAnalysis();
   this.isSynchronized = methodGen.isSynchronized();
   this.isStatic = methodGen.isStatic();
   if (DEBUG) {
     System.out.println(
         "Analyzing Locks in " + methodGen.getClassName() + "." + methodGen.getName());
   }
 }
示例#17
0
  /** Start the method's visit. */
  public void start() {
    if (!mg.isAbstract() && !mg.isNative()) {
      for (InstructionHandle ih = mg.getInstructionList().getStart();
          ih != null;
          ih = ih.getNext()) {
        Instruction i = ih.getInstruction();

        if (!visitInstruction(i)) i.accept(this);
      }
      updateExceptionHandlers();
    }
  }
  @Override
  public void visitClassContext(ClassContext classContext) {
    JavaClass javaClass = classContext.getJavaClass();

    Method[] methodList = javaClass.getMethods();

    for (Method m : methodList) {
      MethodGen methodGen = classContext.getMethodGen(m);

      if (DEBUG) {
        System.out.println(">>> Method: " + m.getName());
      }

      // To suspect that an invalid String representation is being build,
      // we identify the construction of a MessageDigest and
      // the use of a function that trim leading 0.
      boolean invokeMessageDigest = false;
      boolean invokeToHexString = false;

      ConstantPoolGen cpg = classContext.getConstantPoolGen();
      if (methodGen == null || methodGen.getInstructionList() == null) {
        continue; // No instruction .. nothing to do
      }
      for (Iterator itIns = methodGen.getInstructionList().iterator(); itIns.hasNext(); ) {
        Instruction inst = ((InstructionHandle) itIns.next()).getInstruction();
        if (DEBUG) {
          ByteCode.printOpCode(inst, cpg);
        }

        if (inst instanceof INVOKEVIRTUAL) { // MessageDigest.digest is called
          INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst;
          if ("java.security.MessageDigest".equals(invoke.getClassName(cpg))
              && "digest".equals(invoke.getMethodName(cpg))) {
            invokeMessageDigest = true;
          }
        } else if (inst instanceof INVOKESTATIC
            && invokeMessageDigest) { // The conversion must occurs after the digest was created
          INVOKESTATIC invoke = (INVOKESTATIC) inst;
          if ("java.lang.Integer".equals(invoke.getClassName(cpg))
              && "toHexString".equals(invoke.getMethodName(cpg))) {
            invokeToHexString = true;
          }
        }
      }

      if (invokeMessageDigest && invokeToHexString) {
        bugReporter.reportBug(
            new BugInstance(this, BAD_HEXA_CONVERSION_TYPE, Priorities.NORMAL_PRIORITY) //
                .addClassAndMethod(javaClass, m));
      }
    }
  }
示例#19
0
文件: BCEL.java 项目: tempbottle/ASM
 byte[] nullAdaptClass(final InputStream is, final String name) throws Exception {
   JavaClass jc = new ClassParser(is, name + ".class").parse();
   ClassGen cg = new ClassGen(jc);
   String cName = cg.getClassName();
   ConstantPoolGen cp = cg.getConstantPool();
   Method[] ms = cg.getMethods();
   for (int j = 0; j < ms.length; ++j) {
     MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
     boolean lv = ms[j].getLocalVariableTable() == null;
     boolean ln = ms[j].getLineNumberTable() == null;
     if (lv) {
       mg.removeLocalVariables();
     }
     if (ln) {
       mg.removeLineNumbers();
     }
     mg.stripAttributes(skipDebug);
     InstructionList il = mg.getInstructionList();
     if (il != null) {
       InstructionHandle ih = il.getStart();
       while (ih != null) {
         ih = ih.getNext();
       }
       if (compute) {
         mg.setMaxStack();
         mg.setMaxLocals();
       }
     }
     cg.replaceMethod(ms[j], mg.getMethod());
   }
   return cg.getJavaClass().getBytes();
 }
示例#20
0
  private void createMethod_0() {
    InstructionList il = new InstructionList();
    MethodGen method =
        new MethodGen(
            ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", objectType, il, _cp);

    InstructionHandle ih_0 = il.append(_factory.createLoad(Type.OBJECT, 0));
    il.append(
        _factory.createInvoke(
            "java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
    InstructionHandle ih_4 = il.append(_factory.createReturn(Type.VOID));
    method.setMaxStack();
    method.setMaxLocals();
    _cg.addMethod(method.getMethod());
    il.dispose();
  }
  /**
   * Builds an array of line numbers for the specified instruction list. Each opcode is assigned the
   * next source line number starting at 1000.
   */
  public static void add_line_numbers(MethodGen mg, InstructionList il) {

    il.setPositions(true);
    for (InstructionHandle ih : il.getInstructionHandles()) {
      mg.addLineNumber(ih, 1000 + ih.getPosition());
    }
  }
示例#22
0
 /**
  * TODO
  *
  * @param mg
  */
 public StackTypes(MethodGen mg) {
   InstructionList il = mg.getInstructionList();
   int size = 0;
   if (il != null) size = il.getEnd().getPosition();
   os_arr = new OperandStack[size + 1];
   if (track_locals) loc_arr = new LocalVariables[size + 1];
 }
  /**
   * If this is a putfield or putstatic instruction, check to see if the field is @NonNull, and
   * treat it as dereferences.
   *
   * @param location the Location of the instruction
   * @param vnaFrame the ValueNumberFrame at the Location of the instruction
   * @param fact the dataflow value to modify
   * @throws DataflowAnalysisException
   */
  private void checkNonNullPutField(
      Location location, ValueNumberFrame vnaFrame, UnconditionalValueDerefSet fact)
      throws DataflowAnalysisException {
    INullnessAnnotationDatabase database =
        AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase();

    FieldInstruction fieldIns = (FieldInstruction) location.getHandle().getInstruction();

    XField field = XFactory.createXField(fieldIns, methodGen.getConstantPool());
    char firstChar = field.getSignature().charAt(0);
    if (firstChar != 'L' && firstChar != '[') {
      return;
    }
    NullnessAnnotation resolvedAnnotation = database.getResolvedAnnotation(field, true);
    if (resolvedAnnotation == NullnessAnnotation.NONNULL) {
      IsNullValueFrame invFrame = invDataflow.getFactAtLocation(location);
      if (!invFrame.isValid()) {
        return;
      }
      IsNullValue value = invFrame.getTopValue();
      if (reportDereference(value)) {
        ValueNumber vn = vnaFrame.getTopValue();
        fact.addDeref(vn, location);
      }
    }
  }
示例#24
0
  /** Instrument the specified method to replace mapped calls. */
  public void instrument_method(Method m, MethodGen mg) {

    // Loop through each instruction, making substitutions
    InstructionList il = mg.getInstructionList();
    for (InstructionHandle ih = il.getStart(); ih != null; ) {
      if (debug_instrument_inst.enabled()) {
        debug_instrument_inst.log("instrumenting instruction %s%n", ih);
        // ih.getInstruction().toString(pool.getConstantPool()));
      }
      InstructionList new_il = null;

      // Remember the next instruction to process
      InstructionHandle next_ih = ih.getNext();

      // Get the translation for this instruction (if any)
      new_il = xform_inst(mg, ih.getInstruction());
      if (debug_instrument_inst.enabled()) debug_instrument_inst.log("  new inst: %s%n", new_il);

      // If this instruction was modified, replace it with the new
      // instruction list. If this instruction was the target of any
      // jumps or line numbers , replace them with the first
      // instruction in the new list
      replace_instructions(il, ih, new_il);

      ih = next_ih;
    }
  }
示例#25
0
  /**
   * Generates a setter method for the field described by 'fd' in the class 'class_name'.
   *
   * @param cpg the ConstantPoolGen of the class
   * @param class_name the name of the class
   * @param fd the FieldDescriptor describing the affected field
   * @param factory an InstructionFactory for this class
   * @return the generated getter method
   */
  private Method generateSetter(
      ConstantPoolGen cpg, String class_name, FieldDescriptor fd, InstructionFactory factory) {
    String fieldName = fd.getFieldName();
    Type fieldType = Type.getType(fd.getFieldSignature());
    Type baseType = new ObjectType(class_name);

    Type[] argumentTypes;
    String[] argumentNames;
    if (fd.isStaticField()) {
      argumentTypes = new Type[] {fieldType};
      argumentNames = new String[] {"new_value"};
    } else {
      argumentTypes = new Type[] {baseType, fieldType};
      argumentNames = new String[] {"base_obj", "new_value"};
    }

    InstructionList il = new InstructionList();
    MethodGen mg =
        new MethodGen(
            (Constants.ACC_PUBLIC | Constants.ACC_STATIC),
            Type.VOID,
            argumentTypes,
            argumentNames,
            OT_PREFIX + "set$" + fieldName,
            class_name,
            il,
            cpg);

    int argumentPosition; // position for the argument holding the new field value.
    if (!fd.isStaticField()) {
      il.append(
          InstructionFactory.createLoad(
              baseType, 0)); // first argument is at slot 0 in static methods
      argumentPosition = 1;
    } else {
      argumentPosition = 0;
    }
    il.append(InstructionFactory.createLoad(fieldType, argumentPosition));
    short fieldKind = fd.isStaticField() ? Constants.PUTSTATIC : Constants.PUTFIELD;
    il.append(factory.createFieldAccess(class_name, fieldName, fieldType, fieldKind));
    il.append(InstructionFactory.createReturn(Type.VOID));

    mg.removeNOPs();
    mg.setMaxStack();
    mg.setMaxLocals();
    return mg.getMethod();
  }
  /**
   * Adds a prefix to the original method. To make it callable only from within the framework
   * itself.
   *
   * @param mg the MethodGen
   * @param method the current method
   * @param methodSequence the methods sequence number
   * @param uuid the definition UUID
   * @return the modified method
   */
  private Method addPrefixToMethod(
      final MethodGen mg, final Method method, final int methodSequence, final String uuid) {

    // change the method access flags (should always be set to protected)
    int accessFlags = mg.getAccessFlags();
    if ((accessFlags & Constants.ACC_PROTECTED) == 0) {
      // set the protected flag
      accessFlags |= Constants.ACC_PROTECTED;
    }
    if ((accessFlags & Constants.ACC_PRIVATE) != 0) {
      // clear the private flag
      accessFlags &= ~Constants.ACC_PRIVATE;
    }
    if ((accessFlags & Constants.ACC_PUBLIC) != 0) {
      // clear the public flag
      accessFlags &= ~Constants.ACC_PUBLIC;
    }

    mg.setName(getPrefixedMethodName(method, methodSequence, mg.getClassName()));

    mg.setAccessFlags(accessFlags);

    mg.setMaxStack();
    mg.setMaxLocals();

    return mg.getMethod();
  }
示例#27
0
  /** Visit the method's exception handlers. */
  private void updateExceptionHandlers() {
    CodeExceptionGen[] handlers = mg.getExceptionHandlers();

    /* Measuring decision: couple exceptions */
    for (int i = 0; i < handlers.length; i++) {
      Type t = handlers[i].getCatchType();
      if (t != null) cv.registerCoupling(t);
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * edu.umd.cs.findbugs.classfile.IAnalysisEngine#analyze(edu.umd.cs.findbugs
   * .classfile.IAnalysisCache, java.lang.Object)
   */
  public LoadedFieldSet analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor)
      throws CheckedAnalysisException {
    MethodGen methodGen = getMethodGen(analysisCache, descriptor);
    if (methodGen == null) return null;
    InstructionList il = methodGen.getInstructionList();

    LoadedFieldSet loadedFieldSet = new LoadedFieldSet(methodGen);
    ConstantPoolGen cpg = getConstantPoolGen(analysisCache, descriptor.getClassDescriptor());

    for (InstructionHandle handle = il.getStart(); handle != null; handle = handle.getNext()) {
      Instruction ins = handle.getInstruction();
      short opcode = ins.getOpcode();
      try {
        if (opcode == Constants.INVOKESTATIC) {
          INVOKESTATIC inv = (INVOKESTATIC) ins;
          if (Hierarchy.isInnerClassAccess(inv, cpg)) {
            InnerClassAccess access = Hierarchy.getInnerClassAccess(inv, cpg);
            /*
             * if (access == null) {
             * System.out.println("Missing inner class access in " +
             * SignatureConverter.convertMethodSignature(methodGen)
             * + " at " + inv); }
             */
            if (access != null) {
              if (access.isLoad()) loadedFieldSet.addLoad(handle, access.getField());
              else loadedFieldSet.addStore(handle, access.getField());
            }
          }
        } else if (fieldInstructionOpcodeSet.get(opcode)) {
          boolean isLoad = (opcode == Constants.GETFIELD || opcode == Constants.GETSTATIC);
          XField field = Hierarchy.findXField((FieldInstruction) ins, cpg);
          if (field != null) {
            if (isLoad) loadedFieldSet.addLoad(handle, field);
            else loadedFieldSet.addStore(handle, field);
          }
        }
      } catch (ClassNotFoundException e) {
        AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(e);
      }
    }

    return loadedFieldSet;
  }
 /**
  * If this is a method call instruction, check to see if any of the parameters are @NonNull, and
  * treat them as dereferences.
  *
  * @param location the Location of the instruction
  * @param vnaFrame the ValueNumberFrame at the Location of the instruction
  * @param fact the dataflow value to modify
  * @throws DataflowAnalysisException
  */
 private void checkNonNullParams(
     Location location, ValueNumberFrame vnaFrame, UnconditionalValueDerefSet fact)
     throws DataflowAnalysisException {
   ConstantPoolGen constantPool = methodGen.getConstantPool();
   Set<ValueNumber> nonNullParams =
       checkNonNullParams(
           location, vnaFrame, constantPool, method, invDataflow.getFactAtLocation(location));
   for (ValueNumber vn : nonNullParams) {
     fact.addDeref(vn, location);
   }
 }
  /** Adds code in nl to start of method mg * */
  public static void add_to_start(MethodGen mg, InstructionList nl) {

    // Add the code before the first instruction
    InstructionList il = mg.getInstructionList();
    InstructionHandle old_start = il.getStart();
    InstructionHandle new_start = il.insert(nl);

    // Move any LineNumbers and local variable that currently point to
    // the first instruction to include the new instructions. Other
    // targeters (branches, exceptions) should not include the new
    // code
    if (old_start.hasTargeters()) {
      for (InstructionTargeter it : old_start.getTargeters()) {
        if ((it instanceof LineNumberGen) || (it instanceof LocalVariableGen))
          it.updateTarget(old_start, new_start);
      }
    }
    mg.setMaxStack();
    mg.setMaxLocals();
  }