Add RangeDetector and update demo

- cleanup netbeans project (delete private files)
 - make Region public
 - move IntelHexParseRangeDetector.java to RangeDetector.java
 - move computions from RangeDetector to MemoryRegions
 - introduce IntelHexException
 - refactor IntelHexParserDemo and extract BinWriter
 - add RangeDetector support to IntelHexParserDemo
This commit is contained in:
Jan Breuer 2015-03-01 11:14:53 +01:00
parent afe484a29e
commit f894afc315
18 changed files with 648 additions and 339 deletions

3
.gitignore vendored
View File

@ -4,4 +4,5 @@
*.jar
*.war
*.ear
/build/
/build/
/nbproject/private/

View File

@ -51,8 +51,7 @@
-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)
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation

View File

@ -54,6 +54,7 @@ is divided into following sections:
<property file="nbproject/project.properties"/>
</target>
<target depends="-pre-init,-init-private,-init-user,-init-project,-init-macrodef-property" name="-do-init">
<property name="platform.java" value="${java.home}/bin/java"/>
<available file="${manifest.file}" property="manifest.available"/>
<condition property="splashscreen.available">
<and>
@ -71,16 +72,20 @@ is divided into following sections:
</not>
</and>
</condition>
<condition property="manifest.available+main.class">
<condition property="profile.available">
<and>
<isset property="manifest.available"/>
<isset property="main.class.available"/>
<isset property="javac.profile"/>
<length length="0" string="${javac.profile}" when="greater"/>
<matches pattern="1\.[89](\..*)?" string="${javac.source}"/>
</and>
</condition>
<condition property="do.archive">
<not>
<istrue value="${jar.archive.disabled}"/>
</not>
<or>
<not>
<istrue value="${jar.archive.disabled}"/>
</not>
<istrue value="${not.archive.disabled}"/>
</or>
</condition>
<condition property="do.mkdist">
<and>
@ -91,12 +96,6 @@ is divided into following sections:
</not>
</and>
</condition>
<condition property="manifest.available+main.class+mkdist.available">
<and>
<istrue value="${manifest.available+main.class}"/>
<isset property="do.mkdist"/>
</and>
</condition>
<condition property="do.archive+manifest.available">
<and>
<isset property="manifest.available"/>
@ -115,24 +114,12 @@ is divided into following sections:
<istrue value="${do.archive}"/>
</and>
</condition>
<condition property="do.archive+manifest.available+main.class">
<condition property="do.archive+profile.available">
<and>
<istrue value="${manifest.available+main.class}"/>
<isset property="profile.available"/>
<istrue value="${do.archive}"/>
</and>
</condition>
<condition property="manifest.available-mkdist.available">
<or>
<istrue value="${manifest.available}"/>
<isset property="do.mkdist"/>
</or>
</condition>
<condition property="manifest.available+main.class-mkdist.available">
<or>
<istrue value="${manifest.available+main.class}"/>
<isset property="do.mkdist"/>
</or>
</condition>
<condition property="have.tests">
<or>
<available file="${test.src.dir}"/>
@ -186,7 +173,15 @@ is divided into following sections:
</condition>
<path id="endorsed.classpath.path" path="${endorsed.classpath}"/>
<condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'">
<length length="0" string="${endorsed.classpath}" when="greater"/>
<and>
<isset property="endorsed.classpath"/>
<not>
<equals arg1="${endorsed.classpath}" arg2="" trim="true"/>
</not>
</and>
</condition>
<condition else="" property="javac.profile.cmd.line.arg" value="-profile ${javac.profile}">
<isset property="profile.available"/>
</condition>
<condition else="false" property="jdkBug6558476">
<and>
@ -275,6 +270,7 @@ is divided into following sections:
<path path="@{classpath}"/>
</classpath>
<compilerarg line="${endorsed.classpath.cmd.line.arg}"/>
<compilerarg line="${javac.profile.cmd.line.arg}"/>
<compilerarg line="${javac.compilerargs}"/>
<compilerarg value="-processorpath"/>
<compilerarg path="@{processorpath}:${empty.dir}"/>
@ -314,6 +310,7 @@ is divided into following sections:
<path path="@{classpath}"/>
</classpath>
<compilerarg line="${endorsed.classpath.cmd.line.arg}"/>
<compilerarg line="${javac.profile.cmd.line.arg}"/>
<compilerarg line="${javac.compilerargs}"/>
<customize/>
</javac>
@ -446,7 +443,7 @@ is divided into following sections:
</fileset>
</union>
<taskdef classname="org.testng.TestNGAntTask" classpath="${run.test.classpath}" name="testng"/>
<testng classfilesetref="test.set" failureProperty="tests.failed" methods="${testng.methods.arg}" mode="${testng.mode}" outputdir="${build.test.results.dir}" suitename="IntelHexParser" testname="TestNG tests" workingDir="${work.dir}">
<testng classfilesetref="test.set" failureProperty="tests.failed" listeners="org.testng.reporters.VerboseReporter" methods="${testng.methods.arg}" mode="${testng.mode}" outputdir="${build.test.results.dir}" suitename="IntelHexParser" testname="TestNG tests" workingDir="${work.dir}">
<xmlfileset dir="${build.test.classes.dir}" includes="@{testincludes}"/>
<propertyset>
<propertyref prefix="test-sys-prop."/>
@ -837,8 +834,8 @@ is divided into following sections:
</chainedmapper>
</pathconvert>
<taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/>
<copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}">
<fileset dir="${build.classes.dir}"/>
<copylibs compress="${jar.compress}" excludeFromCopy="${copylibs.excludes}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}">
<fileset dir="${build.classes.dir}" excludes="${dist.archive.excludes}"/>
<manifest>
<attribute name="Class-Path" value="${jar.classpath}"/>
<customize/>
@ -850,7 +847,7 @@ is divided into following sections:
<target name="-init-presetdef-jar">
<presetdef name="jar" uri="http://www.netbeans.org/ns/j2se-project/1">
<jar compress="${jar.compress}" index="${jar.index}" jarfile="${dist.jar}">
<j2seproject1:fileset dir="${build.classes.dir}"/>
<j2seproject1:fileset dir="${build.classes.dir}" excludes="${dist.archive.excludes}"/>
</jar>
</presetdef>
</target>
@ -966,41 +963,25 @@ is divided into following sections:
<!-- Empty placeholder for easier customization. -->
<!-- You can override this target in the ../build.xml file. -->
</target>
<target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive" name="-do-jar-without-manifest" unless="manifest.available-mkdist.available">
<j2seproject1:jar/>
</target>
<target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive+manifest.available" name="-do-jar-with-manifest" unless="manifest.available+main.class-mkdist.available">
<j2seproject1:jar manifest="${manifest.file}"/>
</target>
<target depends="init,compile,-pre-pre-jar,-pre-jar" if="do.archive+manifest.available+main.class" name="-do-jar-with-mainclass" unless="manifest.available+main.class+mkdist.available">
<j2seproject1:jar manifest="${manifest.file}">
<j2seproject1:manifest>
<j2seproject1:attribute name="Main-Class" value="${main.class}"/>
</j2seproject1:manifest>
</j2seproject1:jar>
<echo level="info">To run this application from the command line without Ant, try:</echo>
<property location="${build.classes.dir}" name="build.classes.dir.resolved"/>
<property location="${dist.jar}" name="dist.jar.resolved"/>
<pathconvert property="run.classpath.with.dist.jar">
<path path="${run.classpath}"/>
<map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/>
</pathconvert>
<echo level="info">java -cp "${run.classpath.with.dist.jar}" ${main.class}</echo>
</target>
<target depends="init" if="do.archive" name="-do-jar-with-libraries-create-manifest" unless="manifest.available">
<target depends="init" if="do.archive" name="-do-jar-create-manifest" unless="manifest.available">
<tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/>
<touch file="${tmp.manifest.file}" verbose="false"/>
</target>
<target depends="init" if="do.archive+manifest.available" name="-do-jar-with-libraries-copy-manifest">
<target depends="init" if="do.archive+manifest.available" name="-do-jar-copy-manifest">
<tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/>
<copy file="${manifest.file}" tofile="${tmp.manifest.file}"/>
</target>
<target depends="init,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest" if="do.archive+main.class.available" name="-do-jar-with-libraries-set-main">
<target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+main.class.available" name="-do-jar-set-mainclass">
<manifest file="${tmp.manifest.file}" mode="update">
<attribute name="Main-Class" value="${main.class}"/>
</manifest>
</target>
<target depends="init,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest" if="do.archive+splashscreen.available" name="-do-jar-with-libraries-set-splashscreen">
<target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+profile.available" name="-do-jar-set-profile">
<manifest file="${tmp.manifest.file}" mode="update">
<attribute name="Profile" value="${javac.profile}"/>
</manifest>
</target>
<target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+splashscreen.available" name="-do-jar-set-splashscreen">
<basename file="${application.splash}" property="splashscreen.basename"/>
<mkdir dir="${build.classes.dir}/META-INF"/>
<copy failonerror="false" file="${application.splash}" todir="${build.classes.dir}/META-INF"/>
@ -1008,23 +989,41 @@ is divided into following sections:
<attribute name="SplashScreen-Image" value="META-INF/${splashscreen.basename}"/>
</manifest>
</target>
<target depends="init,-init-macrodef-copylibs,compile,-pre-pre-jar,-pre-jar,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest,-do-jar-with-libraries-set-main,-do-jar-with-libraries-set-splashscreen" if="do.mkdist" name="-do-jar-with-libraries-pack">
<target depends="init,-init-macrodef-copylibs,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen" if="do.mkdist" name="-do-jar-copylibs">
<j2seproject3:copylibs manifest="${tmp.manifest.file}"/>
<echo level="info">To run this application from the command line without Ant, try:</echo>
<property location="${dist.jar}" name="dist.jar.resolved"/>
<echo level="info">java -jar "${dist.jar.resolved}"</echo>
</target>
<target depends="-do-jar-with-libraries-pack" if="do.archive" name="-do-jar-with-libraries-delete-manifest">
<target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen" if="do.archive" name="-do-jar-jar" unless="do.mkdist">
<j2seproject1:jar manifest="${tmp.manifest.file}"/>
<property location="${build.classes.dir}" name="build.classes.dir.resolved"/>
<property location="${dist.jar}" name="dist.jar.resolved"/>
<pathconvert property="run.classpath.with.dist.jar">
<path path="${run.classpath}"/>
<map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/>
</pathconvert>
<condition else="" property="jar.usage.message" value="To run this application from the command line without Ant, try:${line.separator}${platform.java} -cp ${run.classpath.with.dist.jar} ${main.class}">
<isset property="main.class.available"/>
</condition>
<condition else="debug" property="jar.usage.level" value="info">
<isset property="main.class.available"/>
</condition>
<echo level="${jar.usage.level}" message="${jar.usage.message}"/>
</target>
<target depends="-do-jar-copylibs" if="do.archive" name="-do-jar-delete-manifest">
<delete>
<fileset file="${tmp.manifest.file}"/>
</delete>
</target>
<target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-with-libraries-create-manifest,-do-jar-with-libraries-copy-manifest,-do-jar-with-libraries-set-main,-do-jar-with-libraries-set-splashscreen,-do-jar-with-libraries-pack,-do-jar-with-libraries-delete-manifest" name="-do-jar-with-libraries"/>
<target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen,-do-jar-jar,-do-jar-delete-manifest" name="-do-jar-without-libraries"/>
<target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen,-do-jar-copylibs,-do-jar-delete-manifest" name="-do-jar-with-libraries"/>
<target name="-post-jar">
<!-- Empty placeholder for easier customization. -->
<!-- You can override this target in the ../build.xml file. -->
</target>
<target depends="init,compile,-pre-jar,-do-jar-with-manifest,-do-jar-without-manifest,-do-jar-with-mainclass,-do-jar-with-libraries,-post-jar" description="Build JAR." name="jar"/>
<target depends="init,compile,-pre-jar,-do-jar-without-libraries,-do-jar-with-libraries,-post-jar" name="-do-jar"/>
<target depends="init,compile,-pre-jar,-do-jar,-post-jar" description="Build JAR." name="jar"/>
<!--
=================
EXECUTION SECTION
@ -1203,11 +1202,14 @@ is divided into following sections:
</not>
</and>
</condition>
<javadoc additionalparam="${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}">
<condition else="" property="bug5101868workaround" value="*.java">
<matches pattern="1\.[56](\..*)?" string="${java.version}"/>
</condition>
<javadoc additionalparam="-J-Dfile.encoding=${file.encoding} ${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}">
<classpath>
<path path="${javac.classpath}"/>
</classpath>
<fileset dir="${src.dir}" excludes="*.java,${excludes}" includes="${includes}">
<fileset dir="${src.dir}" excludes="${bug5101868workaround},${excludes}" includes="${includes}">
<filename name="**/*.java"/>
</fileset>
<fileset dir="${build.generated.sources.dir}" erroronmissingdir="false">
@ -1281,7 +1283,7 @@ is divided into following sections:
<mkdir dir="${build.test.results.dir}"/>
</target>
<target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run">
<j2seproject3:test testincludes="**/*Test.java"/>
<j2seproject3:test includes="${includes}" testincludes="**/*Test.java"/>
</target>
<target depends="init,compile-test,-pre-test-run,-do-test-run" if="have.tests" name="-post-test-run">
<fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail>

View File

@ -1,8 +1,8 @@
build.xml.data.CRC32=5794de62
build.xml.script.CRC32=b0761d07
build.xml.stylesheet.CRC32=28e38971@1.50.3.46
build.xml.script.CRC32=cdd13f0f
build.xml.stylesheet.CRC32=8064a381@1.75.2.48
# 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=fb65a51e
nbproject/build-impl.xml.stylesheet.CRC32=c6d2a60f@1.56.1.46
nbproject/build-impl.xml.script.CRC32=95078a0f
nbproject/build-impl.xml.stylesheet.CRC32=876e7a8f@1.75.2.48

View File

@ -1,6 +0,0 @@
compile.on.save=true
do.depend=false
do.jar=true
javac.debug=true
javadoc.preview=true
user.properties.file=/home/jaybee/.netbeans/7.3/build.properties

View File

@ -1,5 +0,0 @@
<?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"/>
<editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
</project-private>

View File

@ -35,8 +35,8 @@ javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.source=1.7
javac.target=1.7
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}

View File

@ -0,0 +1,80 @@
/**
* @license Copyright (c) 2015, 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.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Binary file writer
*
* @author Jan Breuer
* @license BSD 2-Clause
*/
public class BinWriter implements IntelHexDataListener {
private final Region outputRegion;
private final OutputStream destination;
private final byte[] buffer;
private final MemoryRegions regions;
public BinWriter(Region outputRegion, OutputStream destination) {
this.outputRegion = outputRegion;
this.destination = destination;
this.buffer = new byte[(int) (outputRegion.getLength())];
Arrays.fill(buffer, (byte) 0xFF);
regions = new MemoryRegions();
}
@Override
public void data(long address, byte[] data) {
regions.add(address, data.length);
if ((address >= outputRegion.getAddressStart()) && (address <= outputRegion.getAddressEnd())) {
int length = data.length;
if ((address + length) > outputRegion.getAddressEnd()) {
length = (int) (outputRegion.getAddressEnd() - address + 1);
}
System.arraycopy(data, 0, buffer, (int) (address - outputRegion.getAddressStart()), length);
}
}
@Override
public void eof() {
try {
destination.write(buffer);
} catch (IOException ex) {
Logger.getLogger(BinWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}
public MemoryRegions getMemoryRegions() {
return regions;
}
}

View File

@ -1,40 +1,51 @@
/**
* @license
* Copyright (c) 2012, Jan Breuer
* All rights reserved.
*
* @license Copyright (c) 2015, 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 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
* 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
* 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;
/**
* Listener interface to parser events
*
* @author Jan Breuer
* @license BSD 2-Clause
*/
public interface IntelHexDataListener {
/**
* Every time new data are read from file, this listener method is called
* with appropriate values. Multiple calls of this function may be done
* inside one memory regions but they will not overlap (if they don't
* overlap in original intelhex).
*
* @param address
* @param data
*/
public void data(long address, byte[] data);
/**
* After eof is detected in the file, this listener method is called
*/
public void eof();
}

View File

@ -0,0 +1,42 @@
/**
* @license Copyright (c) 2015, 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;
/**
* Custom exception to prevent using general Exception
*
* @author Jan Breuer
* @license BSD 2-Clause
*/
public class IntelHexException extends Exception {
public IntelHexException() {
}
public IntelHexException(String message) {
super(message);
}
}

View File

@ -1,31 +0,0 @@
package cz.jaybee.intelhex;
public class IntelHexParseRangeDetector implements IntelHexDataListener {
private final MemoryRegions regions = new MemoryRegions();
@Override
public void data(long address, byte[] data) {
regions.add(address, data.length);
}
@Override
public void eof() {
regions.compact();
}
public void reset() {
regions.regions.clear();
}
public long getStart() {
if (regions.regions.size() == 0) return 0;
MemoryRegions.Region first = regions.regions.get(0);
return first.getStart();
}
public long getLength() {
if (regions.regions.size() == 0) return 0;
MemoryRegions.Region last = regions.regions.get(regions.regions.size() - 1);
return last.getStart() + last.getLength() - getStart();
}
}

View File

@ -1,28 +1,26 @@
/**
* @license
* Copyright (c) 2012, Jan Breuer
* All rights reserved.
*
* @license Copyright (c) 2015, 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 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
* 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
* 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;
@ -30,8 +28,11 @@ package cz.jaybee.intelhex;
import java.io.*;
/**
* Main Intel HEX parser class
*
* @author Jan Breuer
* @author Kristian Sloth Lauszus
* @author riilabs
* @license BSD 2-Clause
*/
public class IntelHexParser {
@ -44,53 +45,83 @@ public class IntelHexParser {
private long upperAddress = 0;
private long startAddress = 0;
/**
* Class to hold one Intel HEX record - one line in the file
*/
private class Record {
int length;
int address;
IntelHexRecordType type;
byte[] data;
/**
* Convert the record to pretty string
*
* @return
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(type);
sb.append(" @");
sb.append(String.format("0x%04X", address));
sb.append(" [");
for(byte c: data) {
for (byte c : data) {
sb.append(String.format("0x%02X", c));
sb.append(" ");
}
sb.setLength(sb.length() - 1);
sb.setLength(sb.length() - 1);
sb.append("]");
return sb.toString();
}
}
/**
* Constructor of the parser with reader
*
* @param reader
*/
public IntelHexParser(Reader reader) {
this.reader = (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader);
this.reader = (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader);
}
/**
* Constructor of the parser with input stream
*
* @param stream
*/
public IntelHexParser(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
/**
* Set data listener to parsing events (data and eof)
*
* @param listener
*/
public void setDataListener(IntelHexDataListener listener) {
this.dataListener = listener;
}
private Record parseRecord(String record) throws Exception {
/**
* Parse one line of Intel HEX file
*
* @param record
* @return
* @throws IntelHexException
*/
private Record parseRecord(String record) throws IntelHexException {
Record result = new Record();
// check, if there wasn an accidential EOF record
if (eof) {
throw new Exception("Data after eof (" + recordIdx + ")");
throw new IntelHexException("Data after eof (" + recordIdx + ")");
}
// every IntelHEX record must start with ":"
if (!record.startsWith(":")) {
throw new Exception("Invalid Intel HEX record (" + recordIdx + ")");
throw new IntelHexException("Invalid Intel HEX record (" + recordIdx + ")");
}
int lineLength = record.length();
@ -106,13 +137,13 @@ public class IntelHexParser {
sum &= 0xff;
if (sum != 0) {
throw new Exception("Invalid checksum (" + recordIdx + ")");
throw new IntelHexException("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 + ")");
throw new IntelHexException("Invalid record length (" + recordIdx + ")");
}
// length is OK, copy data
result.data = new byte[result.length];
@ -124,13 +155,19 @@ public class IntelHexParser {
// 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 + ")");
throw new IntelHexException("Unsupported record type " + (hexRecord[3] & 0xFF) + " (" + recordIdx + ")");
}
return result;
}
private void processRecord(Record record) throws Exception {
/**
* Process parsed record, copute correct address, emit events
*
* @param record
* @throws IntelHexException
*/
private void processRecord(Record record) throws IntelHexException {
// build full address
long addr = record.address | upperAddress;
switch (record.type) {
@ -150,7 +187,7 @@ public class IntelHexParser {
upperAddress = ((record.data[0] & 0xFF) << 8) + (record.data[1] & 0xFF);
upperAddress <<= 16; // ELA is bits 16-31 of the segment base address (SBA), so shift left 16 bits
} else {
throw new Exception("Invalid EXT_LIN record (" + recordIdx + ")");
throw new IntelHexException("Invalid EXT_LIN record (" + recordIdx + ")");
}
break;
@ -159,29 +196,29 @@ public class IntelHexParser {
upperAddress = ((record.data[0] & 0xFF) << 8) + (record.data[1] & 0xFF);
upperAddress <<= 4; // ESA is bits 4-19 of the segment base address (SBA), so shift left 4 bits
} else {
throw new Exception("Invalid EXT_SEG record (" + recordIdx + ")");
throw new IntelHexException("Invalid EXT_SEG record (" + recordIdx + ")");
}
break;
case START_LIN:
if (record.length == 4) {
startAddress = 0;
for (byte c: record.data) {
for (byte c : record.data) {
startAddress = startAddress << 8;
startAddress |= (c & 0xFF);
}
} else {
throw new Exception("Invalid START_LIN record at line #" + recordIdx + " " + record);
throw new IntelHexException("Invalid START_LIN record at line #" + recordIdx + " " + record);
}
break;
case START_SEG:
if (record.length == 4) {
startAddress = 0;
for (byte c: record.data) {
for (byte c : record.data) {
startAddress = startAddress << 8;
startAddress |= (c & 0xFF);
}
}
} else {
throw new Exception("Invalid START_SEG record at line #" + recordIdx + " " + record);
throw new IntelHexException("Invalid START_SEG record at line #" + recordIdx + " " + record);
}
case UNKNOWN:
break;
@ -189,15 +226,27 @@ public class IntelHexParser {
}
/**
* Return program start address/reset address. May not be at the beggining
* of the data.
*
* @return
*/
public long getStartAddress() {
return startAddress;
}
public void parse() throws Exception {
eof = false;
/**
* Main public method to start parsing of the input
*
* @throws IntelHexException
* @throws IOException
*/
public void parse() throws IntelHexException, IOException {
eof = false;
recordIdx = 1;
upperAddress = 0;
startAddress = 0;
startAddress = 0;
String recordStr;
while ((recordStr = reader.readLine()) != null) {
@ -205,9 +254,9 @@ public class IntelHexParser {
processRecord(record);
recordIdx++;
}
if (!eof) {
throw new Exception("No eof at the end of file");
throw new IntelHexException("No eof at the end of file");
}
}
}

View File

@ -1,130 +1,125 @@
/**
* @license
* Copyright (c) 2012, Jan Breuer
* All rights reserved.
*
* @license Copyright (c) 2015, 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 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
* 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
* 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.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class to demonstrate usage of Intel HEX parser
*
* @author Jan Breuer
* @license BSD 2-Clause
* @license BSD 2-Clause
*/
public class IntelHexParserDemo implements IntelHexDataListener {
private long addressStart;
private long addressStop;
private byte[] buffer;
private OutputStream destination;
private MemoryRegions regions;
public class IntelHexParserDemo {
/**
* Convert Intel HEX to bin
*
* usage:
*
* IntelHexParserDemo {source} {target}
*
* IntelHexParserDemo {source} {target} {address_from} {address_to}
*
* {source} is source Intel HEX file name
*
* {target} is target BIN file name
*
* {address_from} is start address e.g. 0x1D000000 or min
*
* {address_to} is end address e.g. 0x1D07FFFF or max
*
* if no address_from and address_to is specified, maximum range is used
*
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
public static void main(String[] args) {
String fileIn = "Application.hex";
String fileOut = "Application.bin";
String dataFrom = "0x1D000000";
String dataTo = "0x1D07FFEF";
String dataFrom = "min";
String dataTo = "max";
if (args.length >= 1) {
fileIn = args[0];
}
}
if (args.length >= 2) {
fileOut = args[1];
}
if (args.length >= 3) {
dataFrom = args[2];
}
if (args.length >= 4) {
dataTo = args[3];
}
Long dataFromInt = Long.parseLong(dataFrom.substring(2), 16);
Long dataToInt = Long.parseLong(dataTo.substring(2), 16);
InputStream is = new FileInputStream(fileIn);
OutputStream os = new FileOutputStream(fileOut);
IntelHexParser ihp = new IntelHexParser(is);
IntelHexParserDemo ihpd = new IntelHexParserDemo(dataFromInt, dataToInt, os);
ihp.setDataListener(ihpd);
ihp.parse();
is.close();
System.out.printf("Program start address 0x%08X\r\n", ihp.getStartAddress());
System.out.println("Memory regions: ");
System.out.println(ihpd.regions);
}
public 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);
regions = new MemoryRegions();
}
try (FileInputStream is = new FileInputStream(fileIn)) {
OutputStream os = new FileOutputStream(fileOut);
// init parser
IntelHexParser parser = new IntelHexParser(is);
@Override
public void data(long address, byte[] data) {
regions.add(address, data.length);
if ((address >= addressStart) && (address <= addressStop)) {
int length = data.length;
if ((address + length) > addressStop) {
length = (int) (addressStop - address + 1);
// 1st iteration - calculate maximum output range
RangeDetector rangeDetector = new RangeDetector();
parser.setDataListener(rangeDetector);
parser.parse();
is.getChannel().position(0);
Region outputRegion = rangeDetector.getFullRangeRegion();
// if address parameter is "max", calculate maximum memory region
if (!("min".equals(dataFrom))) {
outputRegion.setAddressStart(Long.parseLong(dataFrom.substring(2), 16));
}
if (!("max".equals(dataTo))) {
outputRegion.setAddressEnd(Long.parseLong(dataTo.substring(2), 16));
}
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) {
// 2nd iteration - actual write of the output
BinWriter writer = new BinWriter(outputRegion, os);
parser.setDataListener(writer);
parser.parse();
// print statistics
System.out.printf("Program start address 0x%08X\r\n", parser.getStartAddress());
System.out.println("Memory regions: ");
System.out.println(writer.getMemoryRegions());
System.out.print("Written output: ");
System.out.println(outputRegion);
} catch (IntelHexException | IOException 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

@ -1,33 +1,32 @@
/**
* @license
* Copyright (c) 2012, Jan Breuer
* All rights reserved.
*
* @license Copyright (c) 2015, 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 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
* 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
* 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;
/**
* Type of one record in Intel HEX file (type of line)
*
* @author Jan Breuer
* @license BSD 2-Clause
@ -47,10 +46,21 @@ public enum IntelHexRecordType {
this.id = id;
}
/**
* Convert enum value to integer
*
* @return
*/
public int toInt() {
return id;
}
/**
* Convert integer value to enum value
*
* @param id
* @return
*/
public static IntelHexRecordType fromInt(int id) {
for (IntelHexRecordType d : IntelHexRecordType.values()) {
if (d.id == id) {

View File

@ -1,5 +1,5 @@
/**
* @license Copyright (c) 2014, Jan Breuer All rights reserved.
* @license Copyright (c) 2015, 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:
@ -31,83 +31,74 @@ import java.util.Iterator;
import java.util.List;
/**
*
* Class to hold all memory address regions
*
* @author Jan Breuer
* @author riilabs
* @license BSD 2-Clause
*/
public class MemoryRegions {
public final List<Region> regions = new ArrayList<>();
public static class Region implements Comparable<Region>{
private long start;
private long length;
public Region(long start, long length) {
this.start = start;
this.length = length;
}
public long getStart() {
return start;
}
public long getLength() {
return length;
}
void incLength(long value) {
length += value;
}
@Override
public String toString() {
return String.format("0x%08x:0x%08x (%dB 0x%08X)", start, start + length - 1, length, length);
}
@Override
public int compareTo(Region o) {
if(this.start == o.start) {
return Long.compare(this.length, o.length);
} else {
return Long.compare(this.start, o.start);
}
}
}
private final List<Region> regions = new ArrayList<>();
public void add(long start, long length) {
Region prevRegion;
if (regions.size() > 0) {
prevRegion = regions.get(regions.size() - 1);
long nextAddress = prevRegion.start + prevRegion.length;
long nextAddress = prevRegion.getAddressStart() + prevRegion.getLength();
if (nextAddress == start) {
prevRegion.incLength(length);
prevRegion.incLength(length);
return;
}
}
}
regions.add(new Region(start, length));
}
public void compact() {
Collections.sort(regions);
Iterator<Region> iter = regions.iterator();
Region prev = null;
while(iter.hasNext()) {
Region prev = null;
while (iter.hasNext()) {
Region curr = iter.next();
if (prev == null) prev = curr;
else {
// check for chaining
if (curr.getStart() == (prev.getStart() + prev.getLength())) {
prev.incLength(curr.getLength());
iter.remove();
}
else prev = curr;
}
if (prev == null) {
prev = curr;
} else {
// check for chaining
if (curr.getAddressStart() == (prev.getAddressStart() + prev.getLength())) {
prev.incLength(curr.getLength());
iter.remove();
} else {
prev = curr;
}
}
}
}
public void clear() {
regions.clear();
}
public int size() {
return regions.size();
}
public Region get(int index) {
return regions.get(index);
}
public Region getFullRangeRegion() {
long start = 0;
long length = 0;
if (!regions.isEmpty()) {
start = regions.get(0).getAddressStart();
Region last = regions.get(regions.size() - 1);
length = last.getAddressStart() + last.getLength() - start;
}
return new Region(start, length);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();

View File

@ -0,0 +1,60 @@
/**
* @license Copyright (c) 2015, 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;
/**
* First pass listener to calculate data address range for further use
*
* @author riilabs
* @author Jan Breuer
* @license BSD 2-Clause
*/
public class RangeDetector implements IntelHexDataListener {
private final MemoryRegions regions = new MemoryRegions();
@Override
public void data(long address, byte[] data) {
regions.add(address, data.length);
}
@Override
public void eof() {
regions.compact();
}
public void reset() {
regions.clear();
}
public Region getFullRangeRegion() {
return regions.getFullRangeRegion();
}
public MemoryRegions getMemoryRegions() {
return regions;
}
}

View File

@ -0,0 +1,111 @@
/**
* @license Copyright (c) 2015, 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;
/**
* One memory region
*
* @author Jan Breuer
* @license BSD 2-Clause
*/
public class Region implements Comparable<Region> {
private long addressStart;
private long addressEnd;
public Region(long start, long length) {
this.addressStart = start;
this.addressEnd = start + length - 1;
}
/**
* Get length of the region
* @return
*/
public long getLength() {
return addressEnd - addressStart + 1;
}
/**
* Return last address in memory region
* @return
*/
public long getAddressEnd() {
return addressEnd;
}
/**
* Set end address
* @param addressEnd
*/
public void setAddressEnd(long addressEnd) {
this.addressEnd = addressEnd;
}
/**
* Get start address of the region
* @return
*/
public long getAddressStart() {
return addressStart;
}
/**
* Set start address
* @param addressStart
*/
public void setAddressStart(long addressStart) {
this.addressStart = addressStart;
}
/**
* Increment length of the region by value
* @param value
*/
void incLength(long value) {
addressEnd += value;
}
@Override
public String toString() {
return String.format("0x%08x:0x%08x (%dB 0x%08X)", addressStart, addressEnd, getLength(), getLength());
}
/**
* Compare, if one region is after another region
*
* @param o
* @return
*/
@Override
public int compareTo(Region o) {
if (this.addressStart == o.addressStart) {
return Long.compare(this.addressEnd, o.addressEnd);
} else {
return Long.compare(this.addressStart, o.addressStart);
}
}
}