com.android.dx.dex.code.PositionList Java Examples

The following examples show how to use com.android.dx.dex.code.PositionList. 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: Box   Author: lulululbj   File: DebugInfoDecoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validates an encoded debug info stream against data used to encode it,
 * throwing an exception if they do not match. Used to validate the
 * encoder.
 *
 * @param info encoded debug info
 * @param file {@code non-null;} file to refer to during decoding
 * @param ref {@code non-null;} method whose info is being decoded
 * @param code {@code non-null;} original code object that was encoded
 * @param isStatic whether the method is static
 */
public static void validateEncode(byte[] info, DexFile file,
        CstMethodRef ref, DalvCode code, boolean isStatic) {
    PositionList pl = code.getPositions();
    LocalList ll = code.getLocals();
    DalvInsnList insns = code.getInsns();
    int codeSize = insns.codeSize();
    int countRegisters = insns.getRegistersSize();

    try {
        validateEncode0(info, codeSize, countRegisters,
                isStatic, ref, file, pl, ll);
    } catch (RuntimeException ex) {
        System.err.println("instructions:");
        insns.debugPrint(System.err, "  ", true);
        System.err.println("local list:");
        ll.debugPrint(System.err, "  ");
        throw ExceptionWithContext.withContext(ex,
                "while processing " + ref.toHuman());
    }
}
 
Example #2
Source Project: Box   Author: lulululbj   File: DebugInfoEncoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds a list of position entries, sorted by ascending address.
 *
 * @return A sorted positions list
 */
private ArrayList<PositionList.Entry> buildSortedPositions() {
    int sz = (positions == null) ? 0 : positions.size();
    ArrayList<PositionList.Entry> result = new ArrayList(sz);

    for (int i = 0; i < sz; i++) {
        result.add(positions.get(i));
    }

    // Sort ascending by address.
    Collections.sort (result, new Comparator<PositionList.Entry>() {
        @Override
        public int compare (PositionList.Entry a, PositionList.Entry b) {
            return a.getAddress() - b.getAddress();
        }

        @Override
        public boolean equals (Object obj) {
           return obj == this;
        }
    });
    return result;
}
 
Example #3
Source Project: Box   Author: lulululbj   File: DebugInfoItem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper for {@link #encode} to do most of the work.
 *
 * @param file {@code null-ok;} file to refer to during encoding
 * @param prefix {@code null-ok;} prefix to attach to each line of output
 * @param debugPrint {@code null-ok;} if specified, an alternate output for
 * annotations
 * @param out {@code null-ok;} if specified, where annotations should go
 * @param consume whether to claim to have consumed output for
 * {@code out}
 * @return {@code non-null;} the encoded array
 */
private byte[] encode0(DexFile file, String prefix, PrintWriter debugPrint,
        AnnotatedOutput out, boolean consume) {
    PositionList positions = code.getPositions();
    LocalList locals = code.getLocals();
    DalvInsnList insns = code.getInsns();
    int codeSize = insns.codeSize();
    int regSize = insns.getRegistersSize();

    DebugInfoEncoder encoder =
        new DebugInfoEncoder(positions, locals,
                file, codeSize, regSize, isStatic, ref);

    byte[] result;

    if ((debugPrint == null) && (out == null)) {
        result = encoder.convert();
    } else {
        result = encoder.convertAndAnnotate(prefix, debugPrint, out,
                consume);
    }

    return result;
}
 
Example #4
Source Project: Box   Author: lulululbj   File: DebugInfoDecoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validates an encoded debug info stream against data used to encode it,
 * throwing an exception if they do not match. Used to validate the
 * encoder.
 *
 * @param info encoded debug info
 * @param file {@code non-null;} file to refer to during decoding
 * @param ref {@code non-null;} method whose info is being decoded
 * @param code {@code non-null;} original code object that was encoded
 * @param isStatic whether the method is static
 */
public static void validateEncode(byte[] info, DexFile file,
        CstMethodRef ref, DalvCode code, boolean isStatic) {
    PositionList pl = code.getPositions();
    LocalList ll = code.getLocals();
    DalvInsnList insns = code.getInsns();
    int codeSize = insns.codeSize();
    int countRegisters = insns.getRegistersSize();

    try {
        validateEncode0(info, codeSize, countRegisters,
                isStatic, ref, file, pl, ll);
    } catch (RuntimeException ex) {
        System.err.println("instructions:");
        insns.debugPrint(System.err, "  ", true);
        System.err.println("local list:");
        ll.debugPrint(System.err, "  ");
        throw ExceptionWithContext.withContext(ex,
                "while processing " + ref.toHuman());
    }
}
 
Example #5
Source Project: Box   Author: lulululbj   File: DebugInfoEncoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds a list of position entries, sorted by ascending address.
 *
 * @return A sorted positions list
 */
private ArrayList<PositionList.Entry> buildSortedPositions() {
    int sz = (positions == null) ? 0 : positions.size();
    ArrayList<PositionList.Entry> result = new ArrayList(sz);

    for (int i = 0; i < sz; i++) {
        result.add(positions.get(i));
    }

    // Sort ascending by address.
    Collections.sort (result, new Comparator<PositionList.Entry>() {
        @Override
        public int compare (PositionList.Entry a, PositionList.Entry b) {
            return a.getAddress() - b.getAddress();
        }

        @Override
        public boolean equals (Object obj) {
           return obj == this;
        }
    });
    return result;
}
 
Example #6
Source Project: Box   Author: lulululbj   File: DebugInfoItem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper for {@link #encode} to do most of the work.
 *
 * @param file {@code null-ok;} file to refer to during encoding
 * @param prefix {@code null-ok;} prefix to attach to each line of output
 * @param debugPrint {@code null-ok;} if specified, an alternate output for
 * annotations
 * @param out {@code null-ok;} if specified, where annotations should go
 * @param consume whether to claim to have consumed output for
 * {@code out}
 * @return {@code non-null;} the encoded array
 */
private byte[] encode0(DexFile file, String prefix, PrintWriter debugPrint,
        AnnotatedOutput out, boolean consume) {
    PositionList positions = code.getPositions();
    LocalList locals = code.getLocals();
    DalvInsnList insns = code.getInsns();
    int codeSize = insns.codeSize();
    int regSize = insns.getRegistersSize();

    DebugInfoEncoder encoder =
        new DebugInfoEncoder(positions, locals,
                file, codeSize, regSize, isStatic, ref);

    byte[] result;

    if ((debugPrint == null) && (out == null)) {
        result = encoder.convert();
    } else {
        result = encoder.convertAndAnnotate(prefix, debugPrint, out,
                consume);
    }

    return result;
}
 
Example #7
Source Project: J2ME-Loader   Author: nikita36078   File: DebugInfoDecoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validates an encoded debug info stream against data used to encode it,
 * throwing an exception if they do not match. Used to validate the
 * encoder.
 *
 * @param info encoded debug info
 * @param file {@code non-null;} file to refer to during decoding
 * @param ref {@code non-null;} method whose info is being decoded
 * @param code {@code non-null;} original code object that was encoded
 * @param isStatic whether the method is static
 */
public static void validateEncode(byte[] info, DexFile file,
        CstMethodRef ref, DalvCode code, boolean isStatic) {
    PositionList pl = code.getPositions();
    LocalList ll = code.getLocals();
    DalvInsnList insns = code.getInsns();
    int codeSize = insns.codeSize();
    int countRegisters = insns.getRegistersSize();

    try {
        validateEncode0(info, codeSize, countRegisters,
                isStatic, ref, file, pl, ll);
    } catch (RuntimeException ex) {
        System.err.println("instructions:");
        insns.debugPrint(System.err, "  ", true);
        System.err.println("local list:");
        ll.debugPrint(System.err, "  ");
        throw ExceptionWithContext.withContext(ex,
                "while processing " + ref.toHuman());
    }
}
 
Example #8
Source Project: J2ME-Loader   Author: nikita36078   File: DebugInfoEncoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
  * Builds a list of position entries, sorted by ascending address.
  *
  * @return A sorted positions list
  */
 private ArrayList<PositionList.Entry> buildSortedPositions() {
     int sz = (positions == null) ? 0 : positions.size();
     ArrayList<PositionList.Entry> result = new ArrayList(sz);

     for (int i = 0; i < sz; i++) {
         result.add(positions.get(i));
     }

     // Sort ascending by address.
     Collections.sort (result, new Comparator<PositionList.Entry>() {
         @Override
public int compare (PositionList.Entry a, PositionList.Entry b) {
             return a.getAddress() - b.getAddress();
         }

         public boolean equals (Object obj) {
            return obj == this;
         }
     });
     return result;
 }
 
Example #9
Source Project: J2ME-Loader   Author: nikita36078   File: DebugInfoItem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper for {@link #encode} to do most of the work.
 *
 * @param file {@code null-ok;} file to refer to during encoding
 * @param prefix {@code null-ok;} prefix to attach to each line of output
 * @param debugPrint {@code null-ok;} if specified, an alternate output for
 * annotations
 * @param out {@code null-ok;} if specified, where annotations should go
 * @param consume whether to claim to have consumed output for
 * {@code out}
 * @return {@code non-null;} the encoded array
 */
private byte[] encode0(DexFile file, String prefix, PrintWriter debugPrint,
        AnnotatedOutput out, boolean consume) {
    PositionList positions = code.getPositions();
    LocalList locals = code.getLocals();
    DalvInsnList insns = code.getInsns();
    int codeSize = insns.codeSize();
    int regSize = insns.getRegistersSize();

    DebugInfoEncoder encoder =
        new DebugInfoEncoder(positions, locals,
                file, codeSize, regSize, isStatic, ref);

    byte[] result;

    if ((debugPrint == null) && (out == null)) {
        result = encoder.convert();
    } else {
        result = encoder.convertAndAnnotate(prefix, debugPrint, out,
                consume);
    }

    return result;
}
 
Example #10
Source Project: buck   Author: facebook   File: DebugInfoDecoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validates an encoded debug info stream against data used to encode it,
 * throwing an exception if they do not match. Used to validate the
 * encoder.
 *
 * @param info encoded debug info
 * @param file {@code non-null;} file to refer to during decoding
 * @param ref {@code non-null;} method whose info is being decoded
 * @param code {@code non-null;} original code object that was encoded
 * @param isStatic whether the method is static
 */
public static void validateEncode(byte[] info, DexFile file,
        CstMethodRef ref, DalvCode code, boolean isStatic) {
    PositionList pl = code.getPositions();
    LocalList ll = code.getLocals();
    DalvInsnList insns = code.getInsns();
    int codeSize = insns.codeSize();
    int countRegisters = insns.getRegistersSize();

    try {
        validateEncode0(info, codeSize, countRegisters,
                isStatic, ref, file, pl, ll);
    } catch (RuntimeException ex) {
        System.err.println("instructions:");
        insns.debugPrint(System.err, "  ", true);
        System.err.println("local list:");
        ll.debugPrint(System.err, "  ");
        throw ExceptionWithContext.withContext(ex,
                "while processing " + ref.toHuman());
    }
}
 
Example #11
Source Project: buck   Author: facebook   File: DebugInfoEncoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds a list of position entries, sorted by ascending address.
 *
 * @return A sorted positions list
 */
private ArrayList<PositionList.Entry> buildSortedPositions() {
    int sz = (positions == null) ? 0 : positions.size();
    ArrayList<PositionList.Entry> result = new ArrayList(sz);

    for (int i = 0; i < sz; i++) {
        result.add(positions.get(i));
    }

    // Sort ascending by address.
    Collections.sort (result, new Comparator<PositionList.Entry>() {
        public int compare (PositionList.Entry a, PositionList.Entry b) {
            return a.getAddress() - b.getAddress();
        }

        public boolean equals (Object obj) {
           return obj == this;
        }
    });
    return result;
}
 
Example #12
Source Project: buck   Author: facebook   File: DebugInfoItem.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper for {@link #encode} to do most of the work.
 *
 * @param file {@code null-ok;} file to refer to during encoding
 * @param prefix {@code null-ok;} prefix to attach to each line of output
 * @param debugPrint {@code null-ok;} if specified, an alternate output for
 * annotations
 * @param out {@code null-ok;} if specified, where annotations should go
 * @param consume whether to claim to have consumed output for
 * {@code out}
 * @return {@code non-null;} the encoded array
 */
private byte[] encode0(DexFile file, String prefix, PrintWriter debugPrint,
        AnnotatedOutput out, boolean consume) {
    PositionList positions = code.getPositions();
    LocalList locals = code.getLocals();
    DalvInsnList insns = code.getInsns();
    int codeSize = insns.codeSize();
    int regSize = insns.getRegistersSize();

    DebugInfoEncoder encoder =
        new DebugInfoEncoder(positions, locals,
                file, codeSize, regSize, isStatic, ref);

    byte[] result;

    if ((debugPrint == null) && (out == null)) {
        result = encoder.convert();
    } else {
        result = encoder.convertAndAnnotate(prefix, debugPrint, out,
                consume);
    }

    return result;
}
 
Example #13
Source Project: Box   Author: lulululbj   File: DebugInfoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance.
 *
 * @param positions {@code null-ok;} positions (line numbers) to encode
 * @param locals {@code null-ok;} local variables to encode
 * @param file {@code null-ok;} may only be {@code null} if simply using
 * this class to do a debug print
 * @param codeSize
 * @param regSize
 * @param isStatic
 * @param ref
 */
public DebugInfoEncoder(PositionList positions, LocalList locals,
        DexFile file, int codeSize, int regSize,
        boolean isStatic, CstMethodRef ref) {
    this.positions = positions;
    this.locals = locals;
    this.file = file;
    this.desc = ref.getPrototype();
    this.isStatic = isStatic;
    this.codeSize = codeSize;
    this.regSize = regSize;

    output = new ByteArrayAnnotatedOutput();
    lastEntryForReg = new LocalList.Entry[regSize];
}
 
Example #14
Source Project: Box   Author: lulululbj   File: DebugInfoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Emits all positions that occur at the current {@code address}
 *
 * @param curPositionIdx Current index in sortedPositions
 * @param sortedPositions positions, sorted by ascending address
 * @return new value for {@code curPositionIdx}
 * @throws IOException
 */
private int emitPositionsAtAddress(int curPositionIdx,
        ArrayList<PositionList.Entry> sortedPositions)
        throws IOException {
    int positionsSz = sortedPositions.size();
    while ((curPositionIdx < positionsSz)
            && (sortedPositions.get(curPositionIdx).getAddress()
                    == address)) {
        emitPosition(sortedPositions.get(curPositionIdx++));
    }
    return curPositionIdx;
}
 
Example #15
Source Project: Box   Author: lulululbj   File: DebugInfoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance.
 *
 * @param positions {@code null-ok;} positions (line numbers) to encode
 * @param locals {@code null-ok;} local variables to encode
 * @param file {@code null-ok;} may only be {@code null} if simply using
 * this class to do a debug print
 * @param codeSize
 * @param regSize
 * @param isStatic
 * @param ref
 */
public DebugInfoEncoder(PositionList positions, LocalList locals,
        DexFile file, int codeSize, int regSize,
        boolean isStatic, CstMethodRef ref) {
    this.positions = positions;
    this.locals = locals;
    this.file = file;
    this.desc = ref.getPrototype();
    this.isStatic = isStatic;
    this.codeSize = codeSize;
    this.regSize = regSize;

    output = new ByteArrayAnnotatedOutput();
    lastEntryForReg = new LocalList.Entry[regSize];
}
 
Example #16
Source Project: Box   Author: lulululbj   File: DebugInfoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Emits all positions that occur at the current {@code address}
 *
 * @param curPositionIdx Current index in sortedPositions
 * @param sortedPositions positions, sorted by ascending address
 * @return new value for {@code curPositionIdx}
 * @throws IOException
 */
private int emitPositionsAtAddress(int curPositionIdx,
        ArrayList<PositionList.Entry> sortedPositions)
        throws IOException {
    int positionsSz = sortedPositions.size();
    while ((curPositionIdx < positionsSz)
            && (sortedPositions.get(curPositionIdx).getAddress()
                    == address)) {
        emitPosition(sortedPositions.get(curPositionIdx++));
    }
    return curPositionIdx;
}
 
Example #17
Source Project: lua-for-android   Author: qtiuto   File: DexMaker.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
EncodedMethod toEncodedMethod(DexOptions dexOptions) {
    if (code != null) {
        RopMethod ropMethod = new RopMethod(code.toBasicBlocks(), 0);
        LocalVariableInfo locals = null;
        DalvCode dalvCode = RopTranslator.translate(
                ropMethod, PositionList.NONE, locals, code.paramSize(), dexOptions);
        return new EncodedMethod(method.constant, flags, dalvCode, StdTypeList.EMPTY);
    } else return new EncodedMethod(method.constant, flags, null, StdTypeList.EMPTY);

}
 
Example #18
Source Project: J2ME-Loader   Author: nikita36078   File: DebugInfoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance.
 *
 * @param positions {@code null-ok;} positions (line numbers) to encode
 * @param locals {@code null-ok;} local variables to encode
 * @param file {@code null-ok;} may only be {@code null} if simply using
 * this class to do a debug print
 * @param codeSize
 * @param regSize
 * @param isStatic
 * @param ref
 */
public DebugInfoEncoder(PositionList positions, LocalList locals,
        DexFile file, int codeSize, int regSize,
        boolean isStatic, CstMethodRef ref) {
    this.positions = positions;
    this.locals = locals;
    this.file = file;
    this.desc = ref.getPrototype();
    this.isStatic = isStatic;
    this.codeSize = codeSize;
    this.regSize = regSize;

    output = new ByteArrayAnnotatedOutput();
    lastEntryForReg = new LocalList.Entry[regSize];
}
 
Example #19
Source Project: J2ME-Loader   Author: nikita36078   File: DebugInfoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Emits all positions that occur at the current {@code address}
 *
 * @param curPositionIdx Current index in sortedPositions
 * @param sortedPositions positions, sorted by ascending address
 * @return new value for {@code curPositionIdx}
 * @throws IOException
 */
private int emitPositionsAtAddress(int curPositionIdx,
        ArrayList<PositionList.Entry> sortedPositions)
        throws IOException {
    int positionsSz = sortedPositions.size();
    while ((curPositionIdx < positionsSz)
            && (sortedPositions.get(curPositionIdx).getAddress()
                    == address)) {
        emitPosition(sortedPositions.get(curPositionIdx++));
    }
    return curPositionIdx;
}
 
Example #20
Source Project: dexmaker   Author: linkedin   File: DexMaker.java    License: Apache License 2.0 5 votes vote down vote up
EncodedMethod toEncodedMethod(DexOptions dexOptions) {
    if((flags & ABSTRACT) != 0 || (flags & NATIVE) != 0){
        return new EncodedMethod(method.constant, flags, null, StdTypeList.EMPTY);
    }

    RopMethod ropMethod = new RopMethod(code.toBasicBlocks(), 0);
    LocalVariableInfo locals = null;
    DalvCode dalvCode = RopTranslator.translate(
            ropMethod, PositionList.NONE, locals, code.paramSize(), dexOptions);
    return new EncodedMethod(method.constant, flags, dalvCode, StdTypeList.EMPTY);
}
 
Example #21
Source Project: bazel   Author: bazelbuild   File: Dexing.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Integer convert(String input) throws OptionsParsingException {
  for (Field field : PositionList.class.getFields()) {
    if (field.getName().equalsIgnoreCase(input)) {
      try {
        return field.getInt(null);
      } catch (RuntimeException | IllegalAccessException e) {
        throw new OptionsParsingException("Can't parse positions option", input, e);
      }
    }
  }
  throw new OptionsParsingException("Unknown positions option", input);
}
 
Example #22
Source Project: bazel   Author: bazelbuild   File: DexBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildDexArchive() throws Exception {
  DexBuilder.Options options = new DexBuilder.Options();
  // Use Jar file that has this test in it as the input Jar
  Runfiles runfiles = Runfiles.create();
  options.inputJar = Paths.get(runfiles.rlocation(System.getProperty("testinputjar")));
  options.outputZip =
      FileSystems.getDefault().getPath(System.getenv("TEST_TMPDIR"), "dex_builder_test.zip");
  options.maxThreads = 1;
  Dexing.DexingOptions dexingOptions = new Dexing.DexingOptions();
  dexingOptions.optimize = true;
  dexingOptions.positionInfo = PositionList.LINES;
  DexBuilder.buildDexArchive(options, new Dexing(dexingOptions));
  assertThat(options.outputZip.toFile().exists()).isTrue();

  HashSet<String> files = new HashSet<>();
  try (ZipFile zip = new ZipFile(options.outputZip.toFile())) {
    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = entries.nextElement();
      files.add(entry.getName());
      if (entry.getName().endsWith(".dex")) {
        Dex dex = new Dex(zip.getInputStream(entry));
        assertWithMessage(entry.getName()).that(dex.classDefs()).hasSize(1);
      } else if (entry.getName().endsWith("/testresource.txt")) {
        byte[] content = ByteStreams.toByteArray(zip.getInputStream(entry));
        assertWithMessage(entry.getName()).that(content).isEqualTo("test".getBytes(UTF_8));
      }
    }
  }
  // Make sure this test is in the Zip file, which also means we parsed its dex code above
  assertThat(files).contains(getClass().getName().replace('.', '/') + ".class.dex");
  // Make sure test resource is in the Zip file, which also means it had the expected content
  assertThat(files)
      .contains(getClass().getPackage().getName().replace('.', '/') + "/testresource.txt");
}
 
Example #23
Source Project: bazel   Author: bazelbuild   File: DexFileMergerTest.java    License: Apache License 2.0 5 votes vote down vote up
private Path buildDexArchive(Path inputJar, String outputZip) throws Exception {
  DexBuilder.Options options = new DexBuilder.Options();
  options.inputJar = inputJar;
  options.outputZip = FileSystems.getDefault().getPath(System.getenv("TEST_TMPDIR"), outputZip);
  options.maxThreads = 1;
  Dexing.DexingOptions dexingOptions = new Dexing.DexingOptions();
  dexingOptions.optimize = true;
  dexingOptions.positionInfo = PositionList.LINES;
  DexBuilder.buildDexArchive(options, new Dexing(new DxContext(), dexingOptions));
  return options.outputZip;
}
 
Example #24
Source Project: bazel   Author: bazelbuild   File: DexFileSplitterTest.java    License: Apache License 2.0 5 votes vote down vote up
private Path buildDexArchive(Path inputJar, String outputZip) throws Exception {
  DexBuilder.Options options = new DexBuilder.Options();
  // Use Jar file that has this test in it as the input Jar
  options.inputJar = inputJar;
  options.outputZip =
      FileSystems.getDefault().getPath(System.getenv("TEST_TMPDIR"), outputZip);
  options.maxThreads = 1;
  Dexing.DexingOptions dexingOptions = new Dexing.DexingOptions();
  dexingOptions.optimize = true;
  dexingOptions.positionInfo = PositionList.LINES;
  DexBuilder.buildDexArchive(options, new Dexing(new DxContext(), dexingOptions));
  return options.outputZip;
}
 
Example #25
Source Project: bazel   Author: bazelbuild   File: DexConversionEnqueuerTest.java    License: Apache License 2.0 5 votes vote down vote up
private byte[] testConvertClassToDex() throws Exception {
  String filename = getClass().getName().replace('.', '/') + ".class";
  byte[] bytecode = mockClassFile(filename);

  stuffer.call();
  Future<ZipEntryContent> f = stuffer.getFiles().remove();
  assertThat(f.isDone()).isTrue();
  byte[] dexcode = f.get().getContent();
  assertThat(f.get().getEntry().getName()).isEqualTo(filename + ".dex");
  assertThat(f.get().getEntry().getTime()).isEqualTo(FILE_TIME);
  assertThat(f.get().getEntry().getSize()).isEqualTo(dexcode.length);
  assertThat(f.get().getEntry().getCompressedSize()).isEqualTo(dexcode.length);

  Dex dex = new Dex(dexcode);
  assertThat(dex.classDefs()).hasSize(1);
  assertThat(cache.getIfPresent(DexingKey.create(false, false, PositionList.LINES, 13, bytecode)))
      .isSameInstanceAs(dexcode);
  assertThat(cache.getIfPresent(DexingKey.create(false, false, PositionList.NONE, 13, bytecode)))
      .isNull();
  assertThat(cache.getIfPresent(DexingKey.create(true, false, PositionList.LINES, 13, bytecode)))
      .isNull();
  assertThat(cache.getIfPresent(DexingKey.create(false, true, PositionList.LINES, 13, bytecode)))
      .isNull();
  assertThat(cache.getIfPresent(DexingKey.create(true, true, PositionList.LINES, 13, bytecode)))
      .isNull();
  return dexcode;
}
 
Example #26
Source Project: buck   Author: facebook   File: DebugInfoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance.
 *
 * @param positions {@code null-ok;} positions (line numbers) to encode
 * @param locals {@code null-ok;} local variables to encode
 * @param file {@code null-ok;} may only be {@code null} if simply using
 * this class to do a debug print
 * @param codeSize
 * @param regSize
 * @param isStatic
 * @param ref
 */
public DebugInfoEncoder(PositionList positions, LocalList locals,
        DexFile file, int codeSize, int regSize,
        boolean isStatic, CstMethodRef ref) {
    this.positions = positions;
    this.locals = locals;
    this.file = file;
    this.desc = ref.getPrototype();
    this.isStatic = isStatic;
    this.codeSize = codeSize;
    this.regSize = regSize;

    output = new ByteArrayAnnotatedOutput();
    lastEntryForReg = new LocalList.Entry[regSize];
}
 
Example #27
Source Project: buck   Author: facebook   File: DebugInfoEncoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Emits all positions that occur at the current {@code address}
 *
 * @param curPositionIdx Current index in sortedPositions
 * @param sortedPositions positions, sorted by ascending address
 * @return new value for {@code curPositionIdx}
 * @throws IOException
 */
private int emitPositionsAtAddress(int curPositionIdx,
        ArrayList<PositionList.Entry> sortedPositions)
        throws IOException {
    int positionsSz = sortedPositions.size();
    while ((curPositionIdx < positionsSz)
            && (sortedPositions.get(curPositionIdx).getAddress()
                    == address)) {
        emitPosition(sortedPositions.get(curPositionIdx++));
    }
    return curPositionIdx;
}
 
Example #28
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 #29
Source Project: Box   Author: lulululbj   File: DebugInfoEncoder.java    License: Apache License 2.0 4 votes vote down vote up
private byte[] convert0() throws IOException {
    ArrayList<PositionList.Entry> sortedPositions = buildSortedPositions();
    ArrayList<LocalList.Entry> methodArgs = extractMethodArguments();

    emitHeader(sortedPositions, methodArgs);

    // TODO: Make this mark be the actual prologue end.
    output.writeByte(DBG_SET_PROLOGUE_END);

    if (annotateTo != null || debugPrint != null) {
        annotate(1, String.format("%04x: prologue end",address));
    }

    int positionsSz = sortedPositions.size();
    int localsSz = locals.size();

    // Current index in sortedPositions
    int curPositionIdx = 0;
    // Current index in locals
    int curLocalIdx = 0;

    for (;;) {
        /*
         * Emit any information for the current address.
         */

        curLocalIdx = emitLocalsAtAddress(curLocalIdx);
        curPositionIdx =
            emitPositionsAtAddress(curPositionIdx, sortedPositions);

        /*
         * Figure out what the next important address is.
         */

        int nextAddrL = Integer.MAX_VALUE; // local variable
        int nextAddrP = Integer.MAX_VALUE; // position (line number)

        if (curLocalIdx < localsSz) {
            nextAddrL = locals.get(curLocalIdx).getAddress();
        }

        if (curPositionIdx < positionsSz) {
            nextAddrP = sortedPositions.get(curPositionIdx).getAddress();
        }

        int next = Math.min(nextAddrP, nextAddrL);

        // No next important address == done.
        if (next == Integer.MAX_VALUE) {
            break;
        }

        /*
         * If the only work remaining are local ends at the end of the
         * block, stop here. Those are implied anyway.
         */
        if (next == codeSize
                && nextAddrL == Integer.MAX_VALUE
                && nextAddrP == Integer.MAX_VALUE) {
            break;
        }

        if (next == nextAddrP) {
            // Combined advance PC + position entry
            emitPosition(sortedPositions.get(curPositionIdx++));
        } else {
            emitAdvancePc(next - address);
        }
    }

    emitEndSequence();

    return output.toByteArray();
}
 
Example #30
Source Project: Box   Author: lulululbj   File: DebugInfoEncoder.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Emits the necessary byte sequences to emit the given position table
 * entry. This will typically be a single special opcode, although
 * it may also require DBG_ADVANCE_PC or DBG_ADVANCE_LINE.
 *
 * @param entry position entry to emit.
 * @throws IOException
 */
private void emitPosition(PositionList.Entry entry)
        throws IOException {

    SourcePosition pos = entry.getPosition();
    int newLine = pos.getLine();
    int newAddress = entry.getAddress();

    int opcode;

    int deltaLines = newLine - line;
    int deltaAddress = newAddress - address;

    if (deltaAddress < 0) {
        throw new RuntimeException(
                "Position entries must be in ascending address order");
    }

    if ((deltaLines < DBG_LINE_BASE)
            || (deltaLines > (DBG_LINE_BASE + DBG_LINE_RANGE -1))) {
        emitAdvanceLine(deltaLines);
        deltaLines = 0;
    }

    opcode = computeOpcode (deltaLines, deltaAddress);

    if ((opcode & ~0xff) > 0) {
        emitAdvancePc(deltaAddress);
        deltaAddress = 0;
        opcode = computeOpcode (deltaLines, deltaAddress);

        if ((opcode & ~0xff) > 0) {
            emitAdvanceLine(deltaLines);
            deltaLines = 0;
            opcode = computeOpcode (deltaLines, deltaAddress);
        }
    }

    output.writeByte(opcode);

    line += deltaLines;
    address += deltaAddress;

    if (annotateTo != null || debugPrint != null) {
        annotate(1,
                String.format("%04x: line %d", address, line));
    }
}