com.igormaznitsa.jbbp.io.JBBPBitInputStream Java Examples

The following examples show how to use com.igormaznitsa.jbbp.io.JBBPBitInputStream. 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: JBBPOnlyFieldEvaluator.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Override
public int eval(final JBBPBitInputStream inStream, final int currentCompiledBlockOffset, final JBBPCompiledBlock block, final JBBPNamedNumericFieldMap fieldMap) {
  final int result;
  if (this.externalFieldName == null) {
    final JBBPNamedFieldInfo namedField = block.getNamedFields()[this.namedFieldIndex];
    final JBBPNumericField numericField = fieldMap.get(namedField);
    if (numericField == null) {
      throw new java.lang.ArithmeticException("Can't find field '" + namedField.getFieldName() + "' among numeric fields");
    } else {
      result = numericField.getAsInt();
    }
  } else {
    result = this.externalFieldName.equals("$")
        ? (int) inStream.getCounter()
        : fieldMap.getExternalFieldValue(this.externalFieldName, block, this);
  }
  return result;
}
 
Example #2
Source File: JBBPOnlyFieldEvaluatorTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testCounterOfStreamAsParameter() throws Exception {
  final List<JBBPNamedFieldInfo> list = new ArrayList<>();

  final byte[] compiled = new byte[] {0};
  final JBBPCompiledBlock compiledBlock = JBBPCompiledBlock.prepare().setCompiledData(compiled).setSource("none").setNamedFieldData(list).build();

  JBBPOnlyFieldEvaluator expr = new JBBPOnlyFieldEvaluator("$", -1);

  final JBBPBitInputStream inStream = new JBBPBitInputStream(new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5}));
  inStream.read();
  inStream.read();
  inStream.read();

  assertEquals(3, expr.eval(inStream, 0, compiledBlock, null));
}
 
Example #3
Source File: HOBETAPlugin.java    From zxpoly with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getImportingFileInfo(final File file) {
  try {
    JBBPBitInputStream in = null;
    try {
      final StringBuilder result = new StringBuilder();

      final Hobeta hobeta =
          HOBETA_FILE_PARSER.parse(new FileInputStream(file)).mapTo(new Hobeta());
      result.append("     Name:").append(hobeta.name).append("  ").append('\n');
      result.append("     Type:").append((char) hobeta.type).append("  ").append('\n');
      result.append("    Start:").append(hobeta.start).append("  ").append('\n');
      result.append("   Length:").append(hobeta.length).append(" bytes").append("  ")
          .append('\n');
      result.append("  Sectors:").append(hobeta.sectors).append(" sectors").append("  ");

      return result.toString();
    } finally {
      JBBPUtils.closeQuietly(in);
    }
  } catch (Exception ex) {
    return null;
  }
}
 
Example #4
Source File: TARawBlock.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public void parseUnits() throws IOException {
 unitList = new Vector<TAUnit>();
 JBBPParser unitblock = JBBPParser.prepare(
	    "         <int unitNumber;"
	           + "<int length;"
	           + "<int magic;"
	           + "<int unknown;"
    );
 
 JBBPBitInputStream unitsStream = new JBBPBitInputStream(new ByteArrayInputStream(units));
 try {
 while (unitsStream.hasAvailableData()) {
  TARawUnit rawunit = unitblock.parse(unitsStream).mapTo(new TARawUnit());
  rawunit.fetchContent(unitsStream);
  if (rawunit.isValid()) unitList.add(rawunit.getUnit());
 }
 } catch (Exception ioe) {}
 unitsStream.close();
}
 
Example #5
Source File: Parser.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
private static String getSin(String folder, byte[] source) throws Exception {
 Collection<File> sinfiles = FileUtils.listFiles(new File(folder), new String[] {"sin"}, true);
 Iterator<File> ifiles = sinfiles.iterator();
 while (ifiles.hasNext()) {
  try {
	  SinFile  sinfile = new SinFile(ifiles.next());
	  if (sinfile.getVersion()!=4) {
		  JBBPBitInputStream sinStream = new JBBPBitInputStream(new FileInputStream(sinfile.getFile()));
		  byte[] res = sinStream.readByteArray(source.length);
		  if (Arrays.equals(source, res))
			  return sinfile.getShortName();
	  }
	  else {
		  if (Arrays.equals(source, sinfile.getHeader())) return sinfile.getFile().getName();
	  }
  } catch (EOFException eof) {
  }			  
 }
 return "Not identified";
}
 
Example #6
Source File: TapeFileReader.java    From zxpoly with GNU General Public License v3.0 6 votes vote down vote up
public TapeFileReader(final String name, final InputStream tap) throws IOException {
  this.name = name;
  final TapFormatParser tapParser = new TapFormatParser().read(new JBBPBitInputStream(tap));
  if (tapParser.getTAPBLOCK().length == 0) {
    this.current = null;
    LOGGER.warning("Can't find blocks in TAP file");
  } else {
    this.current = new TapBlock(tapParser.getTAPBLOCK()[0]);
    this.current.index = 0;
    this.tapBlockList.add(current);
    this.current.prev = null;
    TapBlock item = this.current;
    for (int i = 1; i < tapParser.getTAPBLOCK().length; i++) {
      final TapBlock newitem = new TapBlock(tapParser.getTAPBLOCK()[i]);
      newitem.index = i;
      newitem.prev = item;
      item.next = newitem;
      item = newitem;

      this.tapBlockList.add(item);
    }
    item.next = null;
    LOGGER.log(Level.INFO, "Pointer to " + makeDescription(this.current));
  }
}
 
Example #7
Source File: JBBPParserTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFinalStreamByteCounter_SequentlyFromTheSameStream_WithEOFAtTheEnd() throws Exception {
  final JBBPBitInputStream stream = new JBBPBitInputStream(new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}));
  final JBBPParser parser = JBBPParser.prepare("byte [5];");
  assertEquals(0L, parser.getFinalStreamByteCounter());
  parser.parse(stream);
  assertEquals(5, parser.getFinalStreamByteCounter());
  parser.parse(stream);
  assertEquals(10, parser.getFinalStreamByteCounter());
  parser.parse(stream);
  assertEquals(15, parser.getFinalStreamByteCounter());
  try {
    parser.parse(stream);
    fail("Must throw EOF");
  } catch (EOFException ex) {
    assertEquals(16, parser.getFinalStreamByteCounter());
  }
}
 
Example #8
Source File: CustomThreeByteIntegerTypeTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Override
public JBBPAbstractField readCustomFieldType(final JBBPBitInputStream in, final JBBPBitOrder bitOrder, final int parserFlags, final JBBPFieldTypeParameterContainer customTypeFieldInfo, final JBBPNamedFieldInfo fieldName, final int extraData, final boolean readWholeStream, final int arrayLength) throws IOException {
  if (arrayLength < 0) {
    return new JBBPFieldInt(fieldName, readThreeBytesAsInt(in, customTypeFieldInfo.getByteOrder(), bitOrder));
  } else {
    if (readWholeStream) {
      final IntBuffer intBuffer = new IntBuffer(1024);
      while (in.hasAvailableData()) {
        intBuffer.put(readThreeBytesAsInt(in, customTypeFieldInfo.getByteOrder(), bitOrder));
      }
      return new JBBPFieldArrayInt(fieldName, intBuffer.toArray());
    } else {
      final int[] array = new int[arrayLength];
      for (int i = 0; i < arrayLength; i++) {
        array[i] = readThreeBytesAsInt(in, customTypeFieldInfo.getByteOrder(), bitOrder);
      }
      return new JBBPFieldArrayInt(fieldName, array);
    }
  }
}
 
Example #9
Source File: VarCustomTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadWrite() throws Exception {
  final VarCustomImpl impl = new VarCustomImpl();

  final byte[] etalonArray = new byte[319044];
  RND.nextBytes(etalonArray);
  etalonArray[0] = 1;

  impl.read(new JBBPBitInputStream(new ByteArrayInputStream(etalonArray)));

  assertEquals(1, impl.getBYTEA());

  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  final JBBPBitOutputStream bios = new JBBPBitOutputStream(bos);

  impl.write(bios);
  bios.close();

  assertArrayEquals(etalonArray, bos.toByteArray());
}
 
Example #10
Source File: GenAnnotationsNonStaticTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Test
void testReadWrite() throws IOException {
  final byte[] testData = new byte[] {4, (byte) 0x12, (byte) 0x34, 3, 5, 6, 7};

  final GenAnnotationsNonStatic result = new GenAnnotationsNonStatic().read(new JBBPBitInputStream(new ByteArrayInputStream(testData)));
  assertEquals(4, result.getLEN());
  assertEquals(3, result.getSOME1().getSOME2().getFIELD().length);

  final String script = "ubyte len;"
      + "some1 {"
      + " bit:4 [len] someField;"
      + " ubyte len;"
      + " some2 {"
      + "   byte [len] field;"
      + " }"
      + "}";

  final GenAnnotationsNonStatic instance = JBBPParser.prepare(script).parse(testData).mapTo(new GenAnnotationsNonStatic());
  assertEquals(result.getLEN(), instance.getLEN());
  assertEquals(result.getSOME1().getLEN(), instance.getSOME1().getLEN());
  assertArrayEquals(result.getSOME1().getSOMEFIELD(), instance.getSOME1().getSOMEFIELD());
  assertArrayEquals(result.getSOME1().getSOME2().getFIELD(), instance.getSOME1().getSOME2().getFIELD());
}
 
Example #11
Source File: SessionData.java    From zxpoly with GNU General Public License v3.0 6 votes vote down vote up
public SessionData(final JBBPBitInputStream inStream) throws IOException {
  baseAddress = inStream.readInt(JBBPByteOrder.BIG_ENDIAN);
  showGrid = inStream.readBoolean();
  showColumns = inStream.readBoolean();
  zxAddressing = inStream.readBoolean();
  invertBase = inStream.readBoolean();
  mode512x384 = inStream.readBoolean();
  columnNumber = inStream.readInt(JBBPByteOrder.BIG_ENDIAN);
  attributeMode =
      EditorComponent.AttributeMode.values()[inStream.readInt(JBBPByteOrder.BIG_ENDIAN)];
  zoom = inStream.readInt(JBBPByteOrder.BIG_ENDIAN);

  extraProperties = new Properties();

  if (inStream.hasAvailableData()) {
    final int extraDataLength = inStream.readInt(JBBPByteOrder.BIG_ENDIAN);
    final byte[] propertyData = inStream.readByteArray(extraDataLength);
    final Properties properties = new Properties();
    properties.load(new StringReader(new String(propertyData, StandardCharsets.UTF_8)));
    properties.stringPropertyNames().forEach(name -> {
      this.extraProperties.put(name, properties.getProperty(name));
    });
  }
}
 
Example #12
Source File: PackedBCDCustomFieldTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
public static long readValueFromPackedDecimal(final JBBPBitInputStream in, final int len, final boolean signed) throws IOException {
  final byte[] data = in.readByteArray(len);

  StringBuilder digitStr = new StringBuilder();
  for (int i = 0; i < len * 2; i++) {
    byte currentByte = data[i / 2];
    byte digit = (i % 2 == 0) ? (byte) ((currentByte & 0xff) >>> 4) : (byte) (currentByte & 0x0f);
    if (digit < 10) {
      digitStr.append(digit);
    }
  }

  if (signed) {
    byte sign = (byte) (data[len - 1] & 0x0f);
    if (sign == 0x0b || sign == 0x0d) {
      digitStr.insert(0, '-');
    }
  }

  return Long.parseLong(digitStr.toString());
}
 
Example #13
Source File: JBBPParser.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
/**
 * Parse am input stream with defined external value provider.
 *
 * @param in                    an input stream which content will be parsed, it must not be null
 * @param varFieldProcessor     a var field processor, it may be null if there is
 *                              not any var field in a script, otherwise NPE will be thrown during parsing
 * @param externalValueProvider an external value provider, it can be null but
 *                              only if the script doesn't have fields desired the provider
 * @return the parsed content as the root structure
 * @throws IOException it will be thrown for transport errors
 */
public JBBPFieldStruct parse(final InputStream in, final JBBPVarFieldProcessor varFieldProcessor, final JBBPExternalValueProvider externalValueProvider) throws IOException {
  final JBBPBitInputStream bitInStream = in instanceof JBBPBitInputStream ? (JBBPBitInputStream) in : new JBBPBitInputStream(in, bitOrder);
  this.finalStreamByteCounter = bitInStream.getCounter();

  final JBBPNamedNumericFieldMap fieldMap;
  if (this.compiledBlock.hasEvaluatedSizeArrays() || this.compiledBlock.hasVarFields()) {
    fieldMap = new JBBPNamedNumericFieldMap(externalValueProvider);
  } else {
    fieldMap = null;
  }

  if (this.compiledBlock.hasVarFields()) {
    JBBPUtils.assertNotNull(varFieldProcessor, "The Script contains VAR fields, a var field processor must be provided");
  }
  try {
    return new JBBPFieldStruct(new JBBPNamedFieldInfo("", "", -1), parseStruct(bitInStream, new JBBPIntCounter(), varFieldProcessor, fieldMap, new JBBPIntCounter(), new JBBPIntCounter(), false));
  } finally {
    this.finalStreamByteCounter = bitInStream.getCounter();
  }
}
 
Example #14
Source File: GenAnnotationsTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Test
void testReadWrite() throws IOException {
  final byte[] testData = new byte[] {4, (byte) 0x12, (byte) 0x34, 3, 5, 6, 7};

  final GenAnnotations result = new GenAnnotations().read(new JBBPBitInputStream(new ByteArrayInputStream(testData)));
  assertEquals(4, result.getLEN());
  assertEquals(3, result.getSOME1().getSOME2().getFIELD().length);

  final String script = "ubyte len;"
      + "some1 {"
      + " bit:4 [len] someField;"
      + " ubyte len;"
      + " some2 {"
      + "   byte [len] field;"
      + " }"
      + "}";

  final GenAnnotations instance = JBBPParser.prepare(script).parse(testData).mapTo(new GenAnnotations());
  assertEquals(result.getLEN(), instance.getLEN());
  assertEquals(result.getSOME1().getLEN(), instance.getSOME1().getLEN());
  assertArrayEquals(result.getSOME1().getSOMEFIELD(), instance.getSOME1().getSOMEFIELD());
  assertArrayEquals(result.getSOME1().getSOME2().getFIELD(), instance.getSOME1().getSOME2().getFIELD());
}
 
Example #15
Source File: PackedBCDCustomFieldTest.java    From java-binary-block-parser with Apache License 2.0 6 votes vote down vote up
@Override
public JBBPAbstractField readCustomFieldType(final JBBPBitInputStream in, final JBBPBitOrder bitOrder, final int parserFlags, final JBBPFieldTypeParameterContainer customTypeFieldInfo, JBBPNamedFieldInfo fieldName, int extraData, boolean readWholeStream, int arrayLength) throws IOException {
  final boolean signed = "sbcd".equals(customTypeFieldInfo.getTypeName());

  if (readWholeStream) {
    throw new UnsupportedOperationException("Whole stream reading unsupported");
  } else {
    if (arrayLength <= 0) {
      return new JBBPFieldLong(fieldName, readValueFromPackedDecimal(in, extraData, signed));
    } else {
      final long[] result = new long[arrayLength];
      for (int i = 0; i < arrayLength; i++) {
        result[i] = readValueFromPackedDecimal(in, extraData, signed);
      }
      return new JBBPFieldArrayLong(fieldName, result);
    }
  }
}
 
Example #16
Source File: S1Packet.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public void finalise() throws IOException {
	if (data!=null) {
		JBBPBitInputStream dataStream = new JBBPBitInputStream(new ByteArrayInputStream(data));
		if (data.length >4)
			data = dataStream.readByteArray(data.length-4);
		else data = null;
		crc = dataStream.readByteArray(4);
	}
	if (data==null) datalength=0;
	else datalength = data.length;		
}
 
Example #17
Source File: CommandFlasher.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public void getUfsInfo()  throws IOException,X10FlashException {
   	logger.info("Sending Get-ufs-info");
   		String command = "Get-ufs-info";
   		USBFlash.write(command.getBytes());
   		CommandPacket reply = USBFlash.readCommandReply(true);
   		logger.info("   Get-ufs-info status : "+reply.getResponse());

   		JBBPParser ufs_parser = JBBPParser.prepare(
   			    "byte headerlen;"
                 + "byte[headerlen-1] ufs_header;"
                 + "luns [_] { "
                 + "   byte lunlength; "
                 + "   byte reserved1; "
                 + "   byte lunid; "
                 + "   byte[12] reserved2; "
                 + "   int length; "
                 + "   byte[lunlength-19] lundata; "
                 + "}"
            );		

   		try {
   			System.out.println(HexDump.toHex(reply.getDataArray()));
   			JBBPBitInputStream stream = new JBBPBitInputStream(new ByteArrayInputStream(reply.getDataArray()));
   			ufs_infos = ufs_parser.parse(stream).mapTo(new UfsInfos());
   			ufs_infos.setSectorSize(Integer.parseInt(getPhoneProperty("Sector-size")));
   			try {
   			   stream.close();
   			} catch (Exception streamclose ) {}
   		}
   		catch (Exception e) {
   			System.out.println(e.getMessage());
   			ufs_infos=null;
   		}

}
 
Example #18
Source File: JBBPParserTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testParse_NegativeExpressonResult_OneFieldAsExpression_FlagOff() throws Exception {
  final JBBPBitInputStream stream = new JBBPBitInputStream(new ByteArrayInputStream(new byte[] {(byte) 0xEF, 1, 2, 3}));
  final JBBPParser parser = JBBPParser.prepare("byte len; byte [len] arr;");

  assertThrows(JBBPParsingException.class, () -> parser.parse(stream));
}
 
Example #19
Source File: AbstractJBBPToJavaConverterTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
protected Object callRead(final Object instance, final JBBPBitInputStream inStream) throws Exception {
  try {
    instance.getClass().getMethod("read", JBBPBitInputStream.class).invoke(instance, inStream);
    return instance;
  } catch (InvocationTargetException ex) {
    if (ex.getTargetException() != null) {
      throw (Exception) ex.getTargetException();
    } else {
      throw ex;
    }
  }
}
 
Example #20
Source File: JBBPParserTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testParse_NegativeExpressonResult_ExpressionWithNegativResult_FlagOn() throws Exception {
  final JBBPBitInputStream stream = new JBBPBitInputStream(new ByteArrayInputStream(new byte[] {4, 1, 2, 3}));
  final JBBPParser parser = JBBPParser.prepare("byte len; byte [len-8] arr;", JBBPParser.FLAG_NEGATIVE_EXPRESSION_RESULT_AS_ZERO);
  final JBBPFieldStruct result = parser.parse(stream);
  assertEquals(4, result.findFieldForType(JBBPFieldByte.class).getAsInt());
  assertEquals(0, result.findFieldForType(JBBPFieldArrayByte.class).getArray().length);
}
 
Example #21
Source File: JBBPParserTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testParse_NoErrorForIgnoreRemainingFieldsFlag() throws Exception {
  final JBBPBitInputStream stream = new JBBPBitInputStream(new ByteArrayInputStream(new byte[] {1, 2, 3, 4}));
  final JBBPParser parser = JBBPParser.prepare("int a; int b;", JBBPParser.FLAG_SKIP_REMAINING_FIELDS_IF_EOF);
  final JBBPFieldStruct result = parser.parse(stream);
  assertEquals(1, result.getArray().length);
  assertEquals("a", result.getArray()[0].getFieldName());
  assertEquals(0x01020304, ((JBBPFieldInt) result.findFieldForName("a")).getAsInt());
}
 
Example #22
Source File: JBBPToJavaConverterReadWriteTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadWrite_NamedExternalFieldInExpression() throws Exception {
  final Object klazz = compileAndMakeInstance("com.igormaznitsa.jbbp.test.ExtraFieldParser", "byte [$one*$two] data;", null, new JavaClassContent("com.igormaznitsa.jbbp.test.ExtraFieldParser", "package com.igormaznitsa.jbbp.test;\n"
      + "import com.igormaznitsa.jbbp.model.*;\n"
      + "import com.igormaznitsa.jbbp.io.*;\n"
      + "import com.igormaznitsa.jbbp.compiler.*;\n"
      + "import com.igormaznitsa.jbbp.compiler.tokenizer.*;\n"
      + "import java.io.IOException;\n"
      + "import java.util.*;\n"
      + "public class ExtraFieldParser extends " + PACKAGE_NAME + '.' + CLASS_NAME + "{"
      + "    public int getNamedValue(Object sourceStruct, String valueName){"
      + "      if (sourceStruct == null) throw new Error(\"Struct must not be null\");"
      + "      if (\"one\".equals(valueName)) return 11;"
      + "      if (\"two\".equals(valueName)) return 7;"
      + "      throw new Error(\"Unexpected value \"+valueName);"
      + "   }"
      + "}"));

  final byte[] array = new byte[77];

  testRandomGen.nextBytes(array);
  final JBBPBitInputStream in = new JBBPBitInputStream(new ByteArrayInputStream(array.clone()));

  callRead(klazz, in);
  assertFalse(in.hasAvailableData());
  assertEquals(77, getField(klazz, "data", byte[].class).length);

  assertArrayEquals(array, callWrite(klazz));
}
 
Example #23
Source File: JBBPParserTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testParse_NegativeExpressonResult_OneFieldAsExpression_FlagOn() throws Exception {
  final JBBPBitInputStream stream = new JBBPBitInputStream(new ByteArrayInputStream(new byte[] {(byte) 0xEF, 1, 2, 3}));
  final JBBPParser parser = JBBPParser.prepare("byte len; byte [len] arr;", JBBPParser.FLAG_NEGATIVE_EXPRESSION_RESULT_AS_ZERO);
  final JBBPFieldStruct result = parser.parse(stream);
  assertEquals((byte) 0xEF, result.findFieldForType(JBBPFieldByte.class).getAsInt());
  assertEquals(0, result.findFieldForType(JBBPFieldArrayByte.class).getArray().length);
}
 
Example #24
Source File: CustomThreeByteIntegerTypeTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadThreeByteInteger_OneValue() throws Exception {
  final JBBPParser parser = JBBPParser.prepare("int24 value;", new Int24CustomTypeProcessor());
  final JBBPParser inverseparser = JBBPParser.prepare("<int24 value;", new Int24CustomTypeProcessor());
  assertEquals(0x010203, parser.parse(new byte[] {0x01, 0x02, 0x03}).findFieldForType(JBBPFieldInt.class).getAsInt());
  assertEquals(0x8040C0, parser.parse(new JBBPBitInputStream(new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03}), JBBPBitOrder.MSB0)).findFieldForType(JBBPFieldInt.class).getAsInt());
  assertEquals(0x030201, inverseparser.parse(new byte[] {0x01, 0x02, 0x03}).findFieldForType(JBBPFieldInt.class).getAsInt());
  assertEquals(0xC04080, inverseparser.parse(new JBBPBitInputStream(new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03}), JBBPBitOrder.MSB0)).findFieldForType(JBBPFieldInt.class).getAsInt());
}
 
Example #25
Source File: SinParser.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public void parseHash(JBBPBitInputStream sinStream) throws IOException {
 JBBPParser hashBlocksV2 = JBBPParser.prepare(
           "block[_] {int offset;"
                   + "int length;"
                   + "byte hashLen;"
                   + "byte[hashLen] crc;}"
 );
 if (hashLen>0) {
  byte[] hashBlocks = sinStream.readByteArray(hashLen);
  blocks = hashBlocksV2.parse(hashBlocks).mapTo(new org.sinfile.parsers.v2.HashBlocks());
  certLen = sinStream.readInt(JBBPByteOrder.BIG_ENDIAN);
  cert = sinStream.readByteArray(certLen);
  if (blocks.block.length==1 && blocks.block[0].offset!=0) blocks.block[0].offset=0;
  if (blocks.block[0].length==16) {
	  partitioninfo = sinStream.readByteArray(16);
	  JBBPParser partInfo = JBBPParser.prepare(
	            "<int mot1;"
	          + "<int mot2;"
	          + "<int offset;"
	          + "<int blockcount;"
	  );
	  parti = partInfo.parse(partitioninfo).mapTo(new org.sinfile.parsers.v1.PartitionInfo());
	  if (blocks.block.length>1)
		  dataSize=parti.blockcount*blocks.block[1].length;
  }
  blocks.setSpare(this.payloadType);
 }
 dataType=getDataTypePriv();
}
 
Example #26
Source File: SinParser.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public void parseHash(JBBPBitInputStream sinStream) throws IOException {
 JBBPParser hashBlocksV2 = JBBPParser.prepare(
           "block[_] {int offset;"
                   + "int length;"
                   + "byte hashLen;"
                   + "byte[hashLen] crc;}"
 );
 if (hashLen>0) {
  byte[] hashBlocks = sinStream.readByteArray(hashLen);
  blocks = hashBlocksV2.parse(hashBlocks).mapTo(new org.sinfile.parsers.v2.HashBlocks());
  certLen = sinStream.readInt(JBBPByteOrder.BIG_ENDIAN);
  cert = sinStream.readByteArray(certLen);
  if (blocks.block.length==1 && blocks.block[0].offset!=0) blocks.block[0].offset=0; 
  if (blocks.block[0].length==16) {
	  byte[] partinfo = sinStream.readByteArray(16);
	  JBBPParser partInfo = JBBPParser.prepare(
	            "<int mot1;"
	          + "<int mot2;"
	          + "<int offset;"
	          + "<int blockcount;"
	  );
	  parti = partInfo.parse(partinfo).mapTo(new org.sinfile.parsers.v1.PartitionInfo());
  }
 }
 dataType=getDataTypePriv();
 dataSize = getDataSizePriv();
}
 
Example #27
Source File: SinParser.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public void parseHash(JBBPBitInputStream sinStream) throws IOException {

		  hashBlocks = sinStream.readByteArray(hashLen);
		  certLen = sinStream.readInt(JBBPByteOrder.BIG_ENDIAN);
		  cert = sinStream.readByteArray(certLen);
		  
		  JBBPParser hashBlocksV3 = JBBPParser.prepare(
		            "blocks[_] {int length;"
	              + "byte["+hashv3len[hashType]+"] crc;}"
	      );
		  blocks = hashBlocksV3.parse(hashBlocks).mapTo(new org.sinfile.parsers.v3.HashBlocks());

	  }
 
Example #28
Source File: TARawUnit.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public void fetchContent(JBBPBitInputStream stream) throws IOException {
	  if (magic==0x3BF8E9C1) {
		  unit = new TAUnit(unitNumber,stream.readByteArray(length));
		  if (length % 4 != 0) {
			  stream.skip(4 - length % 4);
		  }
	  }
}
 
Example #29
Source File: S1Packet.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public TAUnit getTA() {
	try {
		JBBPBitInputStream taStream = new JBBPBitInputStream(new ByteArrayInputStream(data));
		int unit=taStream.readInt(JBBPByteOrder.BIG_ENDIAN);
		int talength = taStream.readInt(JBBPByteOrder.BIG_ENDIAN);
		TAUnit u = new TAUnit(unit, taStream.readByteArray(talength));
		taStream.close();
		return u;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #30
Source File: AbstractJBBPToJavaConverterTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
protected Object callRead(final Object instance, final byte[] array) throws Exception {
  try {
    return this.callRead(instance, new JBBPBitInputStream(new ByteArrayInputStream(array)));
  } catch (InvocationTargetException ex) {
    if (ex.getCause() != null) {
      throw (Exception) ex.getCause();
    } else {
      throw ex;
    }
  }
}