com.android.dex.DexFormat Java Examples

The following examples show how to use com.android.dex.DexFormat. 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 File: TypeIdsSection.java    From Box with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the portion of the file header that refers to this instance.
 *
 * @param out {@code non-null;} where to write
 */
public void writeHeaderPart(AnnotatedOutput out) {
    throwIfNotPrepared();

    int sz = typeIds.size();
    int offset = (sz == 0) ? 0 : getFileOffset();

    if (sz > DexFormat.MAX_TYPE_IDX + 1) {
        throw new DexIndexOverflowException(
                String.format("Too many type identifiers to fit in one dex file: %1$d; max is %2$d.%n"
                                + "You may try using multi-dex. If multi-dex is enabled then the list of "
                                + "classes for the main dex list is too large.",
                        items().size(), DexFormat.MAX_MEMBER_IDX + 1));
    }

    if (out.annotates()) {
        out.annotate(4, "type_ids_size:   " + Hex.u4(sz));
        out.annotate(4, "type_ids_off:    " + Hex.u4(offset));
    }

    out.writeInt(sz);
    out.writeInt(offset);
}
 
Example #2
Source File: TypeIdsSection.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the portion of the file header that refers to this instance.
 *
 * @param out {@code non-null;} where to write
 */
public void writeHeaderPart(AnnotatedOutput out) {
    throwIfNotPrepared();

    int sz = typeIds.size();
    int offset = (sz == 0) ? 0 : getFileOffset();

    if (sz > DexFormat.MAX_TYPE_IDX + 1) {
        throw new DexIndexOverflowException("Too many type references: " + sz +
                "; max is " + (DexFormat.MAX_TYPE_IDX + 1) + ".\n" +
                Main.getTooManyIdsErrorMessage());
    }

    if (out.annotates()) {
        out.annotate(4, "type_ids_size:   " + Hex.u4(sz));
        out.annotate(4, "type_ids_off:    " + Hex.u4(offset));
    }

    out.writeInt(sz);
    out.writeInt(offset);
}
 
Example #3
Source File: TypeIdsSection.java    From J2ME-Loader with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the portion of the file header that refers to this instance.
 *
 * @param out {@code non-null;} where to write
 */
public void writeHeaderPart(AnnotatedOutput out) {
    throwIfNotPrepared();

    int sz = typeIds.size();
    int offset = (sz == 0) ? 0 : getFileOffset();

    if (sz > DexFormat.MAX_TYPE_IDX + 1) {
        throw new DexIndexOverflowException(
                String.format("Too many type identifiers to fit in one dex file: %1$d; max is %2$d.%n"
                                + "You may try using multi-dex. If multi-dex is enabled then the list of "
                                + "classes for the main dex list is too large.",
                        items().size(), DexFormat.MAX_MEMBER_IDX + 1));
    }

    if (out.annotates()) {
        out.annotate(4, "type_ids_size:   " + Hex.u4(sz));
        out.annotate(4, "type_ids_off:    " + Hex.u4(offset));
    }

    out.writeInt(sz);
    out.writeInt(offset);
}
 
Example #4
Source File: TypeIdsSection.java    From Box with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the portion of the file header that refers to this instance.
 *
 * @param out {@code non-null;} where to write
 */
public void writeHeaderPart(AnnotatedOutput out) {
    throwIfNotPrepared();

    int sz = typeIds.size();
    int offset = (sz == 0) ? 0 : getFileOffset();

    if (sz > DexFormat.MAX_TYPE_IDX + 1) {
        throw new DexIndexOverflowException(
                String.format("Too many type identifiers to fit in one dex file: %1$d; max is %2$d.%n"
                                + "You may try using multi-dex. If multi-dex is enabled then the list of "
                                + "classes for the main dex list is too large.",
                        items().size(), DexFormat.MAX_MEMBER_IDX + 1));
    }

    if (out.annotates()) {
        out.annotate(4, "type_ids_size:   " + Hex.u4(sz));
        out.annotate(4, "type_ids_off:    " + Hex.u4(offset));
    }

    out.writeInt(sz);
    out.writeInt(offset);
}
 
Example #5
Source File: MemberIdsSection.java    From Box with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void orderItems() {
    int idx = 0;

    if (items().size() > DexFormat.MAX_MEMBER_IDX + 1) {
        throw new DexIndexOverflowException(getTooManyMembersMessage());
    }

    for (Object i : items()) {
        ((MemberIdItem) i).setIndex(idx);
        idx++;
    }
}
 
Example #6
Source File: Main.java    From buck with Apache License 2.0 5 votes vote down vote up
private static String getDexFileName(int i) {
    if (i == 0) {
        return DexFormat.DEX_IN_JAR_NAME;
    } else {
        return DEX_PREFIX + (i + 1) + DEX_EXTENSION;
    }
}
 
Example #7
Source File: MemberIdsSection.java    From buck with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void orderItems() {
    int idx = 0;

    if (items().size() > DexFormat.MAX_MEMBER_IDX + 1) {
        throw new DexIndexOverflowException(getTooManyMembersMessage());
    }

    for (Object i : items()) {
        ((MemberIdItem) i).setIndex(idx);
        idx++;
    }
}
 
Example #8
Source File: Main.java    From J2ME-Loader with Apache License 2.0 5 votes vote down vote up
/**
 * Parses all command-line arguments and updates the state of the {@code Arguments} object
 * accordingly.
 *
 * @param args {@code non-null;} the arguments
 */
private void parse(String[] args) {
    ArgumentsParser parser = new ArgumentsParser(args);

    parseFlags(parser);

    fileNames = parser.getRemaining();
    if(inputList != null && !inputList.isEmpty()) {
        // append the file names to the end of the input list
        inputList.addAll(Arrays.asList(fileNames));
        fileNames = inputList.toArray(new String[inputList.size()]);
    }

    if (fileNames.length == 0) {
        if (!emptyOk) {
            context.err.println("no input files specified");
            throw new UsageException();
        }
    } else if (emptyOk) {
        context.out.println("ignoring input files");
    }

    if ((humanOutName == null) && (methodToDump != null)) {
        humanOutName = "-";
    }

    if (outputIsDirectory) {
        outName = new File(outName, DexFormat.DEX_IN_JAR_NAME).getPath();
    }

    makeOptionsObjects();
}
 
Example #9
Source File: Main.java    From J2ME-Loader with Apache License 2.0 5 votes vote down vote up
private int runMonoDex() throws IOException {

        if (!processAllFiles()) {
            return 1;
        }

        // this array is null if no classes were defined
        byte[] outArray = null;

        if (!outputDex.isEmpty() || (args.humanOutName != null)) {
            outArray = writeDex(outputDex);

            if (outArray == null) {
                return 2;
            }
        }

        if (args.jarOutput) {
            // Effectively free up the (often massive) DexFile memory.
            outputDex = null;

            if (outArray != null) {
                outputResources.put(DexFormat.DEX_IN_JAR_NAME, outArray);
            }
            if (!createJar(args.outName)) {
                return 3;
            }
        } else if (outArray != null && args.outName != null) {
            OutputStream out = openOutput(args.outName);
            out.write(outArray);
            closeOutput(out);
        }

        return 0;
    }
 
Example #10
Source File: MemberIdsSection.java    From J2ME-Loader with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void orderItems() {
    int idx = 0;

    if (items().size() > DexFormat.MAX_MEMBER_IDX + 1) {
        throw new DexIndexOverflowException(getTooManyMembersMessage());
    }

    for (Object i : items()) {
        ((MemberIdItem) i).setIndex(idx);
        idx++;
    }
}
 
Example #11
Source File: Main.java    From Box with Apache License 2.0 5 votes vote down vote up
private static String getDexFileName(int i) {
    if (i == 0) {
        return DexFormat.DEX_IN_JAR_NAME;
    } else {
        return DEX_PREFIX + (i + 1) + DEX_EXTENSION;
    }
}
 
Example #12
Source File: Simulator.java    From Box with Apache License 2.0 5 votes vote down vote up
private void checkInvokeSignaturePolymorphic(final int opcode) {
    if (!dexOptions.apiIsSupported(DexFormat.API_METHOD_HANDLES)) {
        fail(String.format(
            "invoking a signature-polymorphic requires --min-sdk-version >= %d (currently %d)",
            DexFormat.API_METHOD_HANDLES, dexOptions.minSdkVersion));
    } else if (opcode != ByteOps.INVOKEVIRTUAL) {
        fail("Unsupported signature polymorphic invocation (" + ByteOps.opName(opcode) + ")");
    }
}
 
Example #13
Source File: Simulator.java    From Box with Apache License 2.0 5 votes vote down vote up
private void checkInterfaceMethodDeclaration(ConcreteMethod declaredMethod) {
    if (!dexOptions.apiIsSupported(DexFormat.API_DEFINE_INTERFACE_METHODS)) {
        String reason
            = String.format(
                "defining a %s interface method requires --min-sdk-version >= %d (currently %d)"
                + " for interface methods: %s.%s",
                declaredMethod.isStaticMethod() ? "static" : "default",
                DexFormat.API_DEFINE_INTERFACE_METHODS, dexOptions.minSdkVersion,
                declaredMethod.getDefiningClass().toHuman(), declaredMethod.getNat().toHuman());
        warn(reason);
    }
}
 
Example #14
Source File: Simulator.java    From Box with Apache License 2.0 5 votes vote down vote up
private void checkInvokeDynamicSupported(int opcode) throws SimException {
    if (!dexOptions.apiIsSupported(DexFormat.API_METHOD_HANDLES)) {
        fail(String.format("invalid opcode %02x - invokedynamic requires " +
                           "--min-sdk-version >= %d (currently %d)",
                           opcode, DexFormat.API_METHOD_HANDLES, dexOptions.minSdkVersion));
    }
}
 
Example #15
Source File: Simulator.java    From Box with Apache License 2.0 5 votes vote down vote up
private void checkConstMethodHandleSupported(Constant cst) throws SimException {
    if (!dexOptions.apiIsSupported(DexFormat.API_CONST_METHOD_HANDLE)) {
        fail(String.format("invalid constant type %s requires --min-sdk-version >= %d " +
                           "(currently %d)",
                           cst.typeName(), DexFormat.API_CONST_METHOD_HANDLE,
                           dexOptions.minSdkVersion));
    }
}
 
Example #16
Source File: MemberIdsSection.java    From Box with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void orderItems() {
    int idx = 0;

    if (items().size() > DexFormat.MAX_MEMBER_IDX + 1) {
        throw new DexIndexOverflowException(getTooManyMembersMessage());
    }

    for (Object i : items()) {
        ((MemberIdItem) i).setIndex(idx);
        idx++;
    }
}
 
Example #17
Source File: Main.java    From Box with Apache License 2.0 5 votes vote down vote up
private static String getDexFileName(int i) {
    if (i == 0) {
        return DexFormat.DEX_IN_JAR_NAME;
    } else {
        return DEX_PREFIX + (i + 1) + DEX_EXTENSION;
    }
}
 
Example #18
Source File: Simulator.java    From Box with Apache License 2.0 5 votes vote down vote up
private void checkInvokeSignaturePolymorphic(final int opcode) {
    if (!dexOptions.apiIsSupported(DexFormat.API_METHOD_HANDLES)) {
        fail(String.format(
            "invoking a signature-polymorphic requires --min-sdk-version >= %d (currently %d)",
            DexFormat.API_METHOD_HANDLES, dexOptions.minSdkVersion));
    } else if (opcode != ByteOps.INVOKEVIRTUAL) {
        fail("Unsupported signature polymorphic invocation (" + ByteOps.opName(opcode) + ")");
    }
}
 
Example #19
Source File: Simulator.java    From Box with Apache License 2.0 5 votes vote down vote up
private void checkInterfaceMethodDeclaration(ConcreteMethod declaredMethod) {
    if (!dexOptions.apiIsSupported(DexFormat.API_DEFINE_INTERFACE_METHODS)) {
        String reason
            = String.format(
                "defining a %s interface method requires --min-sdk-version >= %d (currently %d)"
                + " for interface methods: %s.%s",
                declaredMethod.isStaticMethod() ? "static" : "default",
                DexFormat.API_DEFINE_INTERFACE_METHODS, dexOptions.minSdkVersion,
                declaredMethod.getDefiningClass().toHuman(), declaredMethod.getNat().toHuman());
        warn(reason);
    }
}
 
Example #20
Source File: Simulator.java    From Box with Apache License 2.0 5 votes vote down vote up
private void checkConstMethodHandleSupported(Constant cst) throws SimException {
    if (!dexOptions.apiIsSupported(DexFormat.API_CONST_METHOD_HANDLE)) {
        fail(String.format("invalid constant type %s requires --min-sdk-version >= %d " +
                           "(currently %d)",
                           cst.typeName(), DexFormat.API_CONST_METHOD_HANDLE,
                           dexOptions.minSdkVersion));
    }
}
 
Example #21
Source File: Simulator.java    From Box with Apache License 2.0 5 votes vote down vote up
private void checkInvokeDynamicSupported(int opcode) throws SimException {
    if (!dexOptions.apiIsSupported(DexFormat.API_METHOD_HANDLES)) {
        fail(String.format("invalid opcode %02x - invokedynamic requires " +
                           "--min-sdk-version >= %d (currently %d)",
                           opcode, DexFormat.API_METHOD_HANDLES, dexOptions.minSdkVersion));
    }
}
 
Example #22
Source File: DexOptions.java    From J2ME-Loader with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the dex file magic number corresponding to this instance.
 */
public String getMagic() {
    return DexFormat.apiToMagic(minSdkVersion);
}
 
Example #23
Source File: Main.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Parses all command-line arguments.
 *
 * @param args {@code non-null;} the arguments
 * @param context
 */
public void parseCommandLine(String[] args, DxContext context) {
    ArgumentsParser parser = new ArgumentsParser(args);

    OutputOptions outputOptions = parseFlags(parser);

    fileNames = parser.getRemaining();
    if(inputList != null && !inputList.isEmpty()) {
        // append the file names to the end of the input list
        inputList.addAll(Arrays.asList(fileNames));
        fileNames = inputList.toArray(new String[0]);
    }

    if (fileNames.length == 0) {
        if (!emptyOk) {
            err.println("no input files specified");
            throw new UsageException();
        }
    } else if (emptyOk) {
        out.println("ignoring input files");
    }

    if ((humanOutName == null) && (methodToDump != null)) {
        humanOutName = "-";
    }

    if (mainDexListFile != null && !multiDex) {
        err.println(MAIN_DEX_LIST_OPTION + " is only supported in combination with "
            + MULTI_DEX_OPTION);
        throw new UsageException();
    }

    if (minimalMainDex && (mainDexListFile == null || !multiDex)) {
        err.println(MINIMAL_MAIN_DEX_OPTION + " is only supported in combination with "
            + MULTI_DEX_OPTION + " and " + MAIN_DEX_LIST_OPTION);
        throw new UsageException();
    }

    if (multiDex && incremental) {
        err.println(INCREMENTAL_OPTION + " is not supported with "
            + MULTI_DEX_OPTION);
        throw new UsageException();
    }

    if (multiDex && outputOptions.outputIsDirectDex) {
        err.println("Unsupported output \"" + outName +"\". " + MULTI_DEX_OPTION +
            " supports only archive or directory output");
        throw new UsageException();
    }

    if (outputOptions.outputIsDirectory && !multiDex) {
        outName = new File(outName, DexFormat.DEX_IN_JAR_NAME).getPath();
    }

    makeOptionsObjects(context);
}
 
Example #24
Source File: Main.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Processes one file, which may be either a class or a resource.
 *
 * @param name {@code non-null;} name of the file
 * @param bytes {@code non-null;} contents of the file
 * @return whether processing was successful
 */
private boolean processFileBytes(String name, long lastModified, byte[] bytes) {

    boolean isClass = name.endsWith(".class");
    boolean isClassesDex = name.equals(DexFormat.DEX_IN_JAR_NAME);
    boolean keepResources = (outputResources != null);

    if (!isClass && !isClassesDex && !keepResources) {
        if (args.verbose) {
            context.out.println("ignored resource " + name);
        }
        return false;
    }

    if (args.verbose) {
        context.out.println("processing " + name + "...");
    }

    String fixedName = fixPath(name);

    if (isClass) {

        if (keepResources && args.keepClassesInJar) {
            synchronized (outputResources) {
                outputResources.put(fixedName, bytes);
            }
        }
        if (lastModified < minimumFileAge) {
            return true;
        }
        processClass(fixedName, bytes);
        // Assume that an exception may occur. Status will be updated
        // asynchronously, if the class compiles without error.
        return false;
    } else if (isClassesDex) {
        synchronized (libraryDexBuffers) {
            libraryDexBuffers.add(bytes);
        }
        return true;
    } else {
        synchronized (outputResources) {
            outputResources.put(fixedName, bytes);
        }
        return true;
    }
}
 
Example #25
Source File: DexFile.java    From Box with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs an instance. It is initially empty.
 *
 * @param dexOptions {@code non-null;} DEX file generations options to apply
 */
public DexFile(final DexOptions dexOptions) {
    this.dexOptions = dexOptions;

    header = new HeaderSection(this);
    typeLists = new MixedItemSection(null, this, 4, SortType.NONE);
    wordData = new MixedItemSection("word_data", this, 4, SortType.TYPE);
    stringData =
        new MixedItemSection("string_data", this, 1, SortType.INSTANCE);
    classData = new MixedItemSection(null, this, 1, SortType.NONE);
    byteData = new MixedItemSection("byte_data", this, 1, SortType.TYPE);
    stringIds = new StringIdsSection(this);
    typeIds = new TypeIdsSection(this);
    protoIds = new ProtoIdsSection(this);
    fieldIds = new FieldIdsSection(this);
    methodIds = new MethodIdsSection(this);
    classDefs = new ClassDefsSection(this);
    map = new MixedItemSection("map", this, 4, SortType.NONE);

    /*
     * Prepare the list of sections in the order they appear in
     * the final output.
     */
    if (dexOptions.apiIsSupported(DexFormat.API_METHOD_HANDLES)) {
        /*
         * Method handles and call sites only visible in DEX files
         * from SDK version 26 onwards. Do not create or add sections unless
         * version true. This is conditional to avoid churn in the dx tests
         * that look at annotated output.
         */
        callSiteIds = new CallSiteIdsSection(this);
        methodHandles = new MethodHandlesSection(this);

        sections = new Section[] {
            header, stringIds, typeIds, protoIds, fieldIds, methodIds, classDefs,
            callSiteIds, methodHandles,
            wordData, typeLists, stringData, byteData, classData, map };
    } else {
        callSiteIds = null;
        methodHandles = null;

        sections = new Section[] {
            header, stringIds, typeIds, protoIds, fieldIds, methodIds, classDefs,
            wordData, typeLists, stringData, byteData, classData, map };
    }

    fileSize = -1;
    dumpWidth = 79;
}
 
Example #26
Source File: DexOptions.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the dex file magic number corresponding to this instance.
 */
public String getMagic() {
    return DexFormat.apiToMagic(targetApiLevel);
}
 
Example #27
Source File: HeaderItem.java    From buck with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void writeTo(DexFile file, AnnotatedOutput out) {
    int mapOff = file.getMap().getFileOffset();
    Section firstDataSection = file.getFirstDataSection();
    Section lastDataSection = file.getLastDataSection();
    int dataOff = firstDataSection.getFileOffset();
    int dataSize = lastDataSection.getFileOffset() +
        lastDataSection.writeSize() - dataOff;

    String magic = file.getDexOptions().getMagic();

    if (out.annotates()) {
        out.annotate(8, "magic: " + new CstString(magic).toQuoted());
        out.annotate(4, "checksum");
        out.annotate(20, "signature");
        out.annotate(4, "file_size:       " +
                     Hex.u4(file.getFileSize()));
        out.annotate(4, "header_size:     " + Hex.u4(SizeOf.HEADER_ITEM));
        out.annotate(4, "endian_tag:      " + Hex.u4(DexFormat.ENDIAN_TAG));
        out.annotate(4, "link_size:       0");
        out.annotate(4, "link_off:        0");
        out.annotate(4, "map_off:         " + Hex.u4(mapOff));
    }

    // Write the magic number.
    for (int i = 0; i < 8; i++) {
        out.writeByte(magic.charAt(i));
    }

    // Leave space for the checksum and signature.
    out.writeZeroes(24);

    out.writeInt(file.getFileSize());
    out.writeInt(SizeOf.HEADER_ITEM);
    out.writeInt(DexFormat.ENDIAN_TAG);

    /*
     * Write zeroes for the link size and data, as the output
     * isn't a staticly linked file.
     */
    out.writeZeroes(8);

    out.writeInt(mapOff);

    // Write out each section's respective header part.
    file.getStringIds().writeHeaderPart(out);
    file.getTypeIds().writeHeaderPart(out);
    file.getProtoIds().writeHeaderPart(out);
    file.getFieldIds().writeHeaderPart(out);
    file.getMethodIds().writeHeaderPart(out);
    file.getClassDefs().writeHeaderPart(out);

    if (out.annotates()) {
        out.annotate(4, "data_size:       " + Hex.u4(dataSize));
        out.annotate(4, "data_off:        " + Hex.u4(dataOff));
    }

    out.writeInt(dataSize);
    out.writeInt(dataOff);
}
 
Example #28
Source File: HeaderItem.java    From Box with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void writeTo(DexFile file, AnnotatedOutput out) {
    int mapOff = file.getMap().getFileOffset();
    Section firstDataSection = file.getFirstDataSection();
    Section lastDataSection = file.getLastDataSection();
    int dataOff = firstDataSection.getFileOffset();
    int dataSize = lastDataSection.getFileOffset() +
        lastDataSection.writeSize() - dataOff;

    String magic = file.getDexOptions().getMagic();

    if (out.annotates()) {
        out.annotate(8, "magic: " + new CstString(magic).toQuoted());
        out.annotate(4, "checksum");
        out.annotate(20, "signature");
        out.annotate(4, "file_size:       " +
                     Hex.u4(file.getFileSize()));
        out.annotate(4, "header_size:     " + Hex.u4(SizeOf.HEADER_ITEM));
        out.annotate(4, "endian_tag:      " + Hex.u4(DexFormat.ENDIAN_TAG));
        out.annotate(4, "link_size:       0");
        out.annotate(4, "link_off:        0");
        out.annotate(4, "map_off:         " + Hex.u4(mapOff));
    }

    // Write the magic number.
    for (int i = 0; i < 8; i++) {
        out.writeByte(magic.charAt(i));
    }

    // Leave space for the checksum and signature.
    out.writeZeroes(24);

    out.writeInt(file.getFileSize());
    out.writeInt(SizeOf.HEADER_ITEM);
    out.writeInt(DexFormat.ENDIAN_TAG);

    /*
     * Write zeroes for the link size and data, as the output
     * isn't a staticly linked file.
     */
    out.writeZeroes(8);

    out.writeInt(mapOff);

    // Write out each section's respective header part.
    file.getStringIds().writeHeaderPart(out);
    file.getTypeIds().writeHeaderPart(out);
    file.getProtoIds().writeHeaderPart(out);
    file.getFieldIds().writeHeaderPart(out);
    file.getMethodIds().writeHeaderPart(out);
    file.getClassDefs().writeHeaderPart(out);

    if (out.annotates()) {
        out.annotate(4, "data_size:       " + Hex.u4(dataSize));
        out.annotate(4, "data_off:        " + Hex.u4(dataOff));
    }

    out.writeInt(dataSize);
    out.writeInt(dataOff);
}
 
Example #29
Source File: HeaderItem.java    From Box with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void writeTo(DexFile file, AnnotatedOutput out) {
    int mapOff = file.getMap().getFileOffset();
    Section firstDataSection = file.getFirstDataSection();
    Section lastDataSection = file.getLastDataSection();
    int dataOff = firstDataSection.getFileOffset();
    int dataSize = lastDataSection.getFileOffset() +
        lastDataSection.writeSize() - dataOff;

    String magic = file.getDexOptions().getMagic();

    if (out.annotates()) {
        out.annotate(8, "magic: " + new CstString(magic).toQuoted());
        out.annotate(4, "checksum");
        out.annotate(20, "signature");
        out.annotate(4, "file_size:       " +
                     Hex.u4(file.getFileSize()));
        out.annotate(4, "header_size:     " + Hex.u4(SizeOf.HEADER_ITEM));
        out.annotate(4, "endian_tag:      " + Hex.u4(DexFormat.ENDIAN_TAG));
        out.annotate(4, "link_size:       0");
        out.annotate(4, "link_off:        0");
        out.annotate(4, "map_off:         " + Hex.u4(mapOff));
    }

    // Write the magic number.
    for (int i = 0; i < 8; i++) {
        out.writeByte(magic.charAt(i));
    }

    // Leave space for the checksum and signature.
    out.writeZeroes(24);

    out.writeInt(file.getFileSize());
    out.writeInt(SizeOf.HEADER_ITEM);
    out.writeInt(DexFormat.ENDIAN_TAG);

    /*
     * Write zeroes for the link size and data, as the output
     * isn't a staticly linked file.
     */
    out.writeZeroes(8);

    out.writeInt(mapOff);

    // Write out each section's respective header part.
    file.getStringIds().writeHeaderPart(out);
    file.getTypeIds().writeHeaderPart(out);
    file.getProtoIds().writeHeaderPart(out);
    file.getFieldIds().writeHeaderPart(out);
    file.getMethodIds().writeHeaderPart(out);
    file.getClassDefs().writeHeaderPart(out);

    if (out.annotates()) {
        out.annotate(4, "data_size:       " + Hex.u4(dataSize));
        out.annotate(4, "data_off:        " + Hex.u4(dataOff));
    }

    out.writeInt(dataSize);
    out.writeInt(dataOff);
}
 
Example #30
Source File: HeaderItem.java    From J2ME-Loader with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void writeTo(DexFile file, AnnotatedOutput out) {
    int mapOff = file.getMap().getFileOffset();
    Section firstDataSection = file.getFirstDataSection();
    Section lastDataSection = file.getLastDataSection();
    int dataOff = firstDataSection.getFileOffset();
    int dataSize = lastDataSection.getFileOffset() +
        lastDataSection.writeSize() - dataOff;

    String magic = file.getDexOptions().getMagic();

    if (out.annotates()) {
        out.annotate(8, "magic: " + new CstString(magic).toQuoted());
        out.annotate(4, "checksum");
        out.annotate(20, "signature");
        out.annotate(4, "file_size:       " +
                     Hex.u4(file.getFileSize()));
        out.annotate(4, "header_size:     " + Hex.u4(SizeOf.HEADER_ITEM));
        out.annotate(4, "endian_tag:      " + Hex.u4(DexFormat.ENDIAN_TAG));
        out.annotate(4, "link_size:       0");
        out.annotate(4, "link_off:        0");
        out.annotate(4, "map_off:         " + Hex.u4(mapOff));
    }

    // Write the magic number.
    for (int i = 0; i < 8; i++) {
        out.writeByte(magic.charAt(i));
    }

    // Leave space for the checksum and signature.
    out.writeZeroes(24);

    out.writeInt(file.getFileSize());
    out.writeInt(SizeOf.HEADER_ITEM);
    out.writeInt(DexFormat.ENDIAN_TAG);

    /*
     * Write zeroes for the link size and data, as the output
     * isn't a staticly linked file.
     */
    out.writeZeroes(8);

    out.writeInt(mapOff);

    // Write out each section's respective header part.
    file.getStringIds().writeHeaderPart(out);
    file.getTypeIds().writeHeaderPart(out);
    file.getProtoIds().writeHeaderPart(out);
    file.getFieldIds().writeHeaderPart(out);
    file.getMethodIds().writeHeaderPart(out);
    file.getClassDefs().writeHeaderPart(out);

    if (out.annotates()) {
        out.annotate(4, "data_size:       " + Hex.u4(dataSize));
        out.annotate(4, "data_off:        " + Hex.u4(dataOff));
    }

    out.writeInt(dataSize);
    out.writeInt(dataOff);
}