Initial IntelHexParser implementation

This commit is contained in:
Jan Breuer 2012-11-26 16:13:12 +01:00
parent 9d3d4edc17
commit 5710c01e99
15 changed files with 1660 additions and 2 deletions

View File

@ -1,4 +1,26 @@
java-intelhex-parser
Java IntelHex Parser Library
====================
Java IntelHex parser library
* IntelHex file format parsing library written in Java.
* Licensed under Simplified BSD license
* Including demo code: intelhex to binary converter
// create input stream of some IntelHex data
InputStream is = new FileInputStream("Application.hex");
// create IntelHexParserObject
IntelHexParser ihp = new IntelHexParser(is);
// register parser listener
ihp.setDataListener(new IntelHexDataListener() {
@Override
public void data(long address, byte[] data) {
// process data
}
@Override
public void eof() {
// do some action
}
});
ihp.parse();

74
build.xml Normal file
View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="IntelHexParser" default="default" basedir=".">
<description>Builds, tests, and runs the project IntelHexParser.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="IntelHexParser-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

32
dist/README.TXT vendored Normal file
View File

@ -0,0 +1,32 @@
========================
BUILD OUTPUT DESCRIPTION
========================
When you build an Java application project that has a main class, the IDE
automatically copies all of the JAR
files on the projects classpath to your projects dist/lib folder. The IDE
also adds each of the JAR files to the Class-Path element in the application
JAR files manifest file (MANIFEST.MF).
To run the project from the command line, go to the dist folder and
type the following:
java -jar "IntelHexParser.jar"
To distribute this project, zip up the dist folder (including the lib folder)
and distribute the ZIP file.
Notes:
* If two JAR files on the project classpath have the same name, only the first
JAR file is copied to the lib folder.
* Only JAR files are copied to the lib folder.
If the classpath contains other types of files or folders, these files (folders)
are not copied.
* If a library on the projects classpath also has a Class-Path element
specified in the manifest,the content of the Class-Path element has to be on
the projects runtime path.
* To set a main class in a standard Java project, right-click the project node
in the Projects window and choose Properties. Then click Run and enter the
class name in the Main Class field. Alternatively, you can manually type the
class name in the manifest Main-Class element.

3
manifest.mf Normal file
View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

1053
nbproject/build-impl.xml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
build.xml.data.CRC32=5794de62
build.xml.script.CRC32=b0761d07
build.xml.stylesheet.CRC32=28e38971@1.50.3.46
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=5794de62
nbproject/build-impl.xml.script.CRC32=c450650c
nbproject/build-impl.xml.stylesheet.CRC32=fcddb364@1.50.3.46

View File

View File

@ -0,0 +1,7 @@
application.args=SIEZA_FW.X.production.hex SIEZA_FW.X.production.bin
compile.on.save=true
do.depend=false
do.jar=true
javac.debug=true
javadoc.preview=true
user.properties.file=/home/jaybee/.netbeans/7.1.2/build.properties

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
<editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/1"/>
</project-private>

View File

@ -0,0 +1,73 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=IntelHexParser
application.vendor=jaybee
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/IntelHexParser.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
includes=**
jar.compress=false
javac.classpath=
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=cz.jaybee.intelhex.IntelHexParserDemo
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value
# or test-sys-prop.name=value to set system properties for unit tests):
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=UTF-8
src.dir=src
test.src.dir=test

15
nbproject/project.xml Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>IntelHexParser</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
</configuration>
</project>

View File

@ -0,0 +1,40 @@
/**
* @license
* Copyright (c) 2012, Jan Breuer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package cz.jaybee.intelhex;
/**
*
* @author Jan Breuer
* @license BSD 2-Clause
*/
public interface IntelHexDataListener {
public void data(long address, byte[] data);
public void eof();
}

View File

@ -0,0 +1,168 @@
/**
* @license
* Copyright (c) 2012, Jan Breuer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package cz.jaybee.intelhex;
import java.io.*;
/**
*
* @author Jan Breuer
* @license BSD 2-Clause
*/
public class IntelHexParser {
private BufferedReader reader = null;
private IntelHexDataListener dataListener = null;
private static final int HEX = 16;
private boolean eof = false;
private int recordIdx = 0;
private long upperAddress = 0;
private class Record {
int length;
int address;
IntelHexRecordType type;
byte[] data;
}
public IntelHexParser(Reader reader) {
if (reader instanceof BufferedReader) {
this.reader = (BufferedReader) reader;
} else {
this.reader = new BufferedReader(reader);
}
}
public IntelHexParser(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public void setDataListener(IntelHexDataListener listener) {
this.dataListener = listener;
}
private Record parseRecord(String record) throws Exception {
Record result = new Record();
// check, if there wasn an accidential EOF record
if (eof) {
throw new Exception("Data after eof (" + recordIdx + ")");
}
// every IntelHEX record must start with ":"
if (!record.startsWith(":")) {
throw new Exception("Invalid Intel HEX record (" + recordIdx + ")");
}
int lineLength = record.length();
byte[] hexRecord = new byte[lineLength / 2];
// sum of all bytes modulo 256 (including checksum) shuld be 0
int sum = 0;
for (int i = 0; i < hexRecord.length; i++) {
String num = record.substring(2 * i + 1, 2 * i + 3);
hexRecord[i] = (byte) Integer.parseInt(num, HEX);
sum += hexRecord[i] & 0xff;
}
sum &= 0xff;
if (sum != 0) {
throw new Exception("Invalid checksum (" + recordIdx + ")");
}
// if the length field does not correspond with line length
result.length = hexRecord[0];
if ((result.length + 5) != hexRecord.length) {
throw new Exception("Invalid record length (" + recordIdx + ")");
}
// length is OK, copy data
result.data = new byte[result.length];
System.arraycopy(hexRecord, 4, result.data, 0, result.length);
// build lower part of data address
result.address = ((hexRecord[1] & 0xFF) << 8) + (hexRecord[2] & 0xFF);
// determine record type
result.type = IntelHexRecordType.fromInt(hexRecord[3] & 0xFF);
if (result.type == IntelHexRecordType.UNKNOWN) {
throw new Exception("Unsupported record type " + (hexRecord[3] & 0xFF) + " (" + recordIdx + ")");
}
return result;
}
private void processRecord(Record record) throws Exception {
// build full address
long addr = record.address | upperAddress;
switch (record.type) {
case DATA:
if (dataListener != null) {
dataListener.data(addr, record.data);
}
break;
case EOF:
if (dataListener != null) {
dataListener.eof();
}
eof = true;
break;
case EXT_LIN:
if (record.length == 2) {
upperAddress = ((record.data[0] & 0xFF) << 8) + (record.data[1] & 0xFF);
upperAddress <<= 16;
} else {
throw new Exception("Invalid EXT_LIN record (" + recordIdx + ")");
}
break;
case EXT_SEG:
case START_SEG:
case START_LIN:
throw new Exception(record.type + " record not implemented (" + recordIdx + ")");
case UNKNOWN:
break;
}
}
public void parse() throws IOException, Exception {
recordIdx = 1;
upperAddress = 0;
String recordStr;
while ((recordStr = reader.readLine()) != null) {
Record record = parseRecord(recordStr);
processRecord(record);
recordIdx++;
}
if (!eof) {
throw new Exception("No eof at the end of file");
}
}
}

View File

@ -0,0 +1,97 @@
/**
* @license
* Copyright (c) 2012, Jan Breuer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package cz.jaybee.intelhex;
import java.io.*;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Jan Breuer
* @license BSD 2-Clause
*/
public class IntelHexParserDemo implements IntelHexDataListener {
private long addressStart;
private long addressStop;
private byte[] buffer;
private OutputStream destination;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
InputStream is = new FileInputStream("Application.hex");
OutputStream os = new FileOutputStream("Application.bin");
IntelHexParser ihp = new IntelHexParser(is);
IntelHexParserDemo ihpd = new IntelHexParserDemo(0x1D000000, 0x1D07FFEF, os);
ihp.setDataListener(ihpd);
ihp.parse();
is.close();
}
private IntelHexParserDemo(long addressStart, long addressStop, OutputStream destination) {
this.addressStart = addressStart;
this.addressStop = addressStop;
this.destination = destination;
this.buffer = new byte[(int) (addressStop - addressStart + 1)];
Arrays.fill(buffer, (byte) 0xFF);
}
@Override
public void data(long address, byte[] data) {
if ((address >= addressStart) && (address <= addressStop)) {
int length = data.length;
if ((address + length) > addressStop) {
length = (int) (addressStop - address + 1);
}
System.arraycopy(data, 0, buffer, (int) (address - addressStart), length);
}
}
@Override
public void eof() {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(destination);
dos.write(buffer);
} catch (Exception ex) {
Logger.getLogger(IntelHexParserDemo.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dos.close();
} catch (IOException ex) {
Logger.getLogger(IntelHexParserDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}

View File

@ -0,0 +1,62 @@
/**
* @license
* Copyright (c) 2012, Jan Breuer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package cz.jaybee.intelhex;
/**
*
* @author Jan Breuer
* @license BSD 2-Clause
*/
public enum IntelHexRecordType {
DATA(0x00),
EOF(0x01),
EXT_SEG(0x02),
START_SEG(0x03),
EXT_LIN(0x04),
START_LIN(0x05),
UNKNOWN(0xFF);
int id;
IntelHexRecordType(int id) {
this.id = id;
}
public int toInt() {
return id;
}
public static IntelHexRecordType fromInt(int id) {
for (IntelHexRecordType d : IntelHexRecordType.values()) {
if (d.id == id) {
return d;
}
}
return IntelHexRecordType.UNKNOWN;
}
}