From 4e8d761d2c97fc9d43892fd75cd28e033cdfe2e8 Mon Sep 17 00:00:00 2001 From: John-Michael Baier Date: Sun, 6 Dec 2020 17:01:32 +0100 Subject: [PATCH] add PIC loader --- src/tools/CMakeLists.txt | 7 +- src/tools/Makefile.am | 5 +- src/tools/ebuspicloader.cpp | 864 +++++++++++++++++++ src/tools/intelhex/intelhexclass.cpp | 1149 +++++++++++++++++++++++++ src/tools/intelhex/intelhexclass.h | 1159 ++++++++++++++++++++++++++ src/tools/intelhex/license.txt | 19 + 6 files changed, 3200 insertions(+), 3 deletions(-) create mode 100644 src/tools/ebuspicloader.cpp create mode 100644 src/tools/intelhex/intelhexclass.cpp create mode 100644 src/tools/intelhex/intelhexclass.h create mode 100644 src/tools/intelhex/license.txt diff --git a/src/tools/CMakeLists.txt b/src/tools/CMakeLists.txt index 920c3a6f..27f5f0a4 100644 --- a/src/tools/CMakeLists.txt +++ b/src/tools/CMakeLists.txt @@ -1,5 +1,6 @@ set(ebusctl_SOURCES ebusctl.cpp) set(ebusfeed_SOURCES ebusfeed.cpp) +set(ebuspicloader_SOURCES ebuspicloader.cpp intelhex/intelhexclass.cpp) if(HAVE_CONTRIB) set(ebusfeed_LIBS ${ebusfeed_LIBS} ebuscontrib) @@ -7,11 +8,13 @@ endif(HAVE_CONTRIB) include_directories(../lib/ebus) include_directories(../lib/utils) +include_directories(intelhex) add_executable(ebusctl ${ebusctl_SOURCES}) add_executable(ebusfeed ${ebusfeed_SOURCES}) +add_executable(ebuspicloader ${ebuspicloader_SOURCES}) target_link_libraries(ebusctl utils ebus ${LIB_ARGP} ${ebusctl_LIBS}) target_link_libraries(ebusfeed ebus ${LIB_ARGP} ${ebusfeed_LIBS}) +target_link_libraries(ebuspicloader ${LIB_ARGP}) -install(TARGETS ebusctl EXPORT ebusd DESTINATION usr/bin) - +install(TARGETS ebusctl ebuspicloader EXPORT ebusd DESTINATION usr/bin) diff --git a/src/tools/Makefile.am b/src/tools/Makefile.am index a53a9cbd..378b1f2f 100644 --- a/src/tools/Makefile.am +++ b/src/tools/Makefile.am @@ -2,7 +2,8 @@ AM_CXXFLAGS = -I$(top_srcdir)/src \ -isystem$(top_srcdir) bin_PROGRAMS = ebusctl \ - ebusfeed + ebusfeed \ + ebuspicloader ebusctl_SOURCES = ebusctl.cpp ebusctl_LDADD = ../lib/utils/libutils.a @@ -11,6 +12,8 @@ ebusfeed_SOURCES = ebusfeed.cpp ebusfeed_LDADD = ../lib/utils/libutils.a \ ../lib/ebus/libebus.a +ebuspicloader_SOURCES = ebuspicloader.cpp + if CONTRIB ebusfeed_LDADD += ../lib/ebus/contrib/libebuscontrib.a endif diff --git a/src/tools/ebuspicloader.cpp b/src/tools/ebuspicloader.cpp new file mode 100644 index 00000000..b3abac60 --- /dev/null +++ b/src/tools/ebuspicloader.cpp @@ -0,0 +1,864 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "intelhex/intelhexclass.h" + + +/** the version string of the program. */ +const char *argp_program_version = "eBUS adapter PIC firmware loader"; + +/** the documentation of the program. */ +static const char argpdoc[] = + "A tool for loading firmware to the eBUS adapter PIC." + "\vPORT is the serial port to use (e.g./dev/ttyUSB0)"; + +static const char argpargsdoc[] = "PORT"; + +/** the definition of the known program arguments. */ +static const struct argp_option argpoptions[] = { + {"verbose", 'v', nullptr, 0, "enable verbose output", 0 }, + {"dhcp", 'd', nullptr, 0, "set IP address to DHCP", 0 }, + {"ip", 'i', "IP", 0, "set IP address (e.g. 192.168.0.10)", 0 }, + {"mask", 'm', "MASK", 0, "set IP mask (e.g. 24)", 0 }, + {"macip", 'M', nullptr, 0, "set the MAC address suffix from the IP address", 0 }, + {"flash", 'f', "FILE", 0, "flash the FILE to the device", 0 }, + {"reset", 'r', nullptr, 0, "reset the device at the end on success", 0 }, + {nullptr, 0, nullptr, 0, nullptr, 0 }, +}; + +static bool verbose = false; +static bool setDhcp = false; +static bool setIp = false; +static uint8_t setIpAddress[] = {0, 0, 0, 0}; +static bool setMacFromIp = false; +static bool setMask = false; +static uint8_t setMaskLen = 0x1f; +static char* flashFile = nullptr; +static bool reset = false; + +bool parseByte(const char *arg, uint8_t minValue, uint8_t maxValue, uint8_t *result) { + char* strEnd = nullptr; + unsigned long value = 0; + strEnd = nullptr; + value = strtoul(arg, &strEnd, 10); + if (strEnd == nullptr || strEnd == arg || *strEnd != 0) { + return false; + } + if (valuemaxValue) { + return false; + } + *result = (uint8_t)value; + return true; +} + +bool parseShort(const char *arg, uint16_t minValue, uint16_t maxValue, uint16_t *result) { + char* strEnd = nullptr; + unsigned long value = 0; + strEnd = nullptr; + value = strtoul(arg, &strEnd, 10); + if (strEnd == nullptr || strEnd == arg || *strEnd != 0) { + return false; + } + if (valuemaxValue) { + return false; + } + *result = (uint16_t)value; + return true; +} + +error_t parse_opt(int key, char *arg, struct argp_state *state) { + char *ip = nullptr, *part = nullptr; + int pos = 0, sum = 0; + struct stat st; + switch (key) { + case 'v': // --verbose + verbose = true; + break; + case 'd': // --dhcp + if (setIp || setMask) { + argp_error(state, "either DHCP or IP address is needed"); + return EINVAL; + } + setDhcp = true; + break; + case 'i': // --ip=192.168.0.10 + if (arg == nullptr || arg[0] == 0) { + argp_error(state, "invalid IP address"); + return EINVAL; + } + if (setDhcp) { + argp_error(state, "either DHCP or IP address is needed"); + return EINVAL; + } + ip = strdup(arg); + part = strtok(ip, "."); + + for (pos=0; part && pos<4; pos++) { + if (!parseByte(part, 0, 255, setIpAddress+pos)) { + break; + } + sum += setIpAddress[pos]; + part = strtok(nullptr, "."); + } + free(ip); + if (pos!=4 || part || sum==0) { + argp_error(state, "invalid IP address"); + return EINVAL; + } + setIp = true; + break; + case 'm': + if (arg == nullptr || arg[0] == 0) { + argp_error(state, "invalid IP mask"); + return EINVAL; + } + if (setDhcp) { + argp_error(state, "either DHCP or IP address is needed"); + return EINVAL; + } + if (!parseByte(arg, 0, 0x1e, &setMaskLen)) { + argp_error(state, "invalid IP mask"); + return EINVAL; + } + setMask = true; + break; + case 'M': + setMacFromIp = true; + break; + case 'f': + if (arg == nullptr || arg[0] == 0 || stat(arg, &st) != 0 || !S_ISREG(st.st_mode)) { + argp_error(state, "invalid flash file"); + return EINVAL; + } + flashFile = arg; + break; + case 'r': + reset = true; + break; + default: + return ARGP_ERR_UNKNOWN; + } + return 0; +} + +// START: copy from generated bootloader + +#define WRITE_FLASH_BLOCKSIZE 32 +#define ERASE_FLASH_BLOCKSIZE 32 +#define END_FLASH 0x4000 + +// Frame Format +// +// [<...DATA...>] +// These values are negative because the FSR is set to PACKET_DATA to minimize FSR reloads. +typedef union +{ + struct __attribute__((__packed__)) + { + uint8_t command; + uint16_t data_length; + uint8_t EE_key_1; + uint8_t EE_key_2; + uint8_t address_L; + uint8_t address_H; + uint8_t address_U; + uint8_t address_unused; + uint8_t data[2*WRITE_FLASH_BLOCKSIZE]; + }; + uint8_t buffer[2*WRITE_FLASH_BLOCKSIZE+9]; +}frame_t; + +#define STX 0x55 + +#define READ_VERSION 0 +#define READ_FLASH 1 +#define WRITE_FLASH 2 +#define ERASE_FLASH 3 +#define READ_EE_DATA 4 +#define WRITE_EE_DATA 5 +#define READ_CONFIG 6 +#define WRITE_CONFIG 7 +#define CALC_CHECKSUM 8 +#define RESET_DEVICE 9 +#define CALC_CRC 10 + +#define MINOR_VERSION 0x08 // Version +#define MAJOR_VERSION 0x00 +//#define STX 0x55 // Actually code 0x55 is 'U' But this is what the autobaud feature of the PIC16F1 EUSART is looking for +#define ERROR_ADDRESS_OUT_OF_RANGE 0xFE +#define ERROR_INVALID_COMMAND 0xFF +#define COMMAND_SUCCESS 0x01 + +// END: copy from generated bootloader + +#define FRAME_HEADER_LEN 9 +#define FRAME_MAX_LEN (FRAME_HEADER_LEN+2*WRITE_FLASH_BLOCKSIZE) +#define BAUDRATE B115200 +#define WAIT_BYTE_TRANSFERRED_MILLIS 200 +#define WAIT_BITRATE_DETECTION_MILLIS 80 +#define WAIT_RESPONSE_TIMEOUT_MILLIS 100 + +long long getTime() { + timespec_t ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec*1000+ts.tv_nsec/1000000; +} + +ssize_t waitWrite(int fd, uint8_t *data, size_t len, int timeoutMillis) { + int ret; + struct pollfd pfd; + pfd.fd = fd; + pfd.events = POLLOUT | POLLERR | POLLHUP; + ret = poll(&pfd, 1, timeoutMillis); + if (ret >= 0 && pfd.revents & (POLLERR | POLLHUP)) { + return -1; + } + if (ret <= 0) { + return ret; + } + ret = write(fd, data, len); + if (ret<0) { + return ret; + } +#ifdef DEBUG_RAW + std::cout<<"> "<(ret)<<"/"<(len)<<":"<(data[pos]); + } + std::cout<= 0 && pfd.revents & (POLLERR | POLLHUP)) { + return -1; + } + if (ret <= 0) { + return ret; + } + ret = read(fd, data, len); + if (ret<0) { + return ret; + } +#ifdef DEBUG_RAW + std::cout<<"< "<(ret)<<"/"<(len)<<":"<(data[pos]); + } + std::cout<(ch) << std::endl; + } + return -1; + } + // read the answer from the device + len = FRAME_HEADER_LEN; // start with the header itself + noData = 0; + for (size_t pos=0; pos(frame.data[2] | (frame.data[3] << 8)) << std::endl; + } + std::cout<<"Device ID: "<(frame.data[6] | (frame.data[7]<<8)); + if (frame.data[6]==0xb0 && frame.data[7]==0x30) { + std::cout<<" (PIC16F15356)"; + } + std::cout<(frame.data[10])<(frame.data[11])<(frame.data[12])<(frame.data[13])<(frame.data[14])<(frame.data[15])<(address)<<":"; + } + std::cout<<" "<(frame.data[pos++]); + if (skipHigh) { + pos++; + } else if (pos(frame.data[pos++]); + } + address++; + if ((pos%16)==0) { + std::cout<(frame.command)<(frame.data_length)<(frame.address_H)<(frame.address_L); + for (int pos = 0; pos(pos)<<":"<(frame.data[pos++]); + pos++; + } + std::cout<>8)&0xff; + ssize_t ret = sendReceiveFrame(fd, frame, 0, len); + if (ret!=0) { + return ret; + } + if (print) { + printFrameData(frame, skipHigh); + } + if (storeData) { + memcpy(storeData, frame.data, len); + } + return 0; +} + +int writeConfig(int fd, uint16_t address, uint16_t len, uint8_t* data) { + frame_t frame; + memset(frame.buffer, 0, FRAME_MAX_LEN); + frame.command = WRITE_CONFIG; + frame.data_length = len; + frame.EE_key_1 = 0x55; + frame.EE_key_2 = 0xaa; + frame.address_L = address&0xff; + frame.address_H = (address>>8)&0xff; + memcpy(frame.data, data, len); + ssize_t ret = sendReceiveFrame(fd, frame, len, 1, 50); + if (ret!=0) { + return ret; + } + if (frame.data[0]!=COMMAND_SUCCESS) { + return -1; + } + return 0; +} + +int readFlash(int fd, uint16_t address, bool skipHigh=false, bool print=true, uint8_t* storeData=nullptr) { + frame_t frame; + memset(frame.buffer, 0, FRAME_MAX_LEN); + frame.command = READ_FLASH; + frame.data_length = 0x10; + frame.address_L = address&0xff; + frame.address_H = (address>>8)&0xff; + ssize_t ret = sendReceiveFrame(fd, frame, 0, -1); + if (ret!=0) { + return ret; + } + if (print) { + printFrameData(frame, skipHigh); + } + if (storeData) { + memcpy(storeData, frame.data, 0x10); + } + return 0; +} + +int writeFlash(int fd, uint16_t address, uint16_t len, uint8_t* data, bool hideErrors=false) { + frame_t frame; + memset(frame.buffer, 0, FRAME_MAX_LEN); + frame.command = WRITE_FLASH; + frame.data_length = len; + frame.EE_key_1 = 0x55; + frame.EE_key_2 = 0xaa; + frame.address_L = address&0xff; + frame.address_H = (address>>8)&0xff; + memcpy(frame.data, data, len); + ssize_t ret = sendReceiveFrame(fd, frame, len, 1, len*30, hideErrors); + if (ret!=0) { + return ret; + } + if (frame.data[0]!=COMMAND_SUCCESS) { + return -1; + } + return 0; +} + +int eraseFlash(int fd, uint16_t address, uint16_t len) { + frame_t frame; + memset(frame.buffer, 0, FRAME_MAX_LEN); + frame.command = ERASE_FLASH; + frame.data_length = (len+ERASE_FLASH_BLOCKSIZE-1)/ERASE_FLASH_BLOCKSIZE; + frame.EE_key_1 = 0x55; + frame.EE_key_2 = 0xaa; + frame.address_L = address&0xff; + frame.address_H = (address>>8)&0xff; + ssize_t ret = sendReceiveFrame(fd, frame, 0, 1, frame.data_length*5); + if (ret!=0) { + return ret; + } + if (frame.data[0]!=COMMAND_SUCCESS) { + return -frame.data[0]-1; + } + return 0; +} + +int calcChecksum(int fd, uint16_t address, uint16_t len) { + frame_t frame; + memset(frame.buffer, 0, FRAME_MAX_LEN); + frame.command = CALC_CHECKSUM; + frame.data_length = len; + frame.address_L = address&0xff; + frame.address_H = (address>>8)&0xff; + ssize_t ret = sendReceiveFrame(fd, frame, 0, 2, len*30); + if (ret!=0) { + return ret; + } + return frame.data[0] | (frame.data[1]<<8); +} + +int resetDevice(int fd) { + frame_t frame; + memset(frame.buffer, 0, FRAME_MAX_LEN); + frame.command = RESET_DEVICE; + ssize_t ret = sendReceiveFrame(fd, frame, 0, 1); + if (ret!=0) { + return ret; + } + if (frame.data[0]!=COMMAND_SUCCESS) { + return -frame.data[0]-1; + } + return 0; +} + +struct termios termios_original; + +int openSerial(std::string port) { + // open serial port + int fd = open(port.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); // non-blocking IO: | O_NONBLOCK); + if (fd == -1) { + std::cerr<<"unable to open "<> ih; + if (ih.getNoErrors()>0 || ih.getNoWarnings()>0) { + std::cerr<<"errors or warnings while reading the file:"<(startAddr) + << " - 0x" + << std::hex << std::setfill('0') << std::setw(4) << static_cast(endAddr) + << std::endl; + } + if (startAddr<0x800 || endAddr>=0x8000 || endAddr(nextAddr)<(-eraseRes-1)<(blockStart/2)<<" "; + } + if (writeFlash(fd, blockStart/2, WRITE_FLASH_BLOCKSIZE, buf, true)!=0) { + // repeat once silently: + if (writeFlash(fd, blockStart/2, WRITE_FLASH_BLOCKSIZE, buf)!=0) { + std::cerr << "unable to write flash at 0x" << std::hex << std::setfill('0') << std::setw(4) + << static_cast(blockStart/2) << std::endl; + return false; + } + } + std::cout<<"."; + if (++blocks>=64) { + blocks = 0; + } + std::cout.flush(); + } + blockStart += WRITE_FLASH_BLOCKSIZE; + } + std::cout<0) { + mac[2+i] = configData[i*2]; + } + } + if (useMUI) { + // read MUI to build uniqueMAC address + // start with MUI6, end with MUI8 (MUI9 is reserved) + readConfig(fd, 0x0106, 8, true, false, configData); // MUI + for (int i=0; i<3; i++) { + mac[3+i] = configData[i*2]; + } + } + std::cout<<"MAC address:"; + for (int i=0; i<6; i++) { + std::cout<<(i==0?' ':':')<(mac[i]); + } + std::cout<(ip[i]); + } + std::cout<<"/"<(maskLen)<=8 ? 255 : maskLen<=0 ? 0 : (255^((1<<(8-maskLen))-1)); + ip[pos] &= mask[pos]; + maskLen = maskLen>=8 ? maskLen-8 : 0; + } + ip[3] |= 1; // first address in network is used as gateway (not needed anyway)) + std::cout<<"IP gateway:"; + for (int i=0; i<4; i++) { + std::cout<<(i==0?' ':'.')<(ip[i]); + } + std::cout<(((data[1]&0xf)<<2) | ((data[0]&0xc0)>>6)) + << "." << static_cast(data[0]&0x3f) << std::endl; + if (verbose) { + std::cout << "Configuration words:" << std::endl; + readConfig(fd, 0x0007, 5*2); // Configuration Words + std::cout << "MUI:" << std::endl; + readConfig(fd, 0x0100, 9*2, true); // MUI + std::cout<<"EUI:"<(bootloaderVersion) <(firmwareVersion) < +#include +#include +#ifdef _MSC_FULL_VER +#include +#else +#include +#endif + +#include "intelhexclass.h" + +using namespace std; + +/******************************************************************************/ +/*! Possible record types for Intel HEX file. +* +* List of all possible record types that can be found in an Intel HEX file. +*******************************************************************************/ +enum intelhexRecordType { + DATA_RECORD, // '00' + END_OF_FILE_RECORD, // '01' + EXTENDED_SEGMENT_ADDRESS, // '02' + START_SEGMENT_ADDRESS, // '03' + EXTENDED_LINEAR_ADDRESS, // '04' + START_LINEAR_ADDRESS, // '05' + NO_OF_RECORD_TYPES +}; + +/******************************************************************************* +* Converts a 2 char string to its HEX value +*******************************************************************************/ +unsigned char intelhex::stringToHex(string value) +{ + unsigned char returnValue = 0; + string::iterator valueIterator; + + if(value.length() == 2) + { + valueIterator = value.begin(); + + for (int x=0; x < 2; x++) + { + /* Shift result variable 4 bits to the left */ + returnValue <<= 4; + + if (*valueIterator >= '0' && *valueIterator <= '9') + { + returnValue += + static_cast(*valueIterator - '0'); + } + else if (*valueIterator >= 'A' && *valueIterator <= 'F') + { + returnValue += + static_cast(*valueIterator - 'A' + 10); + } + else if (*valueIterator >= 'a' && *valueIterator <= 'f') + { + returnValue += + static_cast(*valueIterator - 'a' + 10); + } + else + { + /* Error occured - non-HEX value found */ + string message; + + message = "Can't convert byte 0x" + value + " @ 0x" + + ulToHexString(segmentBaseAddress) + " to hex."; + + addError(message); + + returnValue = 0; + } + + /* Iterate to next char in the string */ + ++valueIterator; + } + } + else + { + /* Error occured - more or less than two nibbles in the string */ + string message; + + message = value + " @ 0x" + ulToHexString(segmentBaseAddress) + + " isn't an 8-bit value."; + + addError(message); + } + + return returnValue; +} + +/******************************************************************************* +* Converts an unsigned long to a string in HEX format +*******************************************************************************/ +string intelhex::ulToHexString(unsigned long value) +{ + string returnString; + char localString[50]; + + returnString.erase(); + +#ifdef _MSC_FULL_VER + sprintf_s(localString, 49, "%08lX", value); +#else + snprintf(localString, 49, "%08lX", value); +#endif + + returnString.insert(0, localString); + + return returnString; +} + +/******************************************************************************* +* Converts an unsigned long to a string in DEC format +*******************************************************************************/ +string intelhex::ulToString(unsigned long value) +{ + string returnString; + char localString[50]; + + returnString.erase(); + +#ifdef _MSC_FULL_VER + sprintf_s(localString, 49, "%lu", value); +#else + snprintf(localString, 49, "%lu", value); +#endif + returnString.insert(0, localString); + + return returnString; +} + +/******************************************************************************* +* Converts an unsigned char to a string in HEX format +*******************************************************************************/ +string intelhex::ucToHexString(unsigned char value) +{ + string returnString; + char localString[50]; + + returnString.erase(); + +#ifdef _MSC_FULL_VER + sprintf_s(localString, 49, "%02X", value); +#else + snprintf(localString, 49, "%02X", value); +#endif + + returnString.insert(0, localString); + + return returnString; +} + +/******************************************************************************* +* Adds a warning to the list of warning messages +*******************************************************************************/ +void intelhex::addWarning(string warningMessage) +{ + string localMessage; + + /* Build the message and push the warning message onto the list */ + localMessage += ulToString(msgWarning.noOfWarnings + 1) + " Warning: " + + warningMessage; + + msgWarning.ihWarnings.push_back(localMessage); + + /* Update the number of warning messages */ + msgWarning.noOfWarnings = msgWarning.ihWarnings.size(); +} + +/******************************************************************************* +* Adds an error to the list of error messages +*******************************************************************************/ +void intelhex::addError(string errorMessage) +{ + string localMessage; + + /* Build the message and push the error message onto the list */ + localMessage += ulToString(msgError.noOfErrors + 1) + " Error: " + + errorMessage; + + msgError.ihErrors.push_back(localMessage); + + /* Update the number of error messages */ + msgError.noOfErrors = msgError.ihErrors.size(); +} + +/******************************************************************************* +* Decodes a data record read in from a file +*******************************************************************************/ +void intelhex::decodeDataRecord(unsigned char recordLength, + unsigned long loadOffset, + string::const_iterator data) +{ + /* Variable to store a byte of the record as a two char string */ + string sByteRead; + + /* Variable to store the byte of the record as an u.char */ + unsigned char byteRead; + + /* Calculate new SBA by clearing the low four bytes and then adding the */ + /* current loadOffset for this line of Intel HEX data */ + segmentBaseAddress &= ~(0xFFFFUL); + segmentBaseAddress += loadOffset; + + for (unsigned char x = 0; x < recordLength; x ++) + { + sByteRead.erase(); + + sByteRead = *data; + data++; + sByteRead += *data; + data++; + + byteRead = stringToHex(sByteRead); + + ihReturn=ihContent.insert( + pair(segmentBaseAddress, byteRead)); + + if (ihReturn.second==false) + { + /* If this address already contains the byte we are trying to */ + /* write, this is only a warning */ + if (ihReturn.first->second == byteRead) + { + string message; + + message = "Location 0x" + ulToHexString(segmentBaseAddress) + + " already contains data 0x" + sByteRead; + + addWarning(message); + } + /* Otherwise this is an error */ + else + { + string message; + + message = "Couldn't add 0x" + sByteRead + " @ 0x" + + ulToHexString(segmentBaseAddress) + + "; already contains 0x" + + ucToHexString(ihReturn.first->second); + + addError(message); + } + } + + /* Increment the segment base address */ + ++segmentBaseAddress; + } +} + +/******************************************************************************* +* Input Stream for Intel HEX File Decoding (friend function) +*******************************************************************************/ +istream& operator>>(istream& dataIn, intelhex& ihLocal) +{ + // Create a string to store lines of Intel Hex info + string ihLine; + /* Create a string to store a single byte of Intel HEX info */ + string ihByte; + // Create an iterator for this variable + string::iterator ihLineIterator; + // Create a line counter + unsigned long lineCounter = 0; + // Variable to hold a single byte (two chars) of data + unsigned char byteRead; + // Variable to calculate the checksum for each line + unsigned char intelHexChecksum; + // Variable to hold the record length + unsigned char recordLength; + // Variable to hold the load offset + unsigned long loadOffset; + // Variables to hold the record type + intelhexRecordType recordType; + + do + { + /* Clear the string before this next round */ + ihLine.erase(); + + /* Clear the checksum before processing this line */ + intelHexChecksum = 0; + + /* Get a line of data */ + dataIn >> ihLine; + + /* If the line contained some data, process it */ + if (ihLine.length() > 0) + { + /* Increment line counter */ + lineCounter++; + + /* Set string iterator to start of string */ + ihLineIterator = ihLine.begin(); + + /* Check that we have a ':' record mark at the beginning */ + if (*ihLineIterator != ':') + { + /* Add some warning code here */ + string message; + + message = "Line without record mark ':' found @ line " + + ihLocal.ulToString(lineCounter); + + ihLocal.addWarning(message); + + /* If this is the first line, let's simply give up. Chances */ + /* are this is not an Intel HEX file at all */ + if (lineCounter == 1) + { + message = "Intel HEX File decode aborted; ':' missing in " \ + "first line."; + ihLocal.addError(message); + + /* Erase ihLine content and break out of do...while loop */ + ihLine.erase(); + break; + } + } + else + { + /* Remove the record mark from the string as we don't need it */ + /* anymore */ + ihLine.erase(ihLineIterator); + } + + /* Run through the whole line to check the checksum */ + for (ihLineIterator = ihLine.begin(); + ihLineIterator != ihLine.end(); + /* Nothing - really! */ ) + { + /* Convert the line in pair of chars (making a single byte) */ + /* into single bytes, and then add to the checksum variable. */ + /* By adding all the bytes in a line together *including* the */ + /* checksum byte, we should get a result of '0' at the end. */ + /* If not, there is a checksum error */ + ihByte.erase(); + + ihByte = *ihLineIterator; + ++ihLineIterator; + /* Just in case there are an odd number of chars in the */ + /* just check we didn't reach the end of the string early */ + if (ihLineIterator != ihLine.end()) + { + ihByte += *ihLineIterator; + ++ihLineIterator; + + byteRead = ihLocal.stringToHex(ihByte); + + intelHexChecksum += byteRead; + } + else + { + string message; + + message = "Odd number of characters in line " + + ihLocal.ulToString(lineCounter); + + ihLocal.addError(message); + } + } + + /* Make sure the checksum was ok */ + if (intelHexChecksum == 0) + { + /* Reset iterator back to beginning of the line so we can now */ + /* decode it */ + ihLineIterator = ihLine.begin(); + + /* Clear all the variables associated with decoding a line of */ + /* Intel HEX code. */ + recordLength = 0; + loadOffset = 0; + + /* Get the record length */ + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + recordLength = ihLocal.stringToHex(ihByte); + + /* Get the load offset (2 bytes) */ + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + loadOffset = + static_cast(ihLocal.stringToHex(ihByte)); + loadOffset <<= 8; + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + loadOffset += + static_cast(ihLocal.stringToHex(ihByte)); + + /* Get the record type */ + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + recordType = + static_cast(ihLocal.stringToHex(ihByte)); + + /* Decode the INFO or DATA portion of the record */ + switch (recordType) + { + case DATA_RECORD: + ihLocal.decodeDataRecord(recordLength, loadOffset, + ihLineIterator); + if (ihLocal.verbose == true) + { + cout << "Data Record begining @ 0x" << + ihLocal.ulToHexString(loadOffset) << endl; + } + break; + + case END_OF_FILE_RECORD: + /* Check that the EOF record wasn't already found. If */ + /* it was, generate appropriate error */ + if (ihLocal.foundEof == false) + { + ihLocal.foundEof = true; + } + else + { + string message; + + message = "Additional End Of File record @ line " + + ihLocal.ulToString(lineCounter) + + " found."; + + ihLocal.addError(message); + } + /* Generate error if there were */ + if (ihLocal.verbose == true) + { + cout << "End of File" << endl; + } + break; + + case EXTENDED_SEGMENT_ADDRESS: + /* Make sure we have 2 bytes of data */ + if (recordLength == 2) + { + /* Extract the two bytes of the ESA */ + unsigned long extSegAddress = 0; + + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + extSegAddress = static_cast + (ihLocal.stringToHex(ihByte)); + extSegAddress <<= 8; + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + extSegAddress += static_cast + (ihLocal.stringToHex(ihByte)); + + /* ESA is bits 4-19 of the segment base address */ + /* (SBA), so shift left 4 bits */ + extSegAddress <<= 4; + + /* Update the SBA */ + ihLocal.segmentBaseAddress = extSegAddress; + } + else + { + /* Note the error */ + string message; + + message = "Extended Segment Address @ line " + + ihLocal.ulToString(lineCounter) + + " not 2 bytes as required."; + + ihLocal.addError(message); + } + if (ihLocal.verbose == true) + { + cout << "Ext. Seg. Address found: 0x" << + ihLocal.ulToHexString(ihLocal.segmentBaseAddress) + << endl; + } + + break; + + case START_SEGMENT_ADDRESS: + /* Make sure we have 4 bytes of data, and that no */ + /* Start Segment Address has been found to date */ + if (recordLength == 4 && + ihLocal.startSegmentAddress.exists == false) + { + /* Note that the Start Segment Address has been */ + /* found. */ + ihLocal.startSegmentAddress.exists = true; + /* Clear the two registers, just in case */ + ihLocal.startSegmentAddress.csRegister = 0; + ihLocal.startSegmentAddress.ipRegister = 0; + + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + ihLocal.startSegmentAddress.csRegister = + static_cast + (ihLocal.stringToHex(ihByte)); + ihLocal.startSegmentAddress.csRegister <<= 8; + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + ihLocal.startSegmentAddress.csRegister += + static_cast + (ihLocal.stringToHex(ihByte)); + + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + ihLocal.startSegmentAddress.ipRegister = + static_cast + (ihLocal.stringToHex(ihByte)); + ihLocal.startSegmentAddress.ipRegister <<= 8; + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + ihLocal.startSegmentAddress.ipRegister += + static_cast + (ihLocal.stringToHex(ihByte)); + } + /* Note an error if the start seg. address already */ + /* exists */ + else if (ihLocal.startSegmentAddress.exists == true) + { + string message; + + message = "Start Segment Address record appears again @ line " + + ihLocal.ulToString(lineCounter) + + "; repeated record ignored."; + + ihLocal.addError(message); + } + /* Note an error if the start lin. address already */ + /* exists as they should be mutually exclusive */ + if (ihLocal.startLinearAddress.exists == true) + { + string message; + + message = "Start Segment Address record found @ line " + + ihLocal.ulToString(lineCounter) + + " but Start Linear Address already exists."; + + ihLocal.addError(message); + } + /* Note an error if the record lenght is not 4 as */ + /* expected */ + if (recordLength != 4) + { + string message; + + message = "Start Segment Address @ line " + + ihLocal.ulToString(lineCounter) + + " not 4 bytes as required."; + + ihLocal.addError(message); + } + if (ihLocal.verbose == true) + { + cout << "Start Seg. Address - CS 0x" << + ihLocal.ulToHexString(ihLocal.startSegmentAddress.csRegister) << + " IP 0x" << + ihLocal.ulToHexString(ihLocal.startSegmentAddress.ipRegister) + << endl; + } + break; + + case EXTENDED_LINEAR_ADDRESS: + /* Make sure we have 2 bytes of data */ + if (recordLength == 2) + { + /* Extract the two bytes of the ELA */ + unsigned long extLinAddress = 0; + + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + extLinAddress = static_cast + (ihLocal.stringToHex(ihByte)); + extLinAddress <<= 8; + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + extLinAddress += static_cast + (ihLocal.stringToHex(ihByte)); + + /* ELA is bits 16-31 of the segment base address */ + /* (SBA), so shift left 16 bits */ + extLinAddress <<= 16; + + /* Update the SBA */ + ihLocal.segmentBaseAddress = extLinAddress; + } + else + { + /* Note the error */ + //cout << "Error in Ext. Lin. Address" << endl; + + string message; + + message = "Extended Linear Address @ line " + + ihLocal.ulToString(lineCounter) + + " not 2 bytes as required."; + + ihLocal.addError(message); + } + if (ihLocal.verbose == true) + { + cout << "Ext. Lin. Address 0x" << + ihLocal.ulToHexString(ihLocal.segmentBaseAddress) + << endl; + } + + break; + + case START_LINEAR_ADDRESS: + /* Make sure we have 4 bytes of data */ + if (recordLength == 4 && + ihLocal.startLinearAddress.exists == false) + { + /* Note that the linear start address has been */ + /* found */ + ihLocal.startLinearAddress.exists = true; + + /* Clear the EIP register */ + ihLocal.startLinearAddress.eipRegister = 0; + + /* Extract the four bytes of the SLA */ + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + ihLocal.startLinearAddress.eipRegister = + static_cast + (ihLocal.stringToHex(ihByte)); + ihLocal.startLinearAddress.eipRegister <<= 8; + + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + ihLocal.startLinearAddress.eipRegister += + static_cast + (ihLocal.stringToHex(ihByte)); + ihLocal.startLinearAddress.eipRegister <<= 8; + + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + ihLocal.startLinearAddress.eipRegister += + static_cast + (ihLocal.stringToHex(ihByte)); + ihLocal.startLinearAddress.eipRegister <<= 8; + + ihByte.erase(); + ihByte = *ihLineIterator; + ++ihLineIterator; + ihByte += *ihLineIterator; + ++ihLineIterator; + ihLocal.startLinearAddress.eipRegister += + static_cast + (ihLocal.stringToHex(ihByte)); + + } + /* Note an error if the start seg. address already */ + /* exists */ + else if (ihLocal.startLinearAddress.exists == true) + { + string message; + + message = "Start Linear Address record appears again @ line " + + ihLocal.ulToString(lineCounter) + + "; repeated record ignored."; + + ihLocal.addError(message); + } + /* Note an error if the start seg. address already */ + /* exists as they should be mutually exclusive */ + if (ihLocal.startSegmentAddress.exists == true) + { + string message; + + message = "Start Linear Address record found @ line " + + ihLocal.ulToString(lineCounter) + + " but Start Segment Address already exists."; + + ihLocal.addError(message); + } + /* Note an error if the record lenght is not 4 as */ + /* expected */ + if (recordLength != 4) + { + string message; + + message = "Start Linear Address @ line " + + ihLocal.ulToString(lineCounter) + + " not 4 bytes as required."; + + ihLocal.addError(message); + } + if (ihLocal.verbose == true) + { + cout << "Start Lin. Address - EIP 0x" << + ihLocal.ulToHexString(ihLocal.startLinearAddress.eipRegister) + << endl; + } + break; + + default: + /* Handle the error here */ + if (ihLocal.verbose == true) + { + cout << "Unknown Record @ line " << + ihLocal.ulToString(lineCounter) << endl; + } + + + string message; + + message = "Unknown Intel HEX record @ line " + + ihLocal.ulToString(lineCounter); + + ihLocal.addError(message); + + break; + } + } + else + { + /* Note that the checksum contained an error */ + string message; + + message = "Checksum error @ line " + + ihLocal.ulToString(lineCounter) + + "; calculated 0x" + + ihLocal.ucToHexString(intelHexChecksum - byteRead) + + " expected 0x" + + ihLocal.ucToHexString(byteRead); + + ihLocal.addError(message); + } + } + } while (ihLine.length() > 0); + + if (ihLocal.verbose == true) + { + cout << "Decoded " << lineCounter << " lines from file." << endl; + } + + return(dataIn); +} + +/******************************************************************************* +* Output Stream for Intel HEX File Encoding (friend function) +*******************************************************************************/ +ostream& operator<<(ostream& dataOut, intelhex& ihLocal) +{ + /* Stores the address offset needed by the linear/segment address records */ + unsigned long addressOffset; + /* Iterator into the ihContent - where the addresses & data are stored */ + map::iterator ihIterator; + /* Holds string that represents next record to be written */ + string thisRecord; + /* Checksum calculation variable */ + unsigned char checksum; + + thisRecord.clear(); + + /* Check that there is some content to encode */ + if (ihLocal.ihContent.size() > 0) + { + /* Calculate the Linear/Segment address */ + ihIterator = ihLocal.ihContent.begin(); + addressOffset = (*ihIterator).first; + checksum = 0; + + /* Construct the first record to define the segment base address */ + if (ihLocal.segmentAddressMode == false) + { + unsigned char dataByte; + + addressOffset >>= 16; + + thisRecord = ":02000004"; + checksum = 0x02 + 0x04; + + dataByte = static_cast(addressOffset & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast((addressOffset >> 8) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); + } + else + { + unsigned char dataByte; + + addressOffset >>= 4; + + thisRecord = ":02000002"; + checksum = 0x02 + 0x02; + + dataByte = static_cast(addressOffset & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast((addressOffset >> 8) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); + } + + /* Output the record */ + dataOut << thisRecord << endl; + + /* Now loop through all the available data and insert into file */ + /* with maximum 16 bytes per line, and making sure to keep the */ + /* segment base address up to date */ + vector recordData; + unsigned long previousAddress; + unsigned long currentAddress; + unsigned long loadOffset; + + while(ihIterator != ihLocal.ihContent.end()) + { + /* Check to see if we need to start a new linear/segment section */ + loadOffset = (*ihIterator).first; + + /* If we are using the linear mode... */ + if (ihLocal.segmentAddressMode == false) + { + if ((loadOffset >> 16) != addressOffset) + { + unsigned char dataByte; + + thisRecord.clear(); + checksum = 0; + + addressOffset = loadOffset; + addressOffset >>= 16; + + thisRecord = ":02000004"; + checksum = 0x02 + 0x04; + + dataByte = static_cast(addressOffset & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast((addressOffset >> 8) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); + + /* Output the record */ + dataOut << thisRecord << endl; + } + } + /* ...otherwise assume segment mode */ + else + { + if ((loadOffset >> 4) != addressOffset) + { + unsigned char dataByte; + + thisRecord.clear(); + checksum = 0; + + addressOffset = loadOffset; + addressOffset >>= 4; + + thisRecord = ":02000002"; + checksum = 0x02 + 0x02; + + dataByte = static_cast(addressOffset & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast((addressOffset >> 8) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); + + /* Output the record */ + dataOut << thisRecord << endl; + } + } + + /* Prepare for encoding next data record */ + thisRecord.clear(); + checksum = 0; + recordData.clear(); + + /* We need to check where the data actually starts, but only the */ + /* bottom 16-bits; the other bits are in the segment/linear */ + /* address record */ + loadOffset = (*ihIterator).first & 0xFFFF; + + /* Loop through and collect up to 16 bytes of data */ + for (int x = 0; x < 16; x++) + { + currentAddress = (*ihIterator).first & 0xFFFF; + + recordData.push_back((*ihIterator).second); + + ihIterator++; + + /* Check that we haven't run out of data */ + if (ihIterator == ihLocal.ihContent.end()) + { + break; + } + + /* Check that the next address is consecutive */ + previousAddress = currentAddress; + currentAddress = (*ihIterator).first & 0xFFFF; + if (currentAddress != (previousAddress + 1)) + { + break; + } + + /* If we got here we have a consecutive address and can keep */ + /* building up the data portion of the data record */ + } + + /* Now we should have some data to encode; check first */ + if (recordData.size() > 0) + { + vector::iterator itData; + unsigned char dataByte; + + /* Start building data record */ + thisRecord = ":"; + + /* Start with the RECLEN record length */ + dataByte = static_cast(recordData.size()); + thisRecord += ihLocal.ucToHexString(dataByte); + checksum += dataByte; + + /* Then the LOAD OFFSET */ + dataByte = static_cast((loadOffset >> 8) & 0xFF); + thisRecord += ihLocal.ucToHexString(dataByte); + checksum += dataByte; + dataByte = static_cast(loadOffset & 0xFF); + thisRecord += ihLocal.ucToHexString(dataByte); + checksum += dataByte; + + /* Then the RECTYP record type (no need to add to checksum - */ + /* value is zero '00' */ + thisRecord += "00"; + + /* Now we add the data */ + for (itData = recordData.begin(); itData != recordData.end(); itData ++) + { + dataByte = (*itData); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + } + + /* Last bit - add the checksum */ + thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); + + /* Now write the record */ + dataOut << thisRecord << endl; + } + } + } + + /* If there is a segment start address, output the data */ + if (ihLocal.startSegmentAddress.exists == true) + { + unsigned char dataByte; + + thisRecord.clear(); + checksum = 0; + + thisRecord = ":04000003"; + checksum = 0x04 + 0x03; + + dataByte = static_cast((ihLocal.startSegmentAddress.csRegister >> 8) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast(ihLocal.startSegmentAddress.csRegister & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast((ihLocal.startSegmentAddress.ipRegister >> 8) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast(ihLocal.startSegmentAddress.ipRegister & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + + /* Last bit - add the checksum */ + thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); + + /* Now write the record */ + dataOut << thisRecord << endl; + } + + /* If there is a linear start address, output the data */ + if (ihLocal.startLinearAddress.exists == true) + { + unsigned char dataByte; + + thisRecord.clear(); + checksum = 0; + + thisRecord = ":04000005"; + checksum = 0x04 + 0x05; + + dataByte = static_cast((ihLocal.startLinearAddress.eipRegister >> 24) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast((ihLocal.startLinearAddress.eipRegister >> 16) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast((ihLocal.startLinearAddress.eipRegister >> 8) & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + dataByte = static_cast(ihLocal.startLinearAddress.eipRegister & 0xFF); + checksum += dataByte; + thisRecord += ihLocal.ucToHexString(dataByte); + + + /* Last bit - add the checksum */ + thisRecord += ihLocal.ucToHexString(0x00 - (checksum & 0xFF)); + + /* Now write the record */ + dataOut << thisRecord << endl; + } + + /* Whatever happened, we can always output the EOF record */ + dataOut << ":00000001FF" << endl; + + return (dataOut); +} + +/******************************************************************************* +* +* INTEL HEX FILE CLASS MODULE END +* +*******************************************************************************/ diff --git a/src/tools/intelhex/intelhexclass.h b/src/tools/intelhex/intelhexclass.h new file mode 100644 index 00000000..b53ab1e0 --- /dev/null +++ b/src/tools/intelhex/intelhexclass.h @@ -0,0 +1,1159 @@ +/******************************************************************************* +* intelhexclass - class definitions * +* * +* A class to handle the encoding and decoding of an Intel HEX format file as * +* generated by many tool chains for embedded processors and microcontrollers. * +* * +* This class is constructed based upon the definition given in the document * +* 'Hexadecimal Object File Format Specification', Revision A, January 6, 1988, * +* © 1998 Intel Corporation * +*------------------------------------------------------------------------------* +* class intelhex * +* Member Functions: * +* * +*******************************************************************************/ + +/******************************************************************************/ +/*! \file intelhexclass.h +* \author Stuart Cording aka CODINGHEAD +* +* A class to handle the encoding, decoding and manipulatio of an Intel HEX +* format file as generated by many tool chains for embedded processors and +* microcontrollers. +* +* This class is constructed based upon the definition given in the document +* 'Hexadecimal Object File Format Specification', Revision A, January 6, 1988, +* © 1998 Intel Corporation. +******************************************************************************** +* \note See the git versioning notes for version information +* +*******************************************************************************/ + +/******************************************************************************* +* +* INTEL HEX CLASS MODULE +* +*******************************************************************************/ + +#ifndef INTELHEXCLASS_MODULE_PRESENT__ +#define INTELHEXCLASS_MODULE_PRESENT__ + +/******************************************************************************* +* INCLUDE FILES +*******************************************************************************/ +#include +#include +#include + +/******************************************************************************* +* EXTERNS +*******************************************************************************/ + + +/******************************************************************************* +* DEFAULT CONFIGURATION +*******************************************************************************/ + + +/******************************************************************************* +* DEFINES +*******************************************************************************/ + +using namespace std; + +/******************************************************************************/ +/*! \cond +* class - intelhex +* \endcond +* +* \brief Class to decode, encode and manipulate Intel HEX format files. +* +* The Intel HEX class allows the user to stream in the content of an Intel HEX +* file so that its content can by analysed more easily than trying to decode +* the Intel HEX file in a text editor. In conjunction with a suitable +* application it is possible to create content, analyse content and even compare +* the content of files with one another. +*******************************************************************************/ +class intelhex { + /**********************************************************************/ + /*! \brief Output stream overload operator. + * + * Operator overloaded to encode any data held in memory into the Intel + * HEX format for storage on disk + * + * \sa operator>>() + * + * \param dataOut - Output stream for to store the decoded file + * information + * \param ihLocal - Points to this class so that friend function has + * access to private class members + * + * \retval - pointer to output stream + ***********************************************************************/ + friend ostream& operator<<(ostream& dataOut, + intelhex& ihLocal); + + /**********************************************************************/ + /*! \brief Input stream overload operator. + * + * Operator overloaded to decode data streamed in from a file in the + * Intel HEX format into memory + * + * \sa operator<<() + * + * \param dataIn - Input stream for the encoded file information + * \param ihLocal - Points to this class so that friend function has + * access to private class members + * + * \retval - pointer to input stream + ***********************************************************************/ + friend istream& operator>>(istream& dataIn, + intelhex& ihLocal); + + private: + /**********************************************************************/ + /*! \brief Container for decoded Intel HEX content. + * + * STL map holding the addresses found in the Intel HEX file and the + * associated data byte stored at that address + ***********************************************************************/ + map ihContent; + + /**********************************************************************/ + /*! \brief Iterator for the container holding the decoded Intel HEX + * content. + * + * This iterator is used by the class to point to the location in memory + * currently being used to read or write data. If no file has been + * loaded into memory, it points to the start of ihContent. + ***********************************************************************/ + map::iterator ihIterator; + + /**********************************************************************/ + /*! \brief Pair for the container holding the decoded Intel HEX content. + * + * This is used to acquire the result of an attempt to insert new data + * into ihContent. Since the ihContent is a map STL, it can't allow + * data to be assigned to the same address more than once. In this way we + * can ensure that no address in a file is falsely assigned data more + * than once. + ***********************************************************************/ + pair::iterator,bool> ihReturn; + + /**********************************************************************/ + /*! \brief Stores segment base address of Intel HEX file. + * + * The segment base address is a 32-bit address to which the current + * load offset (as found in a Data Record line of the Intel HEX file) is + * added to calculate the actual address of the data. The Data Records + * can only point to a 64kByte address, so the segment base address + * expands the addressing to 4GB. This variable always holds the last + * address accessed. This variable is only used during file decoding + * and encoding in the operator<< and operator>> class member friend + * functions. + ***********************************************************************/ + unsigned long segmentBaseAddress; + + /**********************************************************************/ + /*! \brief Stores the content of the CS/IP Registers, if used. + * + * Used to store the content of the CS and IS Register for HEX files + * created for x286 or earlier Intel processors. This information is + * retrieved from the Start Segment Address Record or can be defined + * by the user using the setStartSegmentAddress() function. + * The found element defines if these registers hold valid data or not. + * + * \param csRegister - content of the CS register + * \param ipRegister - content of the IP register + * \param exists - defines if values for the above registers have + * been written (true) or not (false) + * + * \sa getStartSegmentAddress(), setStartSegmentAddress() + ***********************************************************************/ + struct { + unsigned short csRegister; + unsigned short ipRegister; + bool exists; + } startSegmentAddress; + + /**********************************************************************/ + /*! \brief Stores the content of the EIP Register, if used. + * + * Used to store the content of the EIP Register for HEX files created + * for x386 Intel processors. This information is retrieved from the + * the Start Linear Address Record or can be defined by using the + * setStartLinearAddress() function. + * The found element defines if this register holds valid data or not. + * + * \param eipRegister - content of the EIP register + * \param exists - defines if a value for the above register has + * been written (true) or not (false) + * + * \sa getStartLinearAddress(), setStartLinearAddress() + ***********************************************************************/ + struct { + unsigned long eipRegister; + bool exists; + } startLinearAddress; + + + /**********************************************************************/ + /*! \brief Structure to hold warning messages. + * + * Holds warning messages generated during encoding/decoding process and + * number of messages currently present in system + * + * \param ihWarnings - list of warning messages as strings + * \param noOfWarnings - no of warning messages still present in + * the list + ***********************************************************************/ + struct { + list ihWarnings; + unsigned long noOfWarnings; + } msgWarning; + + /**********************************************************************/ + /*! \brief Structure to hold error messages. + * + * Holds error messages generated during encoding/decoding process and + * number of messages currently present in system + * + * \param ihErrors - list of error messages as strings + * \param noOferrors - no of error messages still present in the + * list + ***********************************************************************/ + struct { + list ihErrors; + unsigned long noOfErrors; + } msgError; + + /**********************************************************************/ + /*! \brief Note that EOF record is found. + * + * Used to note that the EOF record was found in order to ensure that it + * doesn't appear twice during encoding. + ***********************************************************************/ + bool foundEof; + + /**********************************************************************/ + /*! \brief Select verbose mode. + * + * Used during development to display messages as the incoming data + * stream is decoded + ***********************************************************************/ + bool verbose; + + /**********************************************************************/ + /*! \brief Select segment address mode. + * + * If true, use the segment addressing mode when encoding files. + * otherwise the default linear address mode will be used. Please refer + * to Intel's Hexadecimal Object File Format Specifiation for further + * information. + ***********************************************************************/ + bool segmentAddressMode; + + /*********************************************************************** + * \brief Converts a 2 char string to its HEX value. + * + * Converts a two byte string to its equivalent value in hexadecimal + * + * \param value - a two character, valid ASCII representation of + * a hexadecimal value + * + * \retval 'value' valid - 8-bit value + * \retval 'value' invalid - 0x00 and calls addWarning() + * + * \note + * This function will post a warning message using the warning handling + * system addWarning() if: + * -# The string contains anything other that exactly two characters + * -# The string contains anything other than the characters 0-9, a-f + * and A-F + * + * \sa ulToHexString(), ucToHexString(), ulToString() + ***********************************************************************/ + unsigned char stringToHex(string value); + + /*********************************************************************** + * \brief Converts an unsigned long to a string in HEX format. + * + * Takes the received paramter and converts it into its equivalent value + * represented in ASCII and formatted in hexadecimal. Return value is an + * 8 character long string, prefaced with '0's where necessary. + * + * \param value - a value between 0x0000000 and 0xFFFFFFFF + * + * \retval - 8-character long string + * + * \note + * Alpha characters are capitalised. + * + * \sa + * stringToHex(), ucToHexString(), ulToString() + ***********************************************************************/ + string ulToHexString(unsigned long value); + + /**********************************************************************/ + /*! \brief Converts an unsigned char to a string in HEX format. + * + * Takes the received paramter and converts it into its equivalent value + * represented in ASCII and formatted in hexadecimal. Return value is a + * 2 character long string, prefaced with '0' where necessary. + * + * \param value - a value between 0x00 and 0xFF + * + * \retval - 2-character long string + * + * \note + * Alpha characters are capitalised. + * + * \sa + * stringToHex(), ulToHexString(), ulToString() + ***********************************************************************/ + string ucToHexString(unsigned char value); + + /**********************************************************************/ + /*! \brief Converts an unsigned long to a string in DEC format. + * + * Takes the received paramter and converts it into its equivalent value + * represented in ASCII and formatted in decimal. Return value will never + * be longer than a 48 character long string. + * + * \param value - value to be converted + * + * \retval - ASCII string representation of value + * + * \sa + * stringToHex(), ulToHexString(), ucToHexString() + ***********************************************************************/ + string ulToString(unsigned long value); + + /**********************************************************************/ + /*! \brief Decodes the data content of a data record. + * + * Takes the data element of a data record in string format, converts + * each 2 char element into a single byte and then inserts that byte of + * data into the ihContent STL map. + * + * \sa encodeDataRecord() + * + * \param recordLength - Number of bytes in this record as extracted + * from this line in the Intel HEX file + * \param loadOffset - The offset from the segment base address for + * the first byte in this record + * \param data - The data content of the record in a string + ***********************************************************************/ + void decodeDataRecord(unsigned char recordLength, + unsigned long loadOffset, + string::const_iterator data); + + /**********************************************************************/ + /*! \brief Add a warning message to the warning message list. + * + * + * \param warningMessage - the text to be added for this warning + ***********************************************************************/ + void addWarning(string warningMessage); + + /**********************************************************************/ + /*! \brief Add an error message to the error message list. + * + * \param errorMessage - the text to be added for this error + ***********************************************************************/ + void addError(string errorMessage); + + public: + /**********************************************************************/ + /*! \brief intelhex Class Constructor. + * + * Important initialisation steps performed here: + * - clear segment base address to zero + * - clear all x86 start address registers to zero + * - note that there are, as yet, no errors or warnings + * - note that the EOF record has not yet been found + * - set verbode mode to 'false' (default) + * - initialise class ihIterator + ***********************************************************************/ + intelhex() + { + /* Initialise the segment base address to zero */ + segmentBaseAddress = 0; + /* Clear content of register variables used with the 'Start Segment' + * and 'Start Linear' address records */ + startSegmentAddress.ipRegister = 0; + startSegmentAddress.csRegister = 0; + startSegmentAddress.exists = false; + startLinearAddress.eipRegister = 0; + startLinearAddress.exists = false; + /* Set up error and warning handling variables */ + msgWarning.noOfWarnings = 0; + msgError.noOfErrors = 0; + /* Note that the EOF record has not been found yet */ + foundEof = false; + /* Set verbose mode to off */ + verbose = false; + /* Set segment address mode to false (default) */ + segmentAddressMode = false; + /* Ensure ihContent is cleared and point ihIterator at it */ + ihContent.clear(); + ihContent.begin(); + ihIterator = ihContent.begin(); + } + + /**********************************************************************/ + /*! \brief intelhex Class Deconstructor. + * + * Currently the deconstructor is intentially empty. + ***********************************************************************/ + ~intelhex() + { + /* Currently nothing */ + } + + /**********************************************************************/ + /*! \brief intelhex Class Copy Constructor. + * + * Copy constructor copies all essential elements for the class. + ***********************************************************************/ + intelhex(const intelhex &ihSource) + { + /* Initialise the segment base address */ + segmentBaseAddress = ihSource.segmentBaseAddress; + /* Initialise content of register variables used with the 'Start Segment' + * and 'Start Linear' address records */ + startSegmentAddress.ipRegister = ihSource.startSegmentAddress.ipRegister; + startSegmentAddress.csRegister = ihSource.startSegmentAddress.csRegister; + startSegmentAddress.exists = ihSource.startSegmentAddress.exists; + startLinearAddress.eipRegister = ihSource.startLinearAddress.eipRegister; + startLinearAddress.exists = ihSource.startLinearAddress.exists; + /* Set up error and warning handling variables */ + msgWarning.noOfWarnings = ihSource.msgWarning.noOfWarnings; + msgWarning.ihWarnings = ihSource.msgWarning.ihWarnings; + msgError.noOfErrors = ihSource.msgError.noOfErrors; + msgError.ihErrors = ihSource.msgError.ihErrors; + /* Note that the EOF record has not been found yet */ + foundEof = ihSource.foundEof; + /* Set verbose mode to off */ + verbose = ihSource.verbose; + /* Set segment address mode to false (default) */ + segmentAddressMode = ihSource.segmentAddressMode; + /* Copy HEX file content variables */ + ihContent = ihSource.ihContent; + ihIterator = ihSource.ihIterator; + } + + /**********************************************************************/ + /*! \brief intelhex Class Assignment Operator. + * + * Implements the assignment operator so that the content of the Intel + * HEX file in memory can be copied to another 'intelhex' variable. + * You may want to keep a copy of the original data in memory and + * only manipulate a copy. + * + * \param ihSource - intelhex variable to be assigned to new + * variable + * + * \retval pointer to variable to which value is to be assigned + ***********************************************************************/ + intelhex& operator= (const intelhex &ihSource) + { + /* Check that we are not trying to assign ourself to ourself */ + /* i.e. are the source/destination addresses the same like */ + /* myData = myData; */ + if (this == &ihSource) + return *this; + + /* Initialise the segment base address */ + segmentBaseAddress = ihSource.segmentBaseAddress; + /* Initialise content of register variables used with the 'Start Segment' + * and 'Start Linear' address records */ + startSegmentAddress.ipRegister = ihSource.startSegmentAddress.ipRegister; + startSegmentAddress.csRegister = ihSource.startSegmentAddress.csRegister; + startSegmentAddress.exists = ihSource.startSegmentAddress.exists; + startLinearAddress.eipRegister = ihSource.startLinearAddress.eipRegister; + startLinearAddress.exists = ihSource.startLinearAddress.exists; + /* Set up error and warning handling variables */ + msgWarning.noOfWarnings = ihSource.msgWarning.noOfWarnings; + msgWarning.ihWarnings = ihSource.msgWarning.ihWarnings; + msgError.noOfErrors = ihSource.msgError.noOfErrors; + msgError.ihErrors = ihSource.msgError.ihErrors; + /* Note that the EOF record has not been found yet */ + foundEof = ihSource.foundEof; + /* Set verbose mode to off */ + verbose = ihSource.verbose; + /* Set segment address mode to false (default) */ + segmentAddressMode = ihSource.segmentAddressMode; + /* Copy HEX file content variables */ + ihContent = ihSource.ihContent; + ihIterator = ihSource.ihIterator; + + return *this; + } + + /**********************************************************************/ + /*! \brief Overloaded prefix increment operator + * + * Overloads the prefix increment operator to move interal iterator to + * next entry in the ihContent map + * + ***********************************************************************/ + intelhex& operator++() + { + ++ihIterator; + + return(*this); + } + + /**********************************************************************/ + /*! \brief Overloaded postfix increment operator + * + * Overloads the postfix increment operator to move interal iterator to + * next entry in the ihContent map + * + ***********************************************************************/ + const intelhex operator++(int) + { + intelhex tmp(*this); + ++(*this); + return(tmp); + } + + /**********************************************************************/ + /*! \brief Overloaded prefix decrement operator + * + * Overloads the prefix decrement operator to move interal iterator to + * previous entry in the ihContent map + * + ***********************************************************************/ + intelhex& operator--() + { + --ihIterator; + + return(*this); + } + + /**********************************************************************/ + /*! \brief Overloaded postfix decrement operator + * + * Overloads the postfix decrement operator to move interal iterator to + * previous entry in the ihContent map + * + ***********************************************************************/ + const intelhex operator--(int) + { + intelhex tmp(*this); + --(*this); + return(tmp); + } + + /**********************************************************************/ + /*! \brief Moves the address pointer to the first available address. + * + * The address pointer will be moved to the first available address in + * memory of the decoded file or of the data the user has inserted into + * memory for the purpose of encoding into the Intel HEX format. + * + * \sa end() + * + * \note This function has no effect if no file has been as yet decoded + * and no data has been inserted into memory. + ***********************************************************************/ + void begin() + { + if (ihContent.size() != 0) + { + ihIterator = ihContent.begin(); + } + } + + /**********************************************************************/ + /*! \brief Moves the address pointer to the last available address. + * + * The address pointer will be moved to the last available address in + * memory of the decoded file or of the data the user has inserted into + * memory for the purpose of encoding into the Intel HEX format. + * + * \sa begin() + * + * \note This function has no effect if no file has been as yet decoded + * and no data has been inserted into memory. + ***********************************************************************/ + void end() + { + if (!ihContent.empty()) + { + ihIterator = ihContent.end(); + --ihIterator; + } + } + + /**********************************************************************/ + /*! \brief Returns current size of decoded file + * + * The quantity of bytes decoded thus far is returned. + ***********************************************************************/ + unsigned long size() + { + return static_cast(ihContent.size()); + } + + /**********************************************************************/ + /*! \brief Checks if we have reached end of available data + * + * The internal pointer is checked to see if we have reached the end of + * the data held in memory + * + * \retval true - reached the end of the Intel HEX data in memory or no + * data in memory yet. + * \retval false - end of Intel HEX data in memory not yet reached. + ***********************************************************************/ + bool endOfData() + { + /* Return true if there is no data anyway */ + bool result = true; + + if (!ihContent.empty()) + { + map::iterator it \ + = ihContent.end(); + + --it; + + if (it != ihIterator) + { + result = false; + } + } + return result; + } + + /**********************************************************************/ + /*! \brief Indicates if the container for data is empty or not + * + * The map container is checked for content. + * + * \retval true - the container is empty - no data has been extracted. + * \retval false - there is data in the container. + ***********************************************************************/ + bool empty() + { + return ihContent.empty(); + } + + /**********************************************************************/ + /*! \brief Moves the address pointer to the desired address. + * + * Address pointer will take on the requested address if the address + * exists in the data stored in memory. If not, the address pointer does + * not change. + * + * \sa currentAddress() + * + * \param address - Desired new address for the address pointer + * + * \retval true - Address exists; pointer moved successfully + * \retval false - Address did not exist; pointer not moved + ***********************************************************************/ + bool jumpTo(unsigned long address) + { + bool result = false; + + if (ihContent.size() != 0) + { + map::iterator it; + it = ihContent.find(address); + if (it != ihContent.end()) + { + result = true; + ihIterator = it; + } + } + return result; + } + + /**********************************************************************/ + /*! \brief Increments to next piece of data. + * + * Address pointer will take on the address of the next location for + * which there is data. + * + * \sa decrementAddress() + * + * \retval true - pointer was incremented; a new data value was found + * \retval false - end of available data reached; pointer is unchanged + ***********************************************************************/ + bool incrementAddress() + { + bool result = false; + + /* If we have data */ + if (ihContent.size() != 0) + { + /* If we're not already pointing to the end */ + if (ihIterator != ihContent.end()) + { + /* Increment iterator */ + ihIterator++; + + /* If we still haven't reached the end... */ + if (ihIterator != ihContent.end()) + { + /* Everything is ok! */ + result = true; + } + } + } + + /* If incrementation of the iterator was successful, return true */ + return result; + } + + /**********************************************************************/ + /*! \brief Decrements to next piece of data. + * + * Address pointer will take on the address of the previous location for + * which there is data. + * + * \sa incrementAddress() + * + * \retval true - pointer was decremented; a new data value was found + * \retval false - start of available data reached; pointer is unchanged + ***********************************************************************/ + bool decrementAddress() + { + bool result = false; + + /* If we have data */ + if (ihContent.size() != 0) + { + /* If we're not already pointing to the start */ + if (ihIterator != ihContent.begin()) + { + /* Decrement iterator */ + ihIterator--; + + /* Everything is ok! */ + result = true; + } + } + + /* If incrementation of the iterator was successful, return true */ + return result; + } + + /**********************************************************************/ + /*! \brief Returns the current address being pointed to. + * + * Current address will be returned. + * + * \sa jumpTo() + * + * \retval Current address being pointed to. + ***********************************************************************/ + unsigned long currentAddress() + { + return ihIterator->first; + } + + /**********************************************************************/ + /*! \brief Returns the lowest address currently available. + * + * Returns the first address that appears in the memory if there is data + * present. If not, no value will be returned. + * + * \sa endAddress() + * + * \param address - variable to hold address requested + * + * \retval true - address existed and returned value is valid + * \retval false - address did not exist and returned valid is not + * valid + ***********************************************************************/ + bool startAddress(unsigned long * address) + { + if (ihContent.size() != 0) + { + map::iterator it; + + it = ihContent.begin(); + *address = (*it).first; + return true; + } + + return false; + } + + /**********************************************************************/ + /*! \brief Returns the highest address currently available. + * + * Returns the last address that appears in the memory if there is data + * present. If not, no value will be returned. + * + * \param address - variable to hold address requested + * + * \retval true - address existed and returned value is valid + * \retval false - address did not exist and returned valid is not + * valid + * + * \sa startAddress() + ***********************************************************************/ + bool endAddress(unsigned long * address) + { + if (ihContent.size() != 0) + { + map::reverse_iterator rit; + + rit = ihContent.rbegin(); + *address = (*rit).first; + return true; + } + + return false; + } + + /**********************************************************************/ + /*! \brief Returns the data to which the iterator is currently pointing. + * + * Returns the data to which the internal iterator (pointer) is currently + * pointing. If no data is in memory, this function returns false. + * + * \param data - variable to hold data requested + * + * \retval true - data was available and returned value is valid + * \retval false - data was not available and returned valid is not + * valid + * + * \sa insertData(), overwriteData() + ***********************************************************************/ + bool getData(unsigned char * data) + { + if (!ihContent.empty() && (ihIterator != ihContent.end())) + { + *data = ihIterator->second; + return true; + } + return false; + } + + /**********************************************************************/ + /*! \brief Returns the data from the desired address. + * + * Returns the data for the desired address. If the address has no data + * assigned to it, the function returns false, the pointer to data is not + * written and the class's address pointer remains unchanged. If the + * address has data assigned to it, the pointer to data will be written + * with the data found and the class's address pointer will be moved to + * this new location. + * + * \param data - variable to hold data requested + * \param address - address to be queried for valid data + * + * \retval true - data was available and returned value is valid + * \retval false - data was not available and returned valid is not + * valid + * + * \sa insertData(), overwriteData() + ***********************************************************************/ + bool getData(unsigned char * data, unsigned long address) + { + bool found = false; + map::iterator localIterator; + + if (!ihContent.empty()) + { + localIterator = ihContent.find(address); + + if (localIterator != ihContent.end()) + { + found = true; + ihIterator = localIterator; + *data = ihIterator->second; + } + } + + return found; + } + + /**********************************************************************/ + /*! \brief Inserts desired byte at the current address pointer. + * + * Inserts byte of data at the current address pointer + * + * \param data - data byte to be inserted + * + * \retval true - data insertion was successful + * \retval false - data insertion failed + * + * \sa getAddress(), overwriteData() + ***********************************************************************/ + bool insertData(unsigned char data); + + /**********************************************************************/ + /*! \brief Inserts desired byte at the desired address. + * + * Inserts byte of data at the desired address. + * + * \param data - data byte to be inserted + * \param address - address at which to insert data + * + * \retval true - data insertion was successful + * \retval false - data insertion failed + * + * \sa getAddress(), overwriteData() + ***********************************************************************/ + bool insertData(unsigned char data, unsigned long address); + + /**********************************************************************/ + /*! \brief Forces insertion of desired byte at the current address pointer. + * + * Forces insertion of byte of data at the current address pointer + * + * \param data - data byte to be inserted + * + * \sa getAddress() + ***********************************************************************/ + void overwriteData(unsigned char data); + + /**********************************************************************/ + /*! \brief Forces insertion of desired byte at the desired address. + * + * Forces insertion of byte of data at the desired address. + * + * \param data - data byte to be inserted + * \param address - address at which to insert data + * + * \sa getAddress() + ***********************************************************************/ + void overwriteData(unsigned char data, unsigned long address); + + bool blankFill(unsigned char data); + + bool blankFill(unsigned char * const data, unsigned long sizeOfData); + + void blankFill(unsigned char * const data, unsigned long sizeOfData, + unsigned long endAddress); + + bool blankFillRandom(); + + void blankFillRandom(unsigned long endAddress); + + bool blankFillAddressLowByte(); + + void blankFillAddressLowByte(unsigned long endAddress); + + /**********************************************************************/ + /*! \brief Returns number of unread warning messages. + * + * Number of unread warning messages will be returned. + * + * \sa popNextWarning(), getNoErrors(), popNextError() + ***********************************************************************/ + unsigned long getNoWarnings() + { + return msgWarning.noOfWarnings; + } + + /**********************************************************************/ + /*! \brief Returns number of unread error messages. + * + * Number of unread error messages will be returned. + * + * \sa popNextWarning(), getNoWarnings(), popNextError() + ***********************************************************************/ + unsigned long getNoErrors() + { + return msgError.noOfErrors; + } + + /**********************************************************************/ + /*! \brief Pop next warning message from the list of warnings. + * + * Next warning message is returned from the list of warnings. If there + * are no more warning in the list, the string will be unchanged. + * + * \param warning - variable to store warning string to be returned + * + * \retval true - more warning messages are available + * \retval false - no more warning messages are available + * + * \sa getNoWarnings(), getNoErrors(), popNextError() + ***********************************************************************/ + bool popNextWarning(string& warning) + { + if (msgWarning.noOfWarnings > 0) + { + warning = msgWarning.ihWarnings.front(); + + msgWarning.ihWarnings.pop_front(); + + msgWarning.noOfWarnings = msgWarning.ihWarnings.size(); + + return true; + } + else + { + return false; + } + } + + /**********************************************************************/ + /*! \brief Pop next error message from the list of errors. + * + * Next error message is returned from the list of errors. If there are + * no more errors in the list, no string will be returned unchanged. + * + * \param error - variable to store error string to be returned + * + * \retval true - more error messages are available + * \retval false - no more error messages are available + * + * \sa getNoWarnings(), getNoErrors(), popNextError() + ***********************************************************************/ + bool popNextError(string& error) + { + if (msgError.noOfErrors > 0) + { + error = msgError.ihErrors.front(); + + msgError.ihErrors.pop_front(); + + msgError.noOfErrors = msgError.ihErrors.size(); + + return true; + } + else + { + return false; + } + } + + /**********************************************************************/ + /*! \brief Returns segment start address for the IP and ES registers. + * + * If these values exist, they will be returned. If not, the function + * returns false. + * + * \param ipRegister - variable to store IP register's value + * \param csRegister - variable to store CS register's value + * + * \retval true - IP and CS registers have defined values + * \retval false - IP and CS registers do not contain values + * + * \sa getStartLinearAddress(), setStartSegmentAddress(), + * setStartLinearAddress() + ***********************************************************************/ + bool getStartSegmentAddress(unsigned short * ipRegister, + unsigned short * csRegister) + { + if (startSegmentAddress.exists == true) + { + *ipRegister = startSegmentAddress.ipRegister; + *csRegister = startSegmentAddress.csRegister; + } + + return startSegmentAddress.exists; + } + + /**********************************************************************/ + /*! \brief Returns segment linear address for the EIP register. + * + * If this value exists, they will be returned. If not, the function + * returns false. + * + * \param eipRegister - variable to store EIP register's value + * + * \retval true - EIP register has defined value + * \retval false - EIP register do not contain value + * + * \sa getStartSegmentAddress(), setStartSegmentAddress(), + * setStartLinearAddress() + ***********************************************************************/ + bool getStartLinearAddress(unsigned long * eipRegister) + { + if (startLinearAddress.exists == true) + { + *eipRegister = startLinearAddress.eipRegister; + } + + return startLinearAddress.exists; + } + + /**********************************************************************/ + /*! \brief Sets the segment start address for the IP and CS registers. + * + * Allows user to define or redefine the contents of the IP and CS + * registers + * + * \param ipRegister - desired IP register value + * \param csRegister - desired CS register value + * + * \sa getStartLinearAddress(), getStartSegmentAddress(), + * setStartLinearAddress() + ***********************************************************************/ + void setStartSegmentAddress(unsigned short ipRegister, + unsigned short csRegister) + { + startSegmentAddress.ipRegister = ipRegister; + startSegmentAddress.csRegister = csRegister; + startSegmentAddress.exists = true; + } + + /**********************************************************************/ + /*! \brief Sets the segment start address for the EIP register. + * + * Allows user to define or redefine the contents of the EIP register + * + * \param eipRegister - desired EIP register value + * + * \sa getStartSegmentAddress(), setStartSegmentAddress(), + * getStartLinearAddress() + ***********************************************************************/ + void setStartLinearAddress(unsigned long eipRegister) + { + startLinearAddress.eipRegister = eipRegister; + startLinearAddress.exists = true; + } + + /**********************************************************************/ + /*! \brief Turns on segment addressing mode during encoding. + * + * Uses the Segment Address Record during encoding. + ***********************************************************************/ + void segmentAddressingOn() + { + segmentAddressMode = true; + } + + /**********************************************************************/ + /*! \brief Turns on linear addressing mode during encoding. + * + * Uses the Linear Address Record during encoding. + ***********************************************************************/ + void linearAddressingOn() + { + segmentAddressMode = false; + } + + /**********************************************************************/ + /*! \brief Turns on textual output to cout during decoding. + * + * Per record single line output to cout during decoding of Intel HEX + * files. + ***********************************************************************/ + void verboseOn() + { + verbose = true; + } + + /**********************************************************************/ + /*! \brief Turns off textual output to cout during decoding. + * + * No output to cout during decoding of Intel HEX files. + ***********************************************************************/ + void verboseOff() + { + verbose = false; + } +}; +#endif diff --git a/src/tools/intelhex/license.txt b/src/tools/intelhex/license.txt new file mode 100644 index 00000000..012e1ef1 --- /dev/null +++ b/src/tools/intelhex/license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2012 - Stuart Cording + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE.