From 4071dcc5a816a09870b8f7d0cf1f6197ff5f1c67 Mon Sep 17 00:00:00 2001 From: Tijmen van Nesselrooij Date: Mon, 7 Sep 2020 20:29:19 +0200 Subject: [PATCH] Support compiling to and running from binary files --- src/main.cpp | 2 +- src/wassembler.cpp | 40 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index eea22c6..4cc8306 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -12,7 +12,7 @@ int main(int argc, char ** argv) std::string outputFile("program.bin"); auto cli = ( - clipp::value("input file").set(inputFile), + clipp::value("input file (*.wasm or *.bin)").set(inputFile), ( clipp::required("-e", "--execute").set(execute), clipp::option("-m", "--memory-size") & clipp::value("memory size in bytes (defaults to 4096)", memorySize), diff --git a/src/wassembler.cpp b/src/wassembler.cpp index fc53811..95dce95 100644 --- a/src/wassembler.cpp +++ b/src/wassembler.cpp @@ -184,10 +184,40 @@ void Wassembler::EnableByteTranslationLogging() bool Wassembler::CompileAndRun(std::string const & filePath) { - std::vector lines; std::vector bytes; - if (!CompileFile(filePath, bytes)) + if (filePath.size() > 4 && filePath.compare(filePath.size() - 4, 4, ".bin") == 0) { + std::ifstream inputFile(filePath); + if (!inputFile.is_open()) + { + std::printf("Error: Cannot open file %s for reading", filePath.c_str()); + return false; + } + + std::size_t previousSize = 0; + bytes.resize(100); + while(inputFile.read(reinterpret_cast(&bytes[previousSize]), 100)) + { + previousSize = bytes.size(); + bytes.resize(bytes.size() + 100); + } + + bytes.resize(bytes.size() - (100 - inputFile.gcount())); + } + else if (filePath.size() > 5 && + filePath.compare(filePath.size() - 5, 5, ".wasm") == 0) + { + if (!CompileFile(filePath, bytes)) + { + return false; + } + } + else + { + std::printf( + "Error: unrecognized file extension on input file %s", + filePath.c_str()); + return false; } @@ -221,9 +251,11 @@ bool Wassembler::CompileToFile( std::printf("Error: Cannot open file %s for writing", outputFilePath.c_str()); return false; } - for(std::size_t i = 0; i < bytes.size(); ++i) + + if (!output.write(reinterpret_cast(bytes.data()), bytes.size())) { - output << bytes[i]; + std::printf("Error: An error occurred whilst writing to %s", outputFilePath.c_str()); + return false; } return true;