rrcc/src/Assembler.cpp
2021-08-03 01:37:14 +02:00

312 lines
11 KiB
C++

/*****************************************************************************
* Copyright (c) 2020, rrcc FM10K-Documentation Contributors
*
* 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.
* * Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* 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 OWNER 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.
*****************************************************************************/
#include "Assembler.h"
#include "instructions/End.h"
#include "instructions/Load.h"
void Assembler::assemble(const std::string& entrypointName, const ImageConfig& config, uint32_t maxImageSize) {
entries.clear();
bytes.clear();
//bytes.resize(maxImageSize - 1, 0x00);
bytes.resize(maxImageSize - 1, (uint8_t) Instruction::Instruction::CommandOp::END);
uint32_t startAddress = config.header.baseAddress;
uint32_t freeOffsetLocation = startAddress;
if (placementMode == FunctionPlacementMode::PlaceAll) {
for (auto &f : linker.getTree()) {
if (f.label == entrypointName) {
startAddress = freeOffsetLocation;
}
freeOffsetLocation = placeFunction(freeOffsetLocation, f);
}
} else {
auto entrypoint = getFunctionByLabel(entrypointName);
if (entrypoint == nullptr) {
throw std::runtime_error("Entrypoint function "+entrypointName+" not found");
}
freeOffsetLocation = placeFunction(freeOffsetLocation, *entrypoint);
}
while (true) {
bool changed = false;
for (auto &fEntry : entries) {
if (fEntry.second.second) {
auto f = getFunctionByLabel(fEntry.first);
for (auto &d : f->declarations) {
for (auto &t : d.tokens) {
if (t.getType() == Token::Type::CodeLabel && t.getTextValue().at(0) != '.') {
if (entries.find(t.getTextValue()) == entries.end()) {
changed = true;
auto fUsed = getFunctionByLabel(t.getTextValue());
if (fUsed == nullptr) {
throw std::runtime_error(
t.getTextValue() + " function not found, in use by " + fEntry.first);
}
freeOffsetLocation = placeFunction(freeOffsetLocation, *fUsed);
}
}
}
}
placeFunction(fEntry.second.first, *f);
}
}
if (!changed) {
break;
}
}
size_t offset = 0;
bytes[offset++] = ((uint8_t) config.header.spiTransferSpeed << 3) | ((uint8_t) config.header.spiTransferMode << 6);
bytes[offset++] = (startAddress >> 16) & 0xFF;
bytes[offset++] = (startAddress >> 8) & 0xFF;
bytes[offset++] = startAddress & 0xFF;
bytes[offset++] = (config.buildVersion >> 24) & 0xFF;
bytes[offset++] = (config.buildVersion >> 16) & 0xFF;
bytes[offset++] = (config.buildVersion >> 8) & 0xFF;
bytes[offset++] = config.buildVersion & 0xFF;
bytes[offset++] = 0x00;
bytes[offset++] = 0x00;
bytes[offset++] = 0x00;
bytes[offset++] = 0x00;
bytes[offset++] = 0x01;
bytes[offset++] = 0x00;
bytes[offset++] = 0x10;
bytes[offset++] = 0x00;
const uint32_t headerLength = offset + 4 + config.headerExtraBytes.size();
bytes[offset++] = headerLength >> 2; // Length in words
bytes[offset++] = (config.properties.baseAddress >> 16) & 0xFF;
bytes[offset++] = (config.properties.baseAddress >> 8) & 0xFF;
bytes[offset++] = config.properties.baseAddress & 0xFF;
for(auto& c : config.headerExtraBytes){
bytes[offset++] = c;
}
std::copy(config.buildSignature.begin(), config.buildSignature.end(), bytes.begin() + offset);
offset = config.properties.baseAddress - 2;
bytes[offset++] = (config.properties.headerPrevShort >> 8) & 0xFF;
bytes[offset++] = config.properties.headerPrevShort & 0xFF;
bytes[offset++] = 1; // fileFormat
bytes[offset++] = 0; // version
bytes[offset++] = 0; // lengthInWords To be written again
bytes[offset++] = 0; // lengthInWords To be written again
for(auto& c : config.properties.headerExtraBytes){
bytes[offset++] = c;
}
uint32_t totalSize = 0;
for(auto& s : config.properties.entries){
std::copy(s.begin(), s.end(), bytes.begin() + offset);
offset += s.size();
totalSize += s.size();
}
totalSize >>= 2; //Length in words
offset = config.properties.baseAddress + 2;
bytes[offset++] = (totalSize >> 8) & 0xFF;
bytes[offset++] = totalSize & 0xFF;
}
uint32_t Assembler::placeFunction(uint32_t base, const Function &function) {
std::unordered_map<std::string, uint32_t> labeledAddress;
std::unordered_map<uint32_t, uint32_t> endAddresses;
auto declarations = function.declarations; //Copy is necessary
uint32_t offset = base;
//Resolve local labels and end addresses
for (auto &d : declarations) {
if (!d.label.empty()) {
labeledAddress[d.label] = offset;
}
bool hasOperator = false;
for (auto &t : d.tokens) {
if (t.getType() == Token::Type::Operator) {
hasOperator = true;
break;
}
}
if (!hasOperator) {
continue;
}
auto instr = Instruction::Instruction::getCommandForDeclaration(d);
if (instr == nullptr) {
throw std::runtime_error("Unknown or invalid declaration on function " + function.label);
}
instr->setAddress(offset);
offset += instr->getByteSize();
endAddresses[instr->getAddress()] = offset;
}
offset = base;
bool needsReLabeling = false;
for (auto &d : declarations) {
for (auto &t : d.tokens) {
if (t.getType() == Token::Type::CodeLabel) {
if (t.getTextValue().at(0) == '.') {
if (labeledAddress.find(t.getTextValue()) != labeledAddress.end()) {
t.valueImmediate += labeledAddress.at(t.getTextValue());
} else {
throw std::runtime_error("Could not find local label " + t.getTextValue() + " on function " + function.label);
}
} else if (entries.find(t.getTextValue()) != entries.end()) {
t.valueImmediate += entries.at(t.getTextValue()).first;
} else {
needsReLabeling = true;
}
}
}
}
std::unordered_map<uint32_t, std::string> knownComments;
for (auto &d : declarations) {
auto instr = Instruction::Instruction::getCommandForDeclaration(d);
if (instr == nullptr) {
throw std::runtime_error("Unknown or invalid declaration on function " + function.label);
}
if (!d.label.empty()) {
labeledAddress[d.label] = offset;
}
instr->setAddress(offset);
auto comment = instr->getComment();
if(!comment.empty()){
d.comment += "\n" + comment;
}
if(!d.comment.empty()){
knownComments[offset] = d.comment;
}
instr->setEndAddress(endAddresses[offset]); //TODO: this might not be needed anymore!
auto data = instr->toBytes();
if (offset + data.size() > bytes.size()) {
throw std::runtime_error("Instruction encoding exceeds image size on function " + function.label);
}
std::copy(data.begin(), data.end(), bytes.begin() + offset);
offset += data.size();
}
if (placeSymbols) {
enum class SymbolKind : uint8_t {
FunctionName = 0,
Comment = 1,
Reserved_2 = 2,
Reserved_3 = 3
};
uint32_t endOffset = offset;
{
auto endInstruction = Instruction::End();
endInstruction.reserved = endOffset; // Tag end of function, start of debug data
auto data = endInstruction.toBytes();
std::copy(data.begin(), data.end(), bytes.begin() + offset);
offset += data.size();
}
std::vector<std::pair<std::pair<SymbolKind, uint32_t>, std::string>> debugEntries;
debugEntries.push_back({{SymbolKind::FunctionName, base}, function.label}); //Tag start of function, and data
for (auto& comment : knownComments) {
debugEntries.push_back({{SymbolKind::Comment, comment.first}, comment.second});
}
for(auto i = 0; i < debugEntries.size(); ++i){
auto& entry = debugEntries[i];
std::vector<uint32_t> debugData;
uint8_t off = 4;
uint32_t v = 0;
for(uint8_t c : entry.second){
--off;
v |= (uint32_t)c << (off * 8);
if(off == 0){
debugData.emplace_back(v);
off = 4;
v = 0;
}
}
if(off != 4){
debugData.emplace_back(v);
}
auto loadInstruction = Instruction::Load({entry.first.second, (uint8_t)entry.first.first}, (i + 1) < debugEntries.size(), debugData);
auto data = loadInstruction.toBytes();
std::copy(data.begin(), data.end(), bytes.begin() + offset);
offset += data.size();
}
}
entries[function.label] = {base, needsReLabeling};
return offset; //Free bytes between functions
}
const Function *Assembler::getFunctionByLabel(const std::string &l) {
for (auto &f : linker.getTree()) {
if (f.label == l) {
return &f;
}
}
return nullptr;
}