com.android.dx.dex.file.ClassDefItem Java Examples

The following examples show how to use com.android.dx.dex.file.ClassDefItem. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: J2ME-Loader   Author: nikita36078   File: Main.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Boolean call() throws Exception {
    try {
        ClassDefItem clazz = futureClazz.get();
        if (clazz != null) {
            addClassToDex(clazz);
            updateStatus(true);
        }
        return true;
    } catch(ExecutionException ex) {
        // Rethrow previously uncaught translation exceptions.
        // These, as well as any exceptions from addClassToDex,
        // are handled and reported in processAllFiles().
        Throwable t = ex.getCause();
        throw (t instanceof Exception) ? (Exception) t : ex;
    }
}
 
Example #2
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private ClassDefItem translateClass(byte[] bytes, DirectClassFile cf) {
    try {
        return CfTranslator.translate(context, cf, bytes, args.cfOptions,
                args.dexOptions, outputDex);
    } catch (ParseException ex) {
        context.err.println("\ntrouble processing:");
        if (args.debug) {
            ex.printStackTrace(context.err);
        } else {
            ex.printContext(context.err);
        }
    }
    errors.incrementAndGet();
    return null;
}
 
Example #3
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private ClassDefItemConsumer(String name, Future<ClassDefItem> futureClazz,
        int maxMethodIdsInClass, int maxFieldIdsInClass) {
    this.name = name;
    this.futureClazz = futureClazz;
    this.maxMethodIdsInClass = maxMethodIdsInClass;
    this.maxFieldIdsInClass = maxFieldIdsInClass;
}
 
Example #4
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Boolean call() throws Exception {
    try {
        ClassDefItem clazz = futureClazz.get();
        if (clazz != null) {
            addClassToDex(clazz);
            updateStatus(true);
        }
        return true;
    } catch(ExecutionException ex) {
        // Rethrow previously uncaught translation exceptions.
        // These, as well as any exceptions from addClassToDex,
        // are handled and reported in processAllFiles().
        Throwable t = ex.getCause();
        throw (t instanceof Exception) ? (Exception) t : ex;
    } finally {
        if (args.multiDex) {
            // Having added our actual indicies to the dex file,
            // we subtract our original estimate from the total estimate,
            // and signal the translation phase, which may be paused
            // waiting to determine if more classes can be added to the
            // current dex file, or if a new dex file must be created.
            synchronized(dexRotationLock) {
                maxMethodIdsInProcess -= maxMethodIdsInClass;
                maxFieldIdsInProcess -= maxFieldIdsInClass;
                dexRotationLock.notifyAll();
            }
        }
    }
}
 
Example #5
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private ClassDefItem translateClass(byte[] bytes, DirectClassFile cf) {
    try {
        return CfTranslator.translate(context, cf, bytes, args.cfOptions,
                args.dexOptions, outputDex);
    } catch (ParseException ex) {
        context.err.println("\ntrouble processing:");
        if (args.debug) {
            ex.printStackTrace(context.err);
        } else {
            ex.printContext(context.err);
        }
    }
    errors.incrementAndGet();
    return null;
}
 
Example #6
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private ClassDefItemConsumer(String name, Future<ClassDefItem> futureClazz,
        int maxMethodIdsInClass, int maxFieldIdsInClass) {
    this.name = name;
    this.futureClazz = futureClazz;
    this.maxMethodIdsInClass = maxMethodIdsInClass;
    this.maxFieldIdsInClass = maxFieldIdsInClass;
}
 
Example #7
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Boolean call() throws Exception {
    try {
        ClassDefItem clazz = futureClazz.get();
        if (clazz != null) {
            addClassToDex(clazz);
            updateStatus(true);
        }
        return true;
    } catch(ExecutionException ex) {
        // Rethrow previously uncaught translation exceptions.
        // These, as well as any exceptions from addClassToDex,
        // are handled and reported in processAllFiles().
        Throwable t = ex.getCause();
        throw (t instanceof Exception) ? (Exception) t : ex;
    } finally {
        if (args.multiDex) {
            // Having added our actual indicies to the dex file,
            // we subtract our original estimate from the total estimate,
            // and signal the translation phase, which may be paused
            // waiting to determine if more classes can be added to the
            // current dex file, or if a new dex file must be created.
            synchronized(dexRotationLock) {
                maxMethodIdsInProcess -= maxMethodIdsInClass;
                maxFieldIdsInProcess -= maxFieldIdsInClass;
                dexRotationLock.notifyAll();
            }
        }
    }
}
 
Example #8
Source Project: lua-for-android   Author: qtiuto   File: AnnotationId.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add this annotation to a method.
 *
 * @param dexMaker DexMaker instance.
 * @param method   Method to be added to.
 */
public static void addToMethod(DexMaker dexMaker, MethodId<?, ?> method,List<AnnotationId<?,?>> ids) {
    ClassDefItem classDefItem = dexMaker.getTypeDeclaration(method.declaringType).toClassDefItem();

    if (classDefItem == null) {
        throw new NullPointerException("No class defined item is found");
    }
    CstMethodRef cstMethodRef = method.constant;
    if (cstMethodRef == null) {
        throw new NullPointerException("Method reference is NULL");
    }
    Annotations annotations = new Annotations();
    for (AnnotationId<?, ?> id :
            ids) {
        if (id.annotatedElement != ElementType.METHOD) {
            throw new IllegalStateException("This annotation is not for method");
        }

        if (method.declaringType != id.declaringType) {
            throw new IllegalArgumentException("Method" + method + "'s declaring type is inconsistent with" + id);
        }

        // Generate CstType
        CstType cstType = CstType.intern(id.type.ropType);

        // Generate Annotation
        Annotation annotation = new Annotation(cstType, AnnotationVisibility.RUNTIME);

        // Add generated annotation
        for (NameValuePair nvp : id.elements.values()) {
            annotation.add(nvp);
        }
        annotations.add(annotation);
    }
    classDefItem.addMethodAnnotations(cstMethodRef, annotations, dexMaker.getDexFile());


}
 
Example #9
Source Project: lua-for-android   Author: qtiuto   File: AnnotationId.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void addToField(DexMaker dexMaker, FieldId<?, ?> field,List<AnnotationId<?,?>> ids) {
    ClassDefItem classDefItem = dexMaker.getTypeDeclaration(field.declaringType).toClassDefItem();
    if (classDefItem == null) {
        throw new NullPointerException("No class defined item is found");
    }
    Annotations annotations = new Annotations();
    for (AnnotationId<?,?> id:ids){
        if (id.annotatedElement != ElementType.FIELD) {
            throw new IllegalStateException("This annotation is not for method");
        }

        if (field.declaringType != id.declaringType) {
            throw new IllegalArgumentException("Field" + field + "'s declaring type is inconsistent with" + id);
        }

        // Generate CstType
        CstType cstType = CstType.intern(id.type.ropType);

        // Generate Annotation
        Annotation annotation = new Annotation(cstType, AnnotationVisibility.RUNTIME);

        // Add generated annotation
        for (NameValuePair nvp : id.elements.values()) {
            annotation.add(nvp);
        }
        annotations.add(annotation);
    }

    CstFieldRef cstFieldRef = field.constant;
    classDefItem.addFieldAnnotations(cstFieldRef, annotations, dexMaker.getDexFile());
}
 
Example #10
Source Project: J2ME-Loader   Author: nikita36078   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private ClassDefItem translateClass(byte[] bytes, DirectClassFile cf) {
    try {
        return CfTranslator.translate(context, cf, bytes, args.cfOptions,
                args.dexOptions, outputDex);
    } catch (ParseException ex) {
        context.err.println("\ntrouble processing:");
        if (args.debug) {
            ex.printStackTrace(context.err);
        } else {
            ex.printContext(context.err);
        }
    }
    errors.incrementAndGet();
    return null;
}
 
Example #11
Source Project: J2ME-Loader   Author: nikita36078   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private Boolean call(DirectClassFile cf) {

            // Submit class to translation phase.
            Future<ClassDefItem> cdif = classTranslatorPool.submit(
                    new ClassTranslatorTask(bytes, cf));
            Future<Boolean> res = classDefItemConsumer.submit(new ClassDefItemConsumer(
                    name, cdif));
            addToDexFutures.add(res);

            return true;
        }
 
Example #12
Source Project: knopflerfish.org   Author: knopflerfish   File: Dexifier.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addToDexFile(DexFile dexFile, String name, byte[] bytes) {
  DirectClassFile cf = new DirectClassFile(bytes, name, cfOptions.strictNameCheck);
  cf.setAttributeFactory(StdAttributeFactory.THE_ONE);
  cf.getMagic();

  int numMethodIds = dexFile.getMethodIds().items().size();
  int numFieldIds = dexFile.getFieldIds().items().size();
  int constantPoolSize = cf.getConstantPool().size();

  int maxMethodIdsInDex = numMethodIds + constantPoolSize + cf.getMethods().size() +
      MAX_METHOD_ADDED_DURING_DEX_CREATION;
  int maxFieldIdsInDex = numFieldIds + constantPoolSize + cf.getFields().size() +
      MAX_FIELD_ADDED_DURING_DEX_CREATION;

  if ((dexFile.getClassDefs().items().size() > 0)
      && ((maxMethodIdsInDex > MAX_NUMBER_OF_IDX_PER_DEX) ||
          (maxFieldIdsInDex > MAX_NUMBER_OF_IDX_PER_DEX))) {
    throw new RuntimeException("TODO multi dex!");
  }

  try {
    ClassDefItem clazz = CfTranslator.translate(cf, bytes, cfOptions , dexOptions, dexFile);
    synchronized (dexFile) {
      dexFile.add(clazz);
    }
  } catch (ParseException ex) {
    Main.exit("Parse error, " + name, ex);
  }
}
 
Example #13
Source Project: dexmaker   Author: linkedin   File: AnnotationId.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add this annotation to a method.
 *
 * @param dexMaker DexMaker instance.
 * @param method Method to be added to.
 */
public void addToMethod(DexMaker dexMaker, MethodId<?, ?> method) {
    if (annotatedElement != ElementType.METHOD) {
        throw new IllegalStateException("This annotation is not for method");
    }

    if (!method.declaringType.equals(declaringType)) {
        throw new IllegalArgumentException("Method" + method + "'s declaring type is inconsistent with" + this);
    }

    ClassDefItem classDefItem = dexMaker.getTypeDeclaration(declaringType).toClassDefItem();

    if (classDefItem == null) {
        throw new NullPointerException("No class defined item is found");
    } else {
        CstMethodRef cstMethodRef = method.constant;

        if (cstMethodRef == null) {
            throw new NullPointerException("Method reference is NULL");
        } else {
            // Generate CstType
            CstType cstType = CstType.intern(type.ropType);

            // Generate Annotation
            Annotation annotation = new Annotation(cstType, AnnotationVisibility.RUNTIME);

            // Add generated annotation
            Annotations annotations = new Annotations();
            for (NameValuePair nvp : elements.values()) {
                annotation.add(nvp);
            }
            annotations.add(annotation);
            classDefItem.addMethodAnnotations(cstMethodRef, annotations, dexMaker.getDexFile());
        }
    }
}
 
Example #14
Source Project: bazel   Author: bazelbuild   File: Dexing.java    License: Apache License 2.0 5 votes vote down vote up
public ClassDefItem addToDexFile(DexFile dest, DirectClassFile classFile) {
  ClassDefItem result = CfTranslator.translate(
      context,
      classFile,
      (byte[]) null /*ignored*/,
      cfOptions,
      dest.getDexOptions(),
      dest);
  dest.add(result);
  return result;
}
 
Example #15
Source Project: byte-buddy   Author: raphw   File: AndroidClassLoadingStrategy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassDefItem translate(DirectClassFile directClassFile,
                              byte[] binaryRepresentation,
                              CfOptions dexCompilerOptions,
                              DexOptions dexFileOptions,
                              DexFile dexFile) {
    throw new IllegalStateException("Could not resolve dispatcher: " + message);
}
 
Example #16
Source Project: buck   Author: facebook   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private ClassDefItem translateClass(byte[] bytes, DirectClassFile cf) {
    try {
        return CfTranslator.translate(context, cf, bytes, args.cfOptions,
            args.dexOptions, outputDex);
    } catch (ParseException ex) {
        context.err.println("\ntrouble processing:");
        if (args.debug) {
            ex.printStackTrace(context.err);
        } else {
            ex.printContext(context.err);
        }
    }
    errors.incrementAndGet();
    return null;
}
 
Example #17
Source Project: buck   Author: facebook   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private ClassDefItemConsumer(String name, Future<ClassDefItem> futureClazz,
    int maxMethodIdsInClass, int maxFieldIdsInClass) {
    this.name = name;
    this.futureClazz = futureClazz;
    this.maxMethodIdsInClass = maxMethodIdsInClass;
    this.maxFieldIdsInClass = maxFieldIdsInClass;
}
 
Example #18
Source Project: buck   Author: facebook   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Boolean call() throws Exception {
    try {
        ClassDefItem clazz = futureClazz.get();
        if (clazz != null) {
            addClassToDex(clazz);
            updateStatus(true);
        }
        return true;
    } catch(ExecutionException ex) {
        // Rethrow previously uncaught translation exceptions.
        // These, as well as any exceptions from addClassToDex,
        // are handled and reported in processAllFiles().
        Throwable t = ex.getCause();
        throw (t instanceof Exception) ? (Exception) t : ex;
    } finally {
        if (args.multiDex) {
            // Having added our actual indicies to the dex file,
            // we subtract our original estimate from the total estimate,
            // and signal the translation phase, which may be paused
            // waiting to determine if more classes can be added to the
            // current dex file, or if a new dex file must be created.
            synchronized(dexRotationLock) {
                maxMethodIdsInProcess -= maxMethodIdsInClass;
                maxFieldIdsInProcess -= maxFieldIdsInClass;
                dexRotationLock.notifyAll();
            }
        }
    }
}
 
Example #19
Source Project: Box   Author: lulululbj   File: CfTranslator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Performs the main act of translation. This method is separated
 * from {@link #translate} just to keep things a bit simpler in
 * terms of exception handling.
 *
 *
 * @param context {@code non-null;} the state global to this invocation.
 * @param cf {@code non-null;} the class file
 * @param bytes {@code non-null;} contents of the file
 * @param cfOptions options for class translation
 * @param dexOptions options for dex output
 * @param dexFile {@code non-null;} dex output
 * @return {@code non-null;} the translated class
 */
private static ClassDefItem translate0(DxContext context, DirectClassFile cf, byte[] bytes,
        CfOptions cfOptions, DexOptions dexOptions, DexFile dexFile) {

    context.optimizerOptions.loadOptimizeLists(cfOptions.optimizeListFile,
            cfOptions.dontOptimizeListFile);

    // Build up a class to output.

    CstType thisClass = cf.getThisClass();
    int classAccessFlags = cf.getAccessFlags() & ~AccessFlags.ACC_SUPER;
    CstString sourceFile = (cfOptions.positionInfo == PositionList.NONE) ? null :
        cf.getSourceFile();
    ClassDefItem out =
        new ClassDefItem(thisClass, classAccessFlags,
                cf.getSuperclass(), cf.getInterfaces(), sourceFile);

    Annotations classAnnotations =
        AttributeTranslator.getClassAnnotations(cf, cfOptions);
    if (classAnnotations.size() != 0) {
        out.setClassAnnotations(classAnnotations, dexFile);
    }

    FieldIdsSection fieldIdsSection = dexFile.getFieldIds();
    MethodIdsSection methodIdsSection = dexFile.getMethodIds();
    MethodHandlesSection methodHandlesSection = dexFile.getMethodHandles();
    CallSiteIdsSection callSiteIds = dexFile.getCallSiteIds();
    processFields(cf, out, dexFile);
    processMethods(context, cf, cfOptions, dexOptions, out, dexFile);

    // intern constant pool method, field and type references
    ConstantPool constantPool = cf.getConstantPool();
    int constantPoolSize = constantPool.size();

    for (int i = 0; i < constantPoolSize; i++) {
        Constant constant = constantPool.getOrNull(i);
        if (constant instanceof CstMethodRef) {
            methodIdsSection.intern((CstBaseMethodRef) constant);
        } else if (constant instanceof CstInterfaceMethodRef) {
            methodIdsSection.intern(((CstInterfaceMethodRef) constant).toMethodRef());
        } else if (constant instanceof CstFieldRef) {
            fieldIdsSection.intern((CstFieldRef) constant);
        } else if (constant instanceof CstEnumRef) {
            fieldIdsSection.intern(((CstEnumRef) constant).getFieldRef());
        } else if (constant instanceof CstMethodHandle) {
            methodHandlesSection.intern((CstMethodHandle) constant);
        } else if (constant instanceof CstInvokeDynamic) {
            CstInvokeDynamic cstInvokeDynamic = (CstInvokeDynamic) constant;
            int index = cstInvokeDynamic.getBootstrapMethodIndex();
            BootstrapMethodsList.Item bootstrapMethod = cf.getBootstrapMethods().get(index);
            CstCallSite callSite =
                    CstCallSite.make(bootstrapMethod.getBootstrapMethodHandle(),
                                     cstInvokeDynamic.getNat(),
                                     bootstrapMethod.getBootstrapMethodArguments());
            cstInvokeDynamic.setDeclaringClass(cf.getThisClass());
            cstInvokeDynamic.setCallSite(callSite);
            for (CstCallSiteRef ref : cstInvokeDynamic.getReferences()) {
                callSiteIds.intern(ref);
            }
        }
    }

    return out;
}
 
Example #20
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
private boolean addClassToDex(ClassDefItem clazz) {
    synchronized (outputDex) {
        outputDex.add(clazz);
    }
    return true;
}
 
Example #21
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
private Boolean call(DirectClassFile cf) {

            int maxMethodIdsInClass = 0;
            int maxFieldIdsInClass = 0;

            if (args.multiDex) {

                // Calculate max number of indices this class will add to the
                // dex file.
                // The possibility of overloading means that we can't easily
                // know how many constant are needed for declared methods and
                // fields. We therefore make the simplifying assumption that
                // all constants are external method or field references.

                int constantPoolSize = cf.getConstantPool().size();
                maxMethodIdsInClass = constantPoolSize + cf.getMethods().size()
                        + MAX_METHOD_ADDED_DURING_DEX_CREATION;
                maxFieldIdsInClass = constantPoolSize + cf.getFields().size()
                        + MAX_FIELD_ADDED_DURING_DEX_CREATION;
                synchronized(dexRotationLock) {

                    int numMethodIds;
                    int numFieldIds;
                    // Number of indices used in current dex file.
                    synchronized(outputDex) {
                        numMethodIds = outputDex.getMethodIds().items().size();
                        numFieldIds = outputDex.getFieldIds().items().size();
                    }
                    // Wait until we're sure this class will fit in the current
                    // dex file.
                    while(((numMethodIds + maxMethodIdsInClass + maxMethodIdsInProcess
                            > args.maxNumberOfIdxPerDex) ||
                           (numFieldIds + maxFieldIdsInClass + maxFieldIdsInProcess
                            > args.maxNumberOfIdxPerDex))) {

                        if (maxMethodIdsInProcess > 0 || maxFieldIdsInProcess > 0) {
                            // There are classes in the translation phase that
                            // have not yet been added to the dex file, so we
                            // wait for the next class to complete.
                            try {
                                dexRotationLock.wait();
                            } catch(InterruptedException ex) {
                                /* ignore */
                            }
                        } else if (outputDex.getClassDefs().items().size() > 0) {
                            // There are no further classes in the translation
                            // phase, and we have a full dex file. Rotate!
                            rotateDexFile();
                        } else {
                            // The estimated number of indices is too large for
                            // an empty dex file. We proceed hoping the actual
                            // number of indices needed will fit.
                            break;
                        }
                        synchronized(outputDex) {
                            numMethodIds = outputDex.getMethodIds().items().size();
                            numFieldIds = outputDex.getFieldIds().items().size();
                        }
                    }
                    // Add our estimate to the total estimate for
                    // classes under translation.
                    maxMethodIdsInProcess += maxMethodIdsInClass;
                    maxFieldIdsInProcess += maxFieldIdsInClass;
                }
            }

            // Submit class to translation phase.
            Future<ClassDefItem> cdif = classTranslatorPool.submit(
                    new ClassTranslatorTask(name, bytes, cf));
            Future<Boolean> res = classDefItemConsumer.submit(new ClassDefItemConsumer(
                    name, cdif, maxMethodIdsInClass, maxFieldIdsInClass));
            addToDexFutures.add(res);

            return true;
        }
 
Example #22
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClassDefItem call() {
    ClassDefItem clazz = translateClass(bytes, classFile);
    return clazz;
}
 
Example #23
Source Project: Box   Author: lulululbj   File: CfTranslator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Performs the main act of translation. This method is separated
 * from {@link #translate} just to keep things a bit simpler in
 * terms of exception handling.
 *
 *
 * @param context {@code non-null;} the state global to this invocation.
 * @param cf {@code non-null;} the class file
 * @param bytes {@code non-null;} contents of the file
 * @param cfOptions options for class translation
 * @param dexOptions options for dex output
 * @param dexFile {@code non-null;} dex output
 * @return {@code non-null;} the translated class
 */
private static ClassDefItem translate0(DxContext context, DirectClassFile cf, byte[] bytes,
        CfOptions cfOptions, DexOptions dexOptions, DexFile dexFile) {

    context.optimizerOptions.loadOptimizeLists(cfOptions.optimizeListFile,
            cfOptions.dontOptimizeListFile);

    // Build up a class to output.

    CstType thisClass = cf.getThisClass();
    int classAccessFlags = cf.getAccessFlags() & ~AccessFlags.ACC_SUPER;
    CstString sourceFile = (cfOptions.positionInfo == PositionList.NONE) ? null :
        cf.getSourceFile();
    ClassDefItem out =
        new ClassDefItem(thisClass, classAccessFlags,
                cf.getSuperclass(), cf.getInterfaces(), sourceFile);

    Annotations classAnnotations =
        AttributeTranslator.getClassAnnotations(cf, cfOptions);
    if (classAnnotations.size() != 0) {
        out.setClassAnnotations(classAnnotations, dexFile);
    }

    FieldIdsSection fieldIdsSection = dexFile.getFieldIds();
    MethodIdsSection methodIdsSection = dexFile.getMethodIds();
    MethodHandlesSection methodHandlesSection = dexFile.getMethodHandles();
    CallSiteIdsSection callSiteIds = dexFile.getCallSiteIds();
    processFields(cf, out, dexFile);
    processMethods(context, cf, cfOptions, dexOptions, out, dexFile);

    // intern constant pool method, field and type references
    ConstantPool constantPool = cf.getConstantPool();
    int constantPoolSize = constantPool.size();

    for (int i = 0; i < constantPoolSize; i++) {
        Constant constant = constantPool.getOrNull(i);
        if (constant instanceof CstMethodRef) {
            methodIdsSection.intern((CstBaseMethodRef) constant);
        } else if (constant instanceof CstInterfaceMethodRef) {
            methodIdsSection.intern(((CstInterfaceMethodRef) constant).toMethodRef());
        } else if (constant instanceof CstFieldRef) {
            fieldIdsSection.intern((CstFieldRef) constant);
        } else if (constant instanceof CstEnumRef) {
            fieldIdsSection.intern(((CstEnumRef) constant).getFieldRef());
        } else if (constant instanceof CstMethodHandle) {
            methodHandlesSection.intern((CstMethodHandle) constant);
        } else if (constant instanceof CstInvokeDynamic) {
            CstInvokeDynamic cstInvokeDynamic = (CstInvokeDynamic) constant;
            int index = cstInvokeDynamic.getBootstrapMethodIndex();
            BootstrapMethodsList.Item bootstrapMethod = cf.getBootstrapMethods().get(index);
            CstCallSite callSite =
                    CstCallSite.make(bootstrapMethod.getBootstrapMethodHandle(),
                                     cstInvokeDynamic.getNat(),
                                     bootstrapMethod.getBootstrapMethodArguments());
            cstInvokeDynamic.setDeclaringClass(cf.getThisClass());
            cstInvokeDynamic.setCallSite(callSite);
            for (CstCallSiteRef ref : cstInvokeDynamic.getReferences()) {
                callSiteIds.intern(ref);
            }
        }
    }

    return out;
}
 
Example #24
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
private boolean addClassToDex(ClassDefItem clazz) {
    synchronized (outputDex) {
        outputDex.add(clazz);
    }
    return true;
}
 
Example #25
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
private Boolean call(DirectClassFile cf) {

            int maxMethodIdsInClass = 0;
            int maxFieldIdsInClass = 0;

            if (args.multiDex) {

                // Calculate max number of indices this class will add to the
                // dex file.
                // The possibility of overloading means that we can't easily
                // know how many constant are needed for declared methods and
                // fields. We therefore make the simplifying assumption that
                // all constants are external method or field references.

                int constantPoolSize = cf.getConstantPool().size();
                maxMethodIdsInClass = constantPoolSize + cf.getMethods().size()
                        + MAX_METHOD_ADDED_DURING_DEX_CREATION;
                maxFieldIdsInClass = constantPoolSize + cf.getFields().size()
                        + MAX_FIELD_ADDED_DURING_DEX_CREATION;
                synchronized(dexRotationLock) {

                    int numMethodIds;
                    int numFieldIds;
                    // Number of indices used in current dex file.
                    synchronized(outputDex) {
                        numMethodIds = outputDex.getMethodIds().items().size();
                        numFieldIds = outputDex.getFieldIds().items().size();
                    }
                    // Wait until we're sure this class will fit in the current
                    // dex file.
                    while(((numMethodIds + maxMethodIdsInClass + maxMethodIdsInProcess
                            > args.maxNumberOfIdxPerDex) ||
                           (numFieldIds + maxFieldIdsInClass + maxFieldIdsInProcess
                            > args.maxNumberOfIdxPerDex))) {

                        if (maxMethodIdsInProcess > 0 || maxFieldIdsInProcess > 0) {
                            // There are classes in the translation phase that
                            // have not yet been added to the dex file, so we
                            // wait for the next class to complete.
                            try {
                                dexRotationLock.wait();
                            } catch(InterruptedException ex) {
                                /* ignore */
                            }
                        } else if (outputDex.getClassDefs().items().size() > 0) {
                            // There are no further classes in the translation
                            // phase, and we have a full dex file. Rotate!
                            rotateDexFile();
                        } else {
                            // The estimated number of indices is too large for
                            // an empty dex file. We proceed hoping the actual
                            // number of indices needed will fit.
                            break;
                        }
                        synchronized(outputDex) {
                            numMethodIds = outputDex.getMethodIds().items().size();
                            numFieldIds = outputDex.getFieldIds().items().size();
                        }
                    }
                    // Add our estimate to the total estimate for
                    // classes under translation.
                    maxMethodIdsInProcess += maxMethodIdsInClass;
                    maxFieldIdsInProcess += maxFieldIdsInClass;
                }
            }

            // Submit class to translation phase.
            Future<ClassDefItem> cdif = classTranslatorPool.submit(
                    new ClassTranslatorTask(name, bytes, cf));
            Future<Boolean> res = classDefItemConsumer.submit(new ClassDefItemConsumer(
                    name, cdif, maxMethodIdsInClass, maxFieldIdsInClass));
            addToDexFutures.add(res);

            return true;
        }
 
Example #26
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClassDefItem call() {
    ClassDefItem clazz = translateClass(bytes, classFile);
    return clazz;
}
 
Example #27
Source Project: lua-for-android   Author: qtiuto   File: AnnotationId.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void addToParameters(DexMaker dexMaker, MethodId<?, ?> methodId,
                                   List<List<AnnotationId<?,?>>> annotationIds) {
    ClassDefItem classDefItem = dexMaker.getTypeDeclaration(methodId.declaringType).toClassDefItem();

    if (classDefItem == null) {
        throw new NullPointerException("No class defined item is found");
    }
    CstMethodRef cstMethodRef = methodId.constant;
    if (cstMethodRef == null) {
        throw new NullPointerException("Method reference is NULL");
    }
    AnnotationsList list=new AnnotationsList(annotationIds.size());
    for (int i=list.size()-1;i>=0;--i) {
        List<AnnotationId<?, ?>> ids =
        annotationIds.get(i);
        if(ids==null) continue;
        Annotations annotations = new Annotations();
        for (AnnotationId<?,?> id:ids) {

            if (id.annotatedElement != ElementType.PARAMETER) {
                throw new IllegalStateException("This annotation is not for method");
            }

            if (id.declaringType != methodId.declaringType) {
                throw new IllegalArgumentException("Method" + methodId + "'s declaring type is inconsistent with" + id);
            }
            // Generate CstType
            CstType cstType = CstType.intern(id.type.ropType);

            // Generate Annotation
            Annotation annotation = new Annotation(cstType, AnnotationVisibility.RUNTIME);

            // Add generated annotation
            for (NameValuePair nvp : id.elements.values()) {
                annotation.add(nvp);
            }
            annotations.add(annotation);
        }
        list.set(i,annotations);
    }


    classDefItem.addParameterAnnotations(cstMethodRef,list , dexMaker.getDexFile());
}
 
Example #28
Source Project: J2ME-Loader   Author: nikita36078   File: CfTranslator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Performs the main act of translation. This method is separated
 * from {@link #translate} just to keep things a bit simpler in
 * terms of exception handling.
 *
 *
 * @param context {@code non-null;} the state global to this invocation.
 * @param cf {@code non-null;} the class file
 * @param bytes {@code non-null;} contents of the file
 * @param cfOptions options for class translation
 * @param dexOptions options for dex output
 * @param dexFile {@code non-null;} dex output
 * @return {@code non-null;} the translated class
 */
private static ClassDefItem translate0(DxContext context, DirectClassFile cf, byte[] bytes,
        CfOptions cfOptions, DexOptions dexOptions, DexFile dexFile) {

    context.optimizerOptions.loadOptimizeLists(cfOptions.optimizeListFile,
            cfOptions.dontOptimizeListFile);

    // Build up a class to output.

    CstType thisClass = cf.getThisClass();
    int classAccessFlags = cf.getAccessFlags() & ~AccessFlags.ACC_SUPER;
    CstString sourceFile = (cfOptions.positionInfo == PositionList.NONE) ? null :
        cf.getSourceFile();
    ClassDefItem out =
        new ClassDefItem(thisClass, classAccessFlags,
                cf.getSuperclass(), cf.getInterfaces(), sourceFile);

    Annotations classAnnotations =
        AttributeTranslator.getClassAnnotations(cf, cfOptions);
    if (classAnnotations.size() != 0) {
        out.setClassAnnotations(classAnnotations, dexFile);
    }

    FieldIdsSection fieldIdsSection = dexFile.getFieldIds();
    MethodIdsSection methodIdsSection = dexFile.getMethodIds();
    processFields(cf, out, dexFile);
    processMethods(context, cf, cfOptions, dexOptions, out, dexFile);

    // intern constant pool method, field and type references
    ConstantPool constantPool = cf.getConstantPool();
    int constantPoolSize = constantPool.size();

    for (int i = 0; i < constantPoolSize; i++) {
        Constant constant = constantPool.getOrNull(i);
        if (constant instanceof CstMethodRef) {
            methodIdsSection.intern((CstBaseMethodRef) constant);
        } else if (constant instanceof CstInterfaceMethodRef) {
            methodIdsSection.intern(((CstInterfaceMethodRef) constant).toMethodRef());
        } else if (constant instanceof CstFieldRef) {
            fieldIdsSection.intern((CstFieldRef) constant);
        } else if (constant instanceof CstEnumRef) {
            fieldIdsSection.intern(((CstEnumRef) constant).getFieldRef());
        }
    }

    return out;
}
 
Example #29
Source Project: J2ME-Loader   Author: nikita36078   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
private boolean addClassToDex(ClassDefItem clazz) {
    synchronized (outputDex) {
        outputDex.add(clazz);
    }
    return true;
}
 
Example #30
Source Project: J2ME-Loader   Author: nikita36078   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClassDefItem call() {
    ClassDefItem clazz = translateClass(bytes, classFile);
    return clazz;
}