Java Code Examples for com.android.dx.dex.file.DexFile

The following examples show how to use com.android.dx.dex.file.DexFile. These examples are extracted from open source projects. 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: Mindustry   Author: Anuken   File: AndroidRhinoContext.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Class<?> defineClass(String name, byte[] data){
    try{
        DexOptions dexOptions = new DexOptions();
        DexFile dexFile = new DexFile(dexOptions);
        DirectClassFile classFile = new DirectClassFile(data, name.replace('.', '/') + ".class", true);
        classFile.setAttributeFactory(StdAttributeFactory.THE_ONE);
        classFile.getMagic();
        DxContext context = new DxContext();
        dexFile.add(CfTranslator.translate(context, classFile, null, new CfOptions(), dexOptions, dexFile));
        Dex dex = new Dex(dexFile.toDex(null, false));
        Dex oldDex = getLastDex();
        if(oldDex != null){
            dex = new DexMerger(new Dex[]{dex, oldDex}, CollisionPolicy.KEEP_FIRST, context).merge();
        }
        return loadClass(dex, name);
    }catch(IOException | ClassNotFoundException e){
        throw new FatalLoadingException(e);
    }
}
 
Example #2
Source Project: rhino-android   Author: F43nd1r   File: BaseAndroidClassLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Class<?> defineClass(String name, byte[] data) {
    try {
        DexOptions dexOptions = new DexOptions();
        DexFile dexFile = new DexFile(dexOptions);
        DirectClassFile classFile = new DirectClassFile(data, name.replace('.', '/') + ".class", true);
        classFile.setAttributeFactory(StdAttributeFactory.THE_ONE);
        classFile.getMagic();
        DxContext context = new DxContext();
        dexFile.add(CfTranslator.translate(context, classFile, null, new CfOptions(), dexOptions, dexFile));
        Dex dex = new Dex(dexFile.toDex(null, false));
        Dex oldDex = getLastDex();
        if (oldDex != null) {
            dex = new DexMerger(new Dex[]{dex, oldDex}, CollisionPolicy.KEEP_FIRST, context).merge();
        }
        return loadClass(dex, name);
    } catch (IOException | ClassNotFoundException e) {
        throw new FatalLoadingException(e);
    }
}
 
Example #3
Source Project: knopflerfish.org   Author: knopflerfish   File: Dexifier.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private byte[] dexifyJar(JarInputStream ji) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  JarOutputStream outJar = new JarOutputStream(baos);
  DexFile dexFile = getDexFile();
  for (JarEntry je = ji.getNextJarEntry(); je != null; je = ji.getNextJarEntry()) {
    byte [] bytes = null;
    String name = je.getName();
    if (keepEntry(name)) {
      bytes  = getBytes(ji, (int) je.getSize());
      saveEntry(name, bytes, outJar);
    }
    if (name.endsWith(CLASS_SUFFIX)) {
      if (bytes == null) {
        bytes  = getBytes(ji, (int) je.getSize());
      }
      addToDexFile(dexFile, name, bytes);
    } else if (!force && name.equals(CLASSES_DEX)) {
      // Jar already dexified
      return null;
    }
  }
  saveDexFile(dexFile, 1, outJar);
  outJar.close();
  return baos.toByteArray();
}
 
Example #4
Source Project: byte-buddy   Author: raphw   File: AndroidClassLoadingStrategy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Map<TypeDescription, Class<?>> doLoad(ClassLoader classLoader, Set<TypeDescription> typeDescriptions, File jar) throws IOException {
    dalvik.system.DexFile dexFile = DISPATCHER.loadDex(privateDirectory, jar, classLoader, randomString);
    try {
        Map<TypeDescription, Class<?>> loadedTypes = new HashMap<TypeDescription, Class<?>>();
        for (TypeDescription typeDescription : typeDescriptions) {
            synchronized (classLoader) { // Guaranteed to be non-null by check in 'load' method.
                Class<?> type = DISPATCHER.loadClass(dexFile, classLoader, typeDescription);
                if (type == null) {
                    throw new IllegalStateException("Could not load " + typeDescription);
                }
                loadedTypes.put(typeDescription, type);
            }
        }
        return loadedTypes;
    } finally {
        if (dexFile != null) {
            dexFile.close();
        }
    }
}
 
Example #5
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private void createDexFile() {
    outputDex = new DexFile(args.dexOptions);

    if (args.dumpWidth != 0) {
        outputDex.setDumpWidth(args.dumpWidth);
    }
}
 
Example #6
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private void createDexFile() {
    outputDex = new DexFile(args.dexOptions);

    if (args.dumpWidth != 0) {
        outputDex.setDumpWidth(args.dumpWidth);
    }
}
 
Example #7
Source Project: lua-for-android   Author: qtiuto   File: MainActivity.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public DexFile generateDexFile(List<byte[]> classByteCodes){
    DxContext dxContext=new DxContext();
    DexOptions dexOptions=new DexOptions();
    CfOptions cfOptions=new CfOptions();
    DexFile dexFile=new DexFile(dexOptions);
    for (byte[] cls:classByteCodes){
        DirectClassFile directClassFile=new DirectClassFile(cls,"",false);
        directClassFile.setAttributeFactory(StdAttributeFactory.THE_ONE);
        directClassFile.getMagic();
        dexFile.add(CfTranslator.translate(dxContext,directClassFile,cls,cfOptions,dexOptions,dexFile));
    }
    return dexFile;
}
 
Example #8
Source Project: J2ME-Loader   Author: nikita36078   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private void createDexFile() {
    outputDex = new DexFile(args.dexOptions);

    if (args.dumpWidth != 0) {
        outputDex.setDumpWidth(args.dumpWidth);
    }
}
 
Example #9
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 #10
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 saveDexFile(DexFile dexFile, int idx, JarOutputStream outJar) throws IOException {
  if (!dexFile.isEmpty()) {
    String cn = "classes" + (idx > 1 ? Integer.toString(idx) : "") + ".dex";
    ZipEntry je = new JarEntry(cn);
    outJar.putNextEntry(je);
    dexFile.writeTo(outJar, null, false);
    outJar.closeEntry();
  }
}
 
Example #11
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 #12
Source Project: bazel   Author: bazelbuild   File: DexFileAggregatorTest.java    License: Apache License 2.0 5 votes vote down vote up
private static DexFile convertClass(Class<?> clazz) throws IOException {
  String path = clazz.getName().replace('.', '/') + ".class";
  try (InputStream in =
      Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) {
    return new DexConverter(new Dexing(new DxContext(), new DexOptions(), new CfOptions()))
        .toDexFile(ByteStreams.toByteArray(in), path);
  }
}
 
Example #13
Source Project: bazel   Author: bazelbuild   File: DexLimitTrackerTest.java    License: Apache License 2.0 5 votes vote down vote up
private static DexFile convertClass(Class<?> clazz) throws IOException {
  String path = clazz.getName().replace('.', '/') + ".class";
  try (InputStream in =
      Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) {
    return new DexConverter(new Dexing(new DxContext(), new DexOptions(), new CfOptions()))
        .toDexFile(ByteStreams.toByteArray(in), path);
  }
}
 
Example #14
Source Project: byte-buddy   Author: raphw   File: AndroidClassLoadingStrategy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void register(String name, byte[] binaryRepresentation) {
    DirectClassFile directClassFile = new DirectClassFile(binaryRepresentation, name.replace('.', '/') + CLASS_FILE_EXTENSION, NON_STRICT);
    directClassFile.setAttributeFactory(new StdAttributeFactory());
    dexFile.add(DISPATCHER.translate(directClassFile,
            binaryRepresentation,
            dexCompilerOptions,
            dexFileOptions,
            new DexFile(dexFileOptions)));
}
 
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: byte-buddy   Author: raphw   File: AndroidClassLoadingStrategy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public dalvik.system.DexFile loadDex(File privateDirectory,
                                     File jar,
                                     ClassLoader classLoader,
                                     RandomString randomString) throws IOException {
    return dalvik.system.DexFile.loadDex(jar.getAbsolutePath(),
            new File(privateDirectory.getAbsolutePath(), randomString.nextString() + EXTENSION).getAbsolutePath(),
            NO_FLAGS);
}
 
Example #17
Source Project: byte-buddy   Author: raphw   File: AndroidClassLoadingStrategy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Class<?> loadClass(dalvik.system.DexFile dexFile, ClassLoader classLoader, TypeDescription typeDescription) {
    try {
        return Class.forName(typeDescription.getName(), false, classLoader);
    } catch (ClassNotFoundException exception) {
        throw new IllegalStateException("Could not locate " + typeDescription, exception);
    }
}
 
Example #18
Source Project: buck   Author: facebook   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private void createDexFile() {
    outputDex = new DexFile(args.dexOptions);

    if (args.dumpWidth != 0) {
        outputDex.setDumpWidth(args.dumpWidth);
    }
}
 
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
/**
 * Converts {@link #outputDex} into a {@code byte[]} and do whatever
 * human-oriented dumping is required.
 *
 * @return {@code null-ok;} the converted {@code byte[]} or {@code null}
 * if there was a problem
 */
private byte[] writeDex(DexFile outputDex) {
    byte[] outArray = null;

    try {
        try {
            if (args.methodToDump != null) {
                /*
                 * Simply dump the requested method. Note: The call
                 * to toDex() is required just to get the underlying
                 * structures ready.
                 */
                outputDex.toDex(null, false);
                dumpMethod(outputDex, args.methodToDump, humanOutWriter);
            } else {
                /*
                 * This is the usual case: Create an output .dex file,
                 * and write it, dump it, etc.
                 */
                outArray = outputDex.toDex(humanOutWriter, args.verboseDump);
            }

            if (args.statistics) {
                context.out.println(outputDex.getStatistics().toHuman());
            }
        } finally {
            if (humanOutWriter != null) {
                humanOutWriter.flush();
            }
        }
    } catch (Exception ex) {
        if (args.debug) {
            context.err.println("\ntrouble writing output:");
            ex.printStackTrace(context.err);
        } else {
            context.err.println("\ntrouble writing output: " +
                               ex.getMessage());
        }
        return null;
    }
    return outArray;
}
 
Example #21
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
private DexWriter(DexFile dexFile) {
    this.dexFile = dexFile;
}
 
Example #22
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 #23
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Converts {@link #outputDex} into a {@code byte[]} and do whatever
 * human-oriented dumping is required.
 *
 * @return {@code null-ok;} the converted {@code byte[]} or {@code null}
 * if there was a problem
 */
private byte[] writeDex(DexFile outputDex) {
    byte[] outArray = null;

    try {
        try {
            if (args.methodToDump != null) {
                /*
                 * Simply dump the requested method. Note: The call
                 * to toDex() is required just to get the underlying
                 * structures ready.
                 */
                outputDex.toDex(null, false);
                dumpMethod(outputDex, args.methodToDump, humanOutWriter);
            } else {
                /*
                 * This is the usual case: Create an output .dex file,
                 * and write it, dump it, etc.
                 */
                outArray = outputDex.toDex(humanOutWriter, args.verboseDump);
            }

            if (args.statistics) {
                context.out.println(outputDex.getStatistics().toHuman());
            }
        } finally {
            if (humanOutWriter != null) {
                humanOutWriter.flush();
            }
        }
    } catch (Exception ex) {
        if (args.debug) {
            context.err.println("\ntrouble writing output:");
            ex.printStackTrace(context.err);
        } else {
            context.err.println("\ntrouble writing output: " +
                               ex.getMessage());
        }
        return null;
    }
    return outArray;
}
 
Example #24
Source Project: Box   Author: lulululbj   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
private DexWriter(DexFile dexFile) {
    this.dexFile = dexFile;
}
 
Example #25
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 #26
Source Project: J2ME-Loader   Author: nikita36078   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Converts {@link #outputDex} into a {@code byte[]} and do whatever
 * human-oriented dumping is required.
 *
 * @return {@code null-ok;} the converted {@code byte[]} or {@code null}
 * if there was a problem
 */
private byte[] writeDex(DexFile outputDex) {
    byte[] outArray = null;

    try {
        try {
            if (args.methodToDump != null) {
                /*
                 * Simply dump the requested method. Note: The call
                 * to toDex() is required just to get the underlying
                 * structures ready.
                 */
                outputDex.toDex(null, false);
                dumpMethod(outputDex, args.methodToDump, humanOutWriter);
            } else {
                /*
                 * This is the usual case: Create an output .dex file,
                 * and write it, dump it, etc.
                 */
                outArray = outputDex.toDex(humanOutWriter, args.verboseDump);
            }

            if (args.statistics) {
                context.out.println(outputDex.getStatistics().toHuman());
            }
        } finally {
            if (humanOutWriter != null) {
                humanOutWriter.flush();
            }
        }
    } catch (Exception ex) {
        if (args.debug) {
            context.err.println("\ntrouble writing output:");
            ex.printStackTrace(context.err);
        } else {
            context.err.println("\ntrouble writing output: " +
                               ex.getMessage());
        }
        return null;
    }
    return outArray;
}
 
Example #27
Source Project: knopflerfish.org   Author: knopflerfish   File: Dexifier.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private DexFile getDexFile() {
  return new DexFile(dexOptions);
}
 
Example #28
Source Project: bazel   Author: bazelbuild   File: DexConverter.java    License: Apache License 2.0 4 votes vote down vote up
public DexFile toDexFile(byte[] classfile, String classfilePath) {
  DexFile result = dexing.newDexFile();
  dexing.addToDexFile(result, Dexing.parseClassFile(classfile, classfilePath));
  return result;
}
 
Example #29
Source Project: bazel   Author: bazelbuild   File: Dexing.java    License: Apache License 2.0 4 votes vote down vote up
public DexFile newDexFile() {
  return new DexFile(dexOptions);
}
 
Example #30
Source Project: bazel   Author: bazelbuild   File: DexFiles.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns the {@link Dex} file resulting from writing out the given {@link DexFile}.
 */
public static Dex toDex(DexFile dex) throws IOException {
  return new Dex(encode(dex));
}