From 3b8d8f1a392a2cb5cad1d57d08ced693a0d197d8 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Wed, 25 Apr 2018 12:33:31 +0800 Subject: minicargo - Re-run build script if output is missing --- tools/minicargo/build.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'tools') diff --git a/tools/minicargo/build.cpp b/tools/minicargo/build.cpp index c7c07256..392e6a64 100644 --- a/tools/minicargo/build.cpp +++ b/tools/minicargo/build.cpp @@ -803,7 +803,7 @@ bool Builder::build_target(const PackageManifest& manifest, const PackageTarget& auto out_file = output_dir_abs / "build_" + manifest.name().c_str() + ".txt"; auto out_dir = output_dir_abs / "build_" + manifest.name().c_str(); - + bool run_build_script = false; // TODO: Handle a pre-existing script containing `cargo:rerun-if-changed` auto script_exe = this->build_build_script(manifest, is_for_host, &run_build_script); @@ -813,7 +813,8 @@ bool Builder::build_target(const PackageManifest& manifest, const PackageTarget& return ::helpers::path(); } - if( run_build_script ) + // If the script changed, OR the output file doesn't exist + if( run_build_script || Timestamp::for_file(out_file) == Timestamp::infinite_past() ) { auto script_exe_abs = script_exe.to_absolute(); -- cgit v1.2.3 From 144bd3cdcea986f907468074365dfd17893a0f0f Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 12 May 2018 12:52:46 +0800 Subject: Standalone Miri - Linux build support --- tools/standalone_miri/Makefile | 43 ++++++++++++++++++++++++++++++ tools/standalone_miri/debug.hpp | 4 +-- tools/standalone_miri/lex.cpp | 4 +++ tools/standalone_miri/main.cpp | 49 ++++++++++++++++++++++++++++++++++- tools/standalone_miri/mir.cpp | 1 + tools/standalone_miri/module_tree.cpp | 3 ++- tools/standalone_miri/value.hpp | 1 + 7 files changed, 101 insertions(+), 4 deletions(-) create mode 100644 tools/standalone_miri/Makefile (limited to 'tools') diff --git a/tools/standalone_miri/Makefile b/tools/standalone_miri/Makefile new file mode 100644 index 00000000..94c89452 --- /dev/null +++ b/tools/standalone_miri/Makefile @@ -0,0 +1,43 @@ +# +# Standalone MIR Interpreter +# +ifeq ($(OS),Windows_NT) + EXESUF ?= .exe +endif +EXESUF ?= + +V ?= @ + +OBJDIR := .obj/ + +BIN := ../bin/standalone_miri$(EXESUF) +OBJS := main.o debug.o mir.o lex.o value.o module_tree.o hir_sim.o + +LINKFLAGS := -g -lpthread +CXXFLAGS := -Wall -std=c++14 -g -O2 +CXXFLAGS += -I ../common -I ../../src/include -I . + +OBJS := $(OBJS:%=$(OBJDIR)%) + +.PHONY: all clean + +all: $(BIN) + +clean: + rm $(BIN) $(OBJS) + +$(BIN): $(OBJS) ../bin/common_lib.a + @mkdir -p $(dir $@) + @echo [CXX] -o $@ + $V$(CXX) -o $@ $(OBJS) ../bin/common_lib.a $(LINKFLAGS) + +$(OBJDIR)%.o: %.cpp + @mkdir -p $(dir $@) + @echo [CXX] $< + $V$(CXX) -o $@ -c $< $(CXXFLAGS) -MMD -MP -MF $@.dep + +../bin/common_lib.a: + make -C ../common + +-include $(OBJS:%.o=%.o.dep) + diff --git a/tools/standalone_miri/debug.hpp b/tools/standalone_miri/debug.hpp index 5afad96e..f7d32fe5 100644 --- a/tools/standalone_miri/debug.hpp +++ b/tools/standalone_miri/debug.hpp @@ -75,14 +75,14 @@ FunctionTrace FunctionTrace_d(const char* fname, const char* file, unsigned struct DebugExceptionTodo: public ::std::exception { - const char* what() const { + const char* what() const noexcept override { return "TODO hit"; } }; struct DebugExceptionError: public ::std::exception { - const char* what() const { + const char* what() const noexcept override { return "error"; } }; diff --git a/tools/standalone_miri/lex.cpp b/tools/standalone_miri/lex.cpp index 48a9e0cd..7cfe1a78 100644 --- a/tools/standalone_miri/lex.cpp +++ b/tools/standalone_miri/lex.cpp @@ -390,6 +390,10 @@ void Lexer::advance() { m_cur = Token { TokenClass::Symbol, "<<" }; } + else if( ch == '=' ) + { + m_cur = Token { TokenClass::Symbol, "<=" }; + } else { m_if.unget(); diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index a75e753f..384bc79e 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -353,6 +353,21 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar ret.write_i32(0, 120); // ERROR_CALL_NOT_IMPLEMENTED return ret; } + + // - No guard page needed + if( path == ::HIR::SimplePath { "std", {"sys", "imp", "thread", "guard", "init" } } ) + { + ret = Value::with_size(16, false); + ret.write_u64(0, 0); + ret.write_u64(8, 0); + return ret; + } + + // - No stack overflow handling needed + if( path == ::HIR::SimplePath { "std", { "sys", "imp", "stack_overflow", "imp", "init" } } ) + { + return ret; + } } if( fcn.external.link_name != "" ) @@ -1162,6 +1177,9 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar case RawType::USize: new_val.write_usize( 0, Ops::do_bitwise(v_l.read_usize(0), v_r.read_usize(0), re.op) ); break; + case RawType::I32: + new_val.write_i32( 0, static_cast(Ops::do_bitwise(v_l.read_i32(0), v_r.read_i32(0), re.op)) ); + break; default: LOG_TODO("BinOp bitwise - " << se.src << " w/ " << ty_l); } @@ -1497,7 +1515,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar assert(v.read_usize(v.m_offset) == 0); auto& alloc_ptr = v.m_alloc ? v.m_alloc : v.m_value->allocation; LOG_ASSERT(alloc_ptr, "Calling value that can't be a pointer (no allocation)"); - auto& fcn_alloc_ptr = alloc_ptr.alloc().get_relocation(v.m_offset); + const auto& fcn_alloc_ptr = alloc_ptr.alloc().get_relocation(v.m_offset); LOG_ASSERT(fcn_alloc_ptr, "Calling value with no relocation"); LOG_ASSERT(fcn_alloc_ptr.get_ty() == AllocationPtr::Ty::Function, "Calling value that isn't a function pointer"); fcn_p = &fcn_alloc_ptr.fcn(); @@ -1516,6 +1534,11 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar throw ""; } + +extern "C" { + long sysconf(int); +} + Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& abi, ::std::vector args) { if( link_name == "__rust_allocate" ) @@ -1631,6 +1654,25 @@ Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& ab return rv; } } +#else + // std C + else if( link_name == "signal" ) + { + LOG_DEBUG("Call `signal` - Ignoring and returning SIG_IGN"); + auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, 1); + return rv; + } + // POSIX + else if( link_name == "sysconf" ) + { + auto name = args.at(0).read_i32(0); + LOG_DEBUG("FFI sysconf(" << name << ")"); + long val = sysconf(name); + auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, val); + return rv; + } #endif // Allocators! else @@ -1728,6 +1770,11 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, const ::std::string& name, cons { rv = Value(ty_params.tys.at(0)); } + else if( name == "init" ) + { + rv = Value(ty_params.tys.at(0)); + rv.mark_bytes_valid(0, rv.size()); + } // - Unsized stuff else if( name == "size_of_val" ) { diff --git a/tools/standalone_miri/mir.cpp b/tools/standalone_miri/mir.cpp index 4593fb44..a0601823 100644 --- a/tools/standalone_miri/mir.cpp +++ b/tools/standalone_miri/mir.cpp @@ -7,6 +7,7 @@ */ #include "../../src/mir/mir.hpp" #include "hir_sim.hpp" +#include namespace std { template diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index 2513140a..d62695d1 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -5,6 +5,7 @@ #include "lex.hpp" #include "value.hpp" #include +#include // std::find #include "debug.hpp" ModuleTree::ModuleTree() @@ -1328,4 +1329,4 @@ Value* ModuleTree::get_static_opt(const ::HIR::Path& p) return nullptr; } return &it->second; -} \ No newline at end of file +} diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index 8b103210..fb5cc5ae 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -6,6 +6,7 @@ #include #include #include +#include // memcpy #include namespace HIR { -- cgit v1.2.3 From f2ba1740cf1570bc06ddf5472a7319fdbb5ff827 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 12 May 2018 13:55:04 +0800 Subject: Standalone Miri - More implementation work --- tools/standalone_miri/Makefile | 1 + tools/standalone_miri/main.cpp | 51 ++++++++++++++++++++++++++++++++++-------- 2 files changed, 43 insertions(+), 9 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/Makefile b/tools/standalone_miri/Makefile index 94c89452..95e99c75 100644 --- a/tools/standalone_miri/Makefile +++ b/tools/standalone_miri/Makefile @@ -16,6 +16,7 @@ OBJS := main.o debug.o mir.o lex.o value.o module_tree.o hir_sim.o LINKFLAGS := -g -lpthread CXXFLAGS := -Wall -std=c++14 -g -O2 CXXFLAGS += -I ../common -I ../../src/include -I . +CXXFLAGS += -Wno-misleading-indentation # Gets REALLY confused by the TU_ARM macro OBJS := $(OBJS:%=$(OBJDIR)%) diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 384bc79e..86a213dd 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -1266,10 +1266,16 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar } } break; TU_ARM(se.src, DstMeta, re) { - LOG_TODO(stmt); + auto ptr = state.get_value_ref(re.val); + + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = ptr.read_value(POINTER_SIZE, dst_ty.get_size()); } break; TU_ARM(se.src, DstPtr, re) { - LOG_TODO(stmt); + auto ptr = state.get_value_ref(re.val); + + new_val = ptr.read_value(0, POINTER_SIZE); } break; TU_ARM(se.src, MakeDst, re) { // - Get target type, just for some assertions @@ -1655,6 +1661,17 @@ Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& ab } } #else + // POSIX + else if( link_name == "sysconf" ) + { + auto name = args.at(0).read_i32(0); + LOG_DEBUG("FFI sysconf(" << name << ")"); + long val = sysconf(name); + auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, val); + return rv; + } +#endif // std C else if( link_name == "signal" ) { @@ -1663,17 +1680,33 @@ Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& ab rv.write_usize(0, 1); return rv; } - // POSIX - else if( link_name == "sysconf" ) + // - `void *memchr(const void *s, int c, size_t n);` + else if( link_name == "memchr" ) { - auto name = args.at(0).read_i32(0); - LOG_DEBUG("FFI sysconf(" << name << ")"); - long val = sysconf(name); + LOG_ASSERT(args.at(0).allocation.is_alloc(), ""); + //size_t ptr_space; + //void* ptr = args.at(0).read_pointer(0, ptr_space); + auto ptr_alloc = args.at(0).allocation.alloc().get_relocation(0); + void* ptr = ptr_alloc.alloc().data_ptr() + args.at(0).read_usize(0); + auto c = args.at(1).read_i32(0); + auto n = args.at(2).read_usize(0); + // TODO: Check range of `n` + + void* ret = memchr(ptr, c, n); + auto rv = Value(::HIR::TypeRef(RawType::USize)); - rv.write_usize(0, val); + rv.create_allocation(); + if( ret ) + { + rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast(ret) - static_cast(ptr) )); + rv.allocation.alloc().relocations.push_back({ 0, ptr_alloc }); + } + else + { + rv.write_usize(0, 0); + } return rv; } -#endif // Allocators! else { -- cgit v1.2.3 From d667b43bd5971f63d396d2a1a587743c3cfceb68 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 12 May 2018 15:03:37 +0800 Subject: Standalone MIRI - De-duplicate some value code --- tools/standalone_miri/value.cpp | 82 +++++++++++++++++++------ tools/standalone_miri/value.hpp | 132 +++++++++++++++++++++------------------- 2 files changed, 133 insertions(+), 81 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index beff8a38..af462e40 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -150,6 +150,68 @@ size_t AllocationPtr::get_size() const return os; } +uint64_t ValueCommon::read_usize(size_t ofs) const +{ + uint64_t v = 0; + this->read_bytes(ofs, &v, POINTER_SIZE); + return v; +} +void ValueCommon::write_usize(size_t ofs, uint64_t v) +{ + this->write_bytes(ofs, &v, POINTER_SIZE); +} +void* ValueCommon::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& out_size, bool& out_is_mut) const +{ + auto ofs = read_usize(rd_ofs); + auto reloc = get_relocation(rd_ofs); + if( !reloc ) + { + if( ofs != 0 ) { + LOG_FATAL("Read a non-zero offset with no relocation"); + } + out_is_mut = false; + out_size = 0; + return nullptr; + } + else + { + switch(reloc.get_ty()) + { + case AllocationPtr::Ty::Allocation: { + auto& a = reloc.alloc(); + if( ofs > a.size() ) + LOG_FATAL("Out-of-bounds pointer"); + if( ofs + req_valid > a.size() ) + LOG_FATAL("Out-of-bounds pointer (" << ofs << " + " << req_valid << " > " << a.size()); + a.check_bytes_valid( ofs, req_valid ); + out_size = a.size() - ofs; + out_is_mut = true; + return a.data_ptr() + ofs; + } + case AllocationPtr::Ty::StdString: { + const auto& s = reloc.str(); + if( ofs > s.size() ) + LOG_FATAL("Out-of-bounds pointer"); + if( ofs + req_valid > s.size() ) + LOG_FATAL("Out-of-bounds pointer (" << ofs << " + " << req_valid << " > " << s.size()); + out_size = s.size() - ofs; + out_is_mut = false; + return const_cast( static_cast(s.data() + ofs) ); + } + case AllocationPtr::Ty::Function: + LOG_FATAL("read_pointer w/ function"); + case AllocationPtr::Ty::FfiPointer: + if( req_valid ) + LOG_FATAL("Can't request valid data from a FFI pointer"); + // TODO: Have an idea of mutability and available size from FFI + out_size = 0; + out_is_mut = false; + return reloc.ffi().ptr_value /* + ofs */; + } + throw ""; + } +} + void Allocation::resize(size_t new_size) { @@ -371,10 +433,6 @@ void Allocation::write_bytes(size_t ofs, const void* src, size_t count) ::std::memcpy(this->data_ptr() + ofs, src, count); mark_bytes_valid(ofs, count); } -void Allocation::write_usize(size_t ofs, uint64_t v) -{ - this->write_bytes(ofs, &v, POINTER_SIZE); -} ::std::ostream& operator<<(::std::ostream& os, const Allocation& x) { auto flags = os.flags(); @@ -651,10 +709,6 @@ void Value::write_value(size_t ofs, Value v) } } } -void Value::write_usize(size_t ofs, uint64_t v) -{ - this->write_bytes(ofs, &v, POINTER_SIZE); -} ::std::ostream& operator<<(::std::ostream& os, const Value& v) { @@ -775,15 +829,3 @@ uint64_t ValueRef::read_usize(size_t ofs) const this->read_bytes(ofs, &v, POINTER_SIZE); return v; } -uint64_t Value::read_usize(size_t ofs) const -{ - uint64_t v = 0; - this->read_bytes(ofs, &v, POINTER_SIZE); - return v; -} -uint64_t Allocation::read_usize(size_t ofs) const -{ - uint64_t v = 0; - this->read_bytes(ofs, &v, POINTER_SIZE); - return v; -} \ No newline at end of file diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index fb5cc5ae..95f8b508 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -110,7 +110,60 @@ struct Relocation size_t slot_ofs; AllocationPtr backing_alloc; }; -class Allocation + +struct ValueCommon +{ + virtual AllocationPtr get_relocation(size_t ofs) const = 0; + virtual void read_bytes(size_t ofs, void* dst, size_t count) const = 0; + virtual void write_bytes(size_t ofs, const void* src, size_t count) = 0; + + void write_u8 (size_t ofs, uint8_t v) { write_bytes(ofs, &v, 1); } + void write_u16(size_t ofs, uint16_t v) { write_bytes(ofs, &v, 2); } + void write_u32(size_t ofs, uint32_t v) { write_bytes(ofs, &v, 4); } + void write_u64(size_t ofs, uint64_t v) { write_bytes(ofs, &v, 8); } + void write_i8 (size_t ofs, int8_t v) { write_u8 (ofs, static_cast(v)); } + void write_i16(size_t ofs, int16_t v) { write_u16(ofs, static_cast(v)); } + void write_i32(size_t ofs, int32_t v) { write_u32(ofs, static_cast(v)); } + void write_i64(size_t ofs, int64_t v) { write_u64(ofs, static_cast(v)); } + void write_f32(size_t ofs, float v) { write_bytes(ofs, &v, 4); } + void write_f64(size_t ofs, double v) { write_bytes(ofs, &v, 8); } + void write_usize(size_t ofs, uint64_t v); + void write_isize(size_t ofs, int64_t v) { write_usize(ofs, static_cast(v)); } + + uint8_t read_u8(size_t ofs) const { uint8_t rv; read_bytes(ofs, &rv, 1); return rv; } + uint16_t read_u16(size_t ofs) const { uint16_t rv; read_bytes(ofs, &rv, 2); return rv; } + uint32_t read_u32(size_t ofs) const { uint32_t rv; read_bytes(ofs, &rv, 4); return rv; } + uint64_t read_u64(size_t ofs) const { uint64_t rv; read_bytes(ofs, &rv, 8); return rv; } + int8_t read_i8(size_t ofs) const { return static_cast(read_u8(ofs)); } + int16_t read_i16(size_t ofs) const { return static_cast(read_u16(ofs)); } + int32_t read_i32(size_t ofs) const { return static_cast(read_u32(ofs)); } + int64_t read_i64(size_t ofs) const { return static_cast(read_u64(ofs)); } + float read_f32(size_t ofs) const { float rv; read_bytes(ofs, &rv, 4); return rv; } + double read_f64(size_t ofs) const { double rv; read_bytes(ofs, &rv, 8); return rv; } + uint64_t read_usize(size_t ofs) const; + int64_t read_isize(size_t ofs) const { return static_cast(read_usize(ofs)); } + + /// Read a pointer from the value, requiring at least `req_valid` valid bytes, saves avaliable space in `size` + void* read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& size, bool& is_mut) const; + /// Read a pointer, requiring `req_len` valid bytes + const void* read_pointer_const(size_t rd_ofs, size_t req_len) const { + size_t tmp; + bool is_mut; + return read_pointer_unsafe(rd_ofs, req_len, tmp, is_mut); + } + /// Read a pointer, not requiring that the target be initialised + void* read_pointer_uninit(size_t rd_ofs, size_t& out_size) { + bool is_mut; + void* rv = read_pointer_unsafe(rd_ofs, 0, out_size, is_mut); + if(!is_mut) + throw ""; + //LOG_FATAL("Attempting to get an uninit pointer to immutable data"); + return rv; + } +}; + +class Allocation: + public ValueCommon { friend class AllocationPtr; size_t refcount; @@ -126,7 +179,7 @@ public: ::std::vector mask; ::std::vector relocations; - AllocationPtr get_relocation(size_t ofs) const { + AllocationPtr get_relocation(size_t ofs) const override { for(const auto& r : relocations) { if(r.slot_ofs == ofs) return r.backing_alloc; @@ -144,41 +197,15 @@ public: void mark_bytes_valid(size_t ofs, size_t size); Value read_value(size_t ofs, size_t size) const; - void read_bytes(size_t ofs, void* dst, size_t count) const; + void read_bytes(size_t ofs, void* dst, size_t count) const override; void write_value(size_t ofs, Value v); - void write_bytes(size_t ofs, const void* src, size_t count); - - // TODO: Make this block common - void write_u8 (size_t ofs, uint8_t v) { write_bytes(ofs, &v, 1); } - void write_u16(size_t ofs, uint16_t v) { write_bytes(ofs, &v, 2); } - void write_u32(size_t ofs, uint32_t v) { write_bytes(ofs, &v, 4); } - void write_u64(size_t ofs, uint64_t v) { write_bytes(ofs, &v, 8); } - void write_i8 (size_t ofs, int8_t v) { write_u8 (ofs, static_cast(v)); } - void write_i16(size_t ofs, int16_t v) { write_u16(ofs, static_cast(v)); } - void write_i32(size_t ofs, int32_t v) { write_u32(ofs, static_cast(v)); } - void write_i64(size_t ofs, int64_t v) { write_u64(ofs, static_cast(v)); } - void write_f32(size_t ofs, float v) { write_bytes(ofs, &v, 4); } - void write_f64(size_t ofs, double v) { write_bytes(ofs, &v, 8); } - void write_usize(size_t ofs, uint64_t v); - void write_isize(size_t ofs, int64_t v) { write_usize(ofs, static_cast(v)); } - - uint8_t read_u8(size_t ofs) const { uint8_t rv; read_bytes(ofs, &rv, 1); return rv; } - uint16_t read_u16(size_t ofs) const { uint16_t rv; read_bytes(ofs, &rv, 2); return rv; } - uint32_t read_u32(size_t ofs) const { uint32_t rv; read_bytes(ofs, &rv, 4); return rv; } - uint64_t read_u64(size_t ofs) const { uint64_t rv; read_bytes(ofs, &rv, 8); return rv; } - int8_t read_i8(size_t ofs) const { return static_cast(read_u8(ofs)); } - int16_t read_i16(size_t ofs) const { return static_cast(read_u16(ofs)); } - int32_t read_i32(size_t ofs) const { return static_cast(read_u32(ofs)); } - int64_t read_i64(size_t ofs) const { return static_cast(read_u64(ofs)); } - float read_f32(size_t ofs) const { float rv; read_bytes(ofs, &rv, 4); return rv; } - double read_f64(size_t ofs) const { double rv; read_bytes(ofs, &rv, 8); return rv; } - uint64_t read_usize(size_t ofs) const; - int64_t read_isize(size_t ofs) const { return static_cast(read_usize(ofs)); } + void write_bytes(size_t ofs, const void* src, size_t count) override; }; extern ::std::ostream& operator<<(::std::ostream& os, const Allocation& x); -struct Value +struct Value: + public ValueCommon { // If NULL, data is direct AllocationPtr allocation; @@ -197,46 +224,27 @@ struct Value void create_allocation(); size_t size() const { return allocation ? allocation.alloc().size() : direct_data.size; } + AllocationPtr get_relocation(size_t ofs) const override { + if( this->allocation && this->allocation.is_alloc() ) + return this->allocation.alloc().get_relocation(ofs); + else + return AllocationPtr(); + } + void check_bytes_valid(size_t ofs, size_t size) const; void mark_bytes_valid(size_t ofs, size_t size); Value read_value(size_t ofs, size_t size) const; - void read_bytes(size_t ofs, void* dst, size_t count) const; + void read_bytes(size_t ofs, void* dst, size_t count) const override; void write_value(size_t ofs, Value v); - void write_bytes(size_t ofs, const void* src, size_t count); - - // TODO: Make this block common - void write_u8 (size_t ofs, uint8_t v) { write_bytes(ofs, &v, 1); } - void write_u16(size_t ofs, uint16_t v) { write_bytes(ofs, &v, 2); } - void write_u32(size_t ofs, uint32_t v) { write_bytes(ofs, &v, 4); } - void write_u64(size_t ofs, uint64_t v) { write_bytes(ofs, &v, 8); } - void write_i8 (size_t ofs, int8_t v) { write_u8 (ofs, static_cast(v)); } - void write_i16(size_t ofs, int16_t v) { write_u16(ofs, static_cast(v)); } - void write_i32(size_t ofs, int32_t v) { write_u32(ofs, static_cast(v)); } - void write_i64(size_t ofs, int64_t v) { write_u64(ofs, static_cast(v)); } - void write_f32(size_t ofs, float v) { write_bytes(ofs, &v, 4); } - void write_f64(size_t ofs, double v) { write_bytes(ofs, &v, 8); } - void write_usize(size_t ofs, uint64_t v); - void write_isize(size_t ofs, int64_t v) { write_usize(ofs, static_cast(v)); } - - uint8_t read_u8(size_t ofs) const { uint8_t rv; read_bytes(ofs, &rv, 1); return rv; } - uint16_t read_u16(size_t ofs) const { uint16_t rv; read_bytes(ofs, &rv, 2); return rv; } - uint32_t read_u32(size_t ofs) const { uint32_t rv; read_bytes(ofs, &rv, 4); return rv; } - uint64_t read_u64(size_t ofs) const { uint64_t rv; read_bytes(ofs, &rv, 8); return rv; } - int8_t read_i8(size_t ofs) const { return static_cast(read_u8(ofs)); } - int16_t read_i16(size_t ofs) const { return static_cast(read_u16(ofs)); } - int32_t read_i32(size_t ofs) const { return static_cast(read_u32(ofs)); } - int64_t read_i64(size_t ofs) const { return static_cast(read_u64(ofs)); } - float read_f32(size_t ofs) const { float rv; read_bytes(ofs, &rv, 4); return rv; } - double read_f64(size_t ofs) const { double rv; read_bytes(ofs, &rv, 8); return rv; } - uint64_t read_usize(size_t ofs) const; - int64_t read_isize(size_t ofs) const { return static_cast(read_usize(ofs)); } + void write_bytes(size_t ofs, const void* src, size_t count) override; }; extern ::std::ostream& operator<<(::std::ostream& os, const Value& v); // A read-only reference to a value (to write, you have to go through it) struct ValueRef + //:public ValueCommon { // Either an AllocationPtr, or a Value pointer AllocationPtr m_alloc; @@ -352,6 +360,8 @@ struct ValueRef m_value->read_bytes(m_offset + ofs, dst, size); } } + + // TODO: Figure out how to make this use `ValueCommon` when it can't write. uint8_t read_u8(size_t ofs) const { uint8_t rv; read_bytes(ofs, &rv, 1); return rv; } uint16_t read_u16(size_t ofs) const { uint16_t rv; read_bytes(ofs, &rv, 2); return rv; } uint32_t read_u32(size_t ofs) const { uint32_t rv; read_bytes(ofs, &rv, 4); return rv; } -- cgit v1.2.3 From 835519441441dcff3bb39e9a82f433a37c61d6ef Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 12 May 2018 17:54:27 +0800 Subject: Standalone MIRI - Get type for statics, add some pthread_* FFI stubs --- tools/standalone_miri/main.cpp | 43 +++++++++++++++++++++++++++-------- tools/standalone_miri/module_tree.cpp | 12 ++++++---- tools/standalone_miri/module_tree.hpp | 17 ++++++++------ 3 files changed, 50 insertions(+), 22 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 86a213dd..e3c7ab50 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -433,8 +433,9 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar return ValueRef(args.at(e.idx), 0, args.at(e.idx).size()); } break; TU_ARM(lv, Static, e) { - // TODO: Type! - return ValueRef(modtree.get_static(e), 0, modtree.get_static(e).size()); + /*const*/ auto& s = modtree.get_static(e); + ty = s.ty; + return ValueRef(s.val, 0, s.val.size()); } break; TU_ARM(lv, Index, e) { auto idx = get_value_ref(*e.idx).read_usize(0); @@ -678,7 +679,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar for(const auto& stmt : bb.statements) { - LOG_DEBUG("BB" << bb_idx << "/" << (&stmt - bb.statements.data()) << ": " << stmt); + LOG_DEBUG("=== BB" << bb_idx << "/" << (&stmt - bb.statements.data()) << ": " << stmt); switch(stmt.tag()) { case ::MIR::Statement::TAGDEAD: throw ""; @@ -1424,7 +1425,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar } } - LOG_DEBUG("BB" << bb_idx << "/TERM: " << bb.terminator); + LOG_DEBUG("=== BB" << bb_idx << "/TERM: " << bb.terminator); switch(bb.terminator.tag()) { case ::MIR::Terminator::TAGDEAD: throw ""; @@ -1522,7 +1523,8 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar auto& alloc_ptr = v.m_alloc ? v.m_alloc : v.m_value->allocation; LOG_ASSERT(alloc_ptr, "Calling value that can't be a pointer (no allocation)"); const auto& fcn_alloc_ptr = alloc_ptr.alloc().get_relocation(v.m_offset); - LOG_ASSERT(fcn_alloc_ptr, "Calling value with no relocation"); + if( !fcn_alloc_ptr ) + LOG_FATAL("Calling value with no relocation - " << v); LOG_ASSERT(fcn_alloc_ptr.get_ty() == AllocationPtr::Ty::Function, "Calling value that isn't a function pointer"); fcn_p = &fcn_alloc_ptr.fcn(); } @@ -1671,6 +1673,30 @@ Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& ab rv.write_usize(0, val); return rv; } + else if( link_name == "pthread_mutex_init" || link_name == "pthread_mutex_lock" || link_name == "pthread_mutex_unlock" ) + { + auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + return rv; + } + else if( link_name == "pthread_mutexattr_init" || link_name == "pthread_mutexattr_settype" || link_name == "pthread_mutexattr_destroy" ) + { + auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + return rv; + } + else if( link_name == "pthread_condattr_init" || link_name == "pthread_condattr_destroy" || link_name == "pthread_condattr_setclock" ) + { + auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + return rv; + } + else if( link_name == "pthread_cond_init" || link_name == "pthread_cond_destroy" ) + { + auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + return rv; + } #endif // std C else if( link_name == "signal" ) @@ -1684,15 +1710,12 @@ Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& ab else if( link_name == "memchr" ) { LOG_ASSERT(args.at(0).allocation.is_alloc(), ""); - //size_t ptr_space; - //void* ptr = args.at(0).read_pointer(0, ptr_space); auto ptr_alloc = args.at(0).allocation.alloc().get_relocation(0); - void* ptr = ptr_alloc.alloc().data_ptr() + args.at(0).read_usize(0); auto c = args.at(1).read_i32(0); auto n = args.at(2).read_usize(0); - // TODO: Check range of `n` + const void* ptr = args.at(0).read_pointer_const(0, n); - void* ret = memchr(ptr, c, n); + const void* ret = memchr(ptr, c, n); auto rv = Value(::HIR::TypeRef(RawType::USize)); rv.create_allocation(); diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index d62695d1..d6c7dcec 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -154,10 +154,12 @@ bool Parser::parse_one() } lex.check_consume(';'); - Value val = Value(ty); - val.write_bytes(0, data.data(), data.size()); + Static s; + s.val = Value(ty); + s.val.write_bytes(0, data.data(), data.size()); + s.ty = ty; - tree.statics.insert(::std::make_pair( ::std::move(p), ::std::move(val) )); + tree.statics.insert(::std::make_pair( ::std::move(p), ::std::move(s) )); } else if( lex.consume_if("type") ) { @@ -1311,7 +1313,7 @@ const Function* ModuleTree::get_function_opt(const ::HIR::Path& p) const } return &it->second; } -Value& ModuleTree::get_static(const ::HIR::Path& p) +Static& ModuleTree::get_static(const ::HIR::Path& p) { auto it = statics.find(p); if(it == statics.end()) @@ -1321,7 +1323,7 @@ Value& ModuleTree::get_static(const ::HIR::Path& p) } return it->second; } -Value* ModuleTree::get_static_opt(const ::HIR::Path& p) +Static* ModuleTree::get_static_opt(const ::HIR::Path& p) { auto it = statics.find(p); if(it == statics.end()) diff --git a/tools/standalone_miri/module_tree.hpp b/tools/standalone_miri/module_tree.hpp index ca24b06a..5479d9ef 100644 --- a/tools/standalone_miri/module_tree.hpp +++ b/tools/standalone_miri/module_tree.hpp @@ -9,15 +9,14 @@ #include "../../src/mir/mir.hpp" #include "hir_sim.hpp" - -struct Value; +#include "value.hpp" struct Function { ::HIR::Path my_path; ::std::vector<::HIR::TypeRef> args; ::HIR::TypeRef ret_ty; - + // If `link_name` is non-empty, then the function is an external struct { ::std::string link_name; @@ -25,6 +24,11 @@ struct Function } external; ::MIR::Function m_mir; }; +struct Static +{ + ::HIR::TypeRef ty; + Value val; +}; /// Container for loaded code and structures class ModuleTree @@ -34,8 +38,7 @@ class ModuleTree ::std::set<::std::string> loaded_files; ::std::map<::HIR::Path, Function> functions; - ::std::map<::HIR::Path, Value> statics; - // TODO: statics + ::std::map<::HIR::Path, Static> statics; // Hack: Tuples are stored as `::""::` ::std::map<::HIR::GenericPath, ::std::unique_ptr> data_types; @@ -47,8 +50,8 @@ public: ::HIR::SimplePath find_lang_item(const char* name) const; const Function& get_function(const ::HIR::Path& p) const; const Function* get_function_opt(const ::HIR::Path& p) const; - Value& get_static(const ::HIR::Path& p); - Value* get_static_opt(const ::HIR::Path& p); + Static& get_static(const ::HIR::Path& p); + Static* get_static_opt(const ::HIR::Path& p); const DataType& get_composite(const ::HIR::GenericPath& p) const { return *data_types.at(p); -- cgit v1.2.3 From 11574b8b30b87fdc130f4e276839eda52860582b Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 12 May 2018 18:21:36 +0800 Subject: Standalone MIRI - Better handling of statics --- tools/standalone_miri/main.cpp | 23 ++++++++++++++++++++--- tools/standalone_miri/module_tree.cpp | 19 ++++++++++++------- 2 files changed, 32 insertions(+), 10 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index e3c7ab50..c9cc7f38 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -627,9 +627,18 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar TU_ARM(c, ItemAddr, ce) { // Create a value with a special backing allocation of zero size that references the specified item. if( const auto* fn = modtree.get_function_opt(ce) ) { + ty = ::HIR::TypeRef(RawType::Function); return Value::new_fnptr(ce); } - LOG_TODO("Constant::ItemAddr - statics?"); + if( const auto* s = modtree.get_static_opt(ce) ) { + ty = s->ty; + ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); + Value val = Value(ty); + val.write_usize(0, 0); + val.allocation.alloc().relocations.push_back(Relocation { 0, s->val.allocation }); + return val; + } + LOG_TODO("Constant::ItemAddr - " << ce << " - not found"); } break; } throw ""; @@ -1510,6 +1519,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar } else { + AllocationPtr fcn_alloc_ptr; const ::HIR::Path* fcn_p; if( te.fcn.is_Path() ) { fcn_p = &te.fcn.as_Path(); @@ -1517,12 +1527,13 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar else { ::HIR::TypeRef ty; auto v = state.get_value_and_type(te.fcn.as_Value(), ty); + LOG_DEBUG("> Indirect call " << v); // TODO: Assert type // TODO: Assert offset/content. assert(v.read_usize(v.m_offset) == 0); auto& alloc_ptr = v.m_alloc ? v.m_alloc : v.m_value->allocation; LOG_ASSERT(alloc_ptr, "Calling value that can't be a pointer (no allocation)"); - const auto& fcn_alloc_ptr = alloc_ptr.alloc().get_relocation(v.m_offset); + fcn_alloc_ptr = alloc_ptr.alloc().get_relocation(v.m_offset); if( !fcn_alloc_ptr ) LOG_FATAL("Calling value with no relocation - " << v); LOG_ASSERT(fcn_alloc_ptr.get_ty() == AllocationPtr::Ty::Function, "Calling value that isn't a function pointer"); @@ -1697,6 +1708,12 @@ Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& ab rv.write_i32(0, 0); return rv; } + else if( link_name == "pthread_key_create" || link_name == "pthread_key_delete" ) + { + auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + return rv; + } #endif // std C else if( link_name == "signal" ) @@ -1761,7 +1778,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, const ::std::string& name, cons const auto& ty = ty_params.tys.at(0); alloc.alloc().write_value(ofs, ::std::move(data_val)); } - else if( name == "atomic_load" ) + else if( name == "atomic_load" || name == "atomic_load_relaxed" ) { auto& ptr_val = args.at(0); LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_store of a value that isn't a pointer-sized value"); diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index d6c7dcec..f6b681cf 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -121,6 +121,15 @@ bool Parser::parse_one() lex.check_consume('='); lex.check(TokenClass::String); auto data = ::std::move(lex.consume().strval); + + Static s; + s.val = Value(ty); + // - Statics need to always have an allocation (for references) + if( !s.val.allocation ) + s.val.create_allocation(); + s.val.write_bytes(0, data.data(), data.size()); + s.ty = ty; + if( lex.consume_if('{') ) { while( !lex.consume_if('}') ) @@ -135,12 +144,13 @@ bool Parser::parse_one() if( lex.next() == TokenClass::String ) { auto reloc_str = ::std::move(lex.consume().strval); - // TODO: Add relocation + // TODO: Figure out how to create this allocation... + //s.val.allocation.alloc().relocations.push_back({ ofs, AllocationPtr::new_string(reloc_str) }); } else if( lex.next() == "::" ) { auto reloc_path = parse_path(); - // TODO: Add relocation + s.val.allocation.alloc().relocations.push_back({ ofs, AllocationPtr::new_fcn(reloc_path) }); } else { @@ -154,11 +164,6 @@ bool Parser::parse_one() } lex.check_consume(';'); - Static s; - s.val = Value(ty); - s.val.write_bytes(0, data.data(), data.size()); - s.ty = ty; - tree.statics.insert(::std::make_pair( ::std::move(p), ::std::move(s) )); } else if( lex.consume_if("type") ) -- cgit v1.2.3 From d8928895e318b026f106a30f145d6a41be74cb0f Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 12 May 2018 19:05:54 +0800 Subject: Standalone MIRI - Fiddling around --- tools/standalone_miri/main.cpp | 14 +++++++++----- tools/standalone_miri/module_tree.cpp | 3 ++- 2 files changed, 11 insertions(+), 6 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index c9cc7f38..b7f62252 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -378,6 +378,8 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar return ret; } + // TODO: Recursion limit. + TRACE_FUNCTION_R(path, path << " = " << ret); for(size_t i = 0; i < args.size(); i ++) { @@ -809,11 +811,13 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar switch(re.type.inner_type) { case RawType::Unreachable: throw "BUG"; - case RawType::Composite: throw "ERROR"; - case RawType::TraitObject: throw "ERROR"; - case RawType::Function: throw "ERROR"; - case RawType::Str: throw "ERROR"; - case RawType::Unit: throw "ERROR"; + case RawType::Composite: + case RawType::TraitObject: + case RawType::Function: + case RawType::Str: + case RawType::Unit: + LOG_ERROR("Casting to " << re.type << " is invalid"); + throw "ERROR"; case RawType::F32: { float dst_val = 0.0; // Can be an integer, or F64 (pointer is impossible atm) diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index f6b681cf..a75cfa8f 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -147,13 +147,14 @@ bool Parser::parse_one() // TODO: Figure out how to create this allocation... //s.val.allocation.alloc().relocations.push_back({ ofs, AllocationPtr::new_string(reloc_str) }); } - else if( lex.next() == "::" ) + else if( lex.next() == "::" || lex.next() == "<" ) { auto reloc_path = parse_path(); s.val.allocation.alloc().relocations.push_back({ ofs, AllocationPtr::new_fcn(reloc_path) }); } else { + LOG_FATAL(lex << "Unexepcted token " << lex.next() << " in relocation value"); throw "ERROR"; } if( ! lex.consume_if(',') ) { -- cgit v1.2.3 From d14ab6eae9abd88ab4e26d7c7fd2f91d48d1a10f Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 12 May 2018 21:06:49 +0800 Subject: Standalone MIRI - TLS and some other messing about --- src/trans/codegen_mmir.cpp | 2 +- tools/standalone_miri/main.cpp | 144 +++++++++++++++++++++++++++++++++------- tools/standalone_miri/value.cpp | 53 ++++++++++++++- tools/standalone_miri/value.hpp | 86 +++++++++++++++--------- 4 files changed, 228 insertions(+), 57 deletions(-) (limited to 'tools') diff --git a/src/trans/codegen_mmir.cpp b/src/trans/codegen_mmir.cpp index db538842..19574814 100644 --- a/src/trans/codegen_mmir.cpp +++ b/src/trans/codegen_mmir.cpp @@ -157,7 +157,7 @@ namespace { if( is_executable ) { - m_of << "fn ::main#(i32, *const *const i8): i32 {\n"; + m_of << "fn ::main#(isize, *const *const i8): i32 {\n"; auto c_start_path = m_resolve.m_crate.get_lang_item_path_opt("mrustc-start"); if( c_start_path == ::HIR::SimplePath() ) { diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index b7f62252..1b33087a 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -19,9 +19,31 @@ struct ProgramOptions int parse(int argc, const char* argv[]); }; -Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector args); -Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& abi, ::std::vector args); -Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args); +struct ThreadState +{ + static unsigned s_next_tls_key; + unsigned call_stack_depth; + ::std::vector tls_values; + + ThreadState(): + call_stack_depth(0) + { + } + + struct DecOnDrop { + unsigned* p; + ~DecOnDrop() { (*p) --; } + }; + DecOnDrop enter_function() { + this->call_stack_depth ++; + return DecOnDrop { &this->call_stack_depth }; + } +}; +unsigned ThreadState::s_next_tls_key = 1; + +Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, ::std::vector args); +Value MIRI_Invoke_Extern(ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args); +Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args); int main(int argc, const char* argv[]) { @@ -36,20 +58,21 @@ int main(int argc, const char* argv[]) tree.load_file(opts.infile); - auto val_argc = Value( ::HIR::TypeRef{RawType::I32} ); + auto val_argc = Value( ::HIR::TypeRef{RawType::ISize} ); ::HIR::TypeRef argv_ty { RawType::I8 }; argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); auto val_argv = Value(argv_ty); - val_argc.write_bytes(0, "\0\0\0", 4); + val_argc.write_bytes(0, "\0\0\0\0\0\0\0", 8); val_argv.write_bytes(0, "\0\0\0\0\0\0\0", argv_ty.get_size()); try { + ThreadState ts; ::std::vector args; args.push_back(::std::move(val_argc)); args.push_back(::std::move(val_argv)); - auto rv = MIRI_Invoke( tree, tree.find_lang_item("start"), ::std::move(args) ); + auto rv = MIRI_Invoke( tree, ts, tree.find_lang_item("start"), ::std::move(args) ); ::std::cout << rv << ::std::endl; } catch(const DebugExceptionTodo& /*e*/) @@ -291,7 +314,7 @@ struct Ops { namespace { - void drop_value(ModuleTree& modtree, Value ptr, const ::HIR::TypeRef& ty) + void drop_value(ModuleTree& modtree, ThreadState& thread, Value ptr, const ::HIR::TypeRef& ty) { if( ty.wrappers.empty() ) { @@ -301,7 +324,7 @@ namespace { LOG_DEBUG("Drop - " << ty); - MIRI_Invoke(modtree, ty.composite_type->drop_glue, { ptr }); + MIRI_Invoke(modtree, thread, ty.composite_type->drop_glue, { ptr }); } else { @@ -338,7 +361,7 @@ namespace } -Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector args) +Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, ::std::vector args) { Value ret; @@ -373,17 +396,22 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar if( fcn.external.link_name != "" ) { // External function! - ret = MIRI_Invoke_Extern(fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); + ret = MIRI_Invoke_Extern(thread, fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); LOG_DEBUG(path << " = " << ret); return ret; } - // TODO: Recursion limit. + // Recursion limit. + if( thread.call_stack_depth > 40 ) { + LOG_ERROR("Recursion limit exceeded"); + } + auto _ = thread.enter_function(); TRACE_FUNCTION_R(path, path << " = " << ret); for(size_t i = 0; i < args.size(); i ++) { LOG_DEBUG("- Argument(" << i << ") = " << args[i]); + // TODO: Check argument sizes against prototype? } ret = Value(fcn.ret_ty == RawType::Unreachable ? ::HIR::TypeRef() : fcn.ret_ty); @@ -489,7 +517,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar ::HIR::TypeRef ptr_ty; auto val = get_value_and_type(*e.val, ptr_ty); ty = ptr_ty.get_inner(); - LOG_DEBUG("val = " << val); + LOG_DEBUG("val = " << val << ", (inner) ty=" << ty); LOG_ASSERT(val.m_size >= POINTER_SIZE, "Deref of a value that doesn't fit a pointer - " << ty); size_t ofs = val.read_usize(0); @@ -500,7 +528,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar LOG_ASSERT(val_alloc.is_alloc(), "Deref of a value with a non-data allocation"); LOG_TRACE("Deref " << val_alloc.alloc() << " + " << ofs << " to give value of type " << ty); auto alloc = val_alloc.alloc().get_relocation(val.m_offset); - LOG_ASSERT(alloc, "Deref of a value with no relocation"); + // NOTE: No alloc can happen when dereferencing a zero-sized pointer if( alloc.is_alloc() ) { LOG_DEBUG("> " << lv << " alloc=" << alloc.alloc()); @@ -517,15 +545,26 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar meta_val = ::std::make_shared( val.read_value(POINTER_SIZE, meta_size) ); // TODO: Get a more sane size from the metadata - LOG_DEBUG("> Meta " << *meta_val << ", size = " << alloc.get_size() << " - " << ofs); - size = alloc.get_size() - ofs; + if( alloc ) + { + LOG_DEBUG("> Meta " << *meta_val << ", size = " << alloc.get_size() << " - " << ofs); + size = alloc.get_size() - ofs; + } + else + { + size = 0; + } } else { LOG_ASSERT(val.m_size == POINTER_SIZE, "Deref of a value that isn't a pointer-sized value (size=" << val.m_size << ") - " << val << ": " << ptr_ty); size = ty.get_size(); + if( !alloc ) { + LOG_ERROR("Deref of a value with no relocation - " << val); + } } + LOG_DEBUG("alloc=" << alloc << ", ofs=" << ofs << ", size=" << size); auto rv = ValueRef(::std::move(alloc), ofs, size); rv.m_metadata = ::std::move(meta_val); return rv; @@ -709,7 +748,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar ::HIR::TypeRef src_ty; ValueRef src_base_value = state.get_value_and_type(re.val, src_ty); auto alloc = src_base_value.m_alloc; - if( !alloc ) + if( !alloc && src_base_value.m_value ) { if( !src_base_value.m_value->allocation ) { @@ -1422,7 +1461,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar ptr_val.write_usize(0, ofs); ptr_val.allocation.alloc().relocations.push_back(Relocation { 0, ::std::move(alloc) }); - drop_value(modtree, ptr_val, ty); + drop_value(modtree, thread, ptr_val, ty); // TODO: Clear validity on the entire inner value. //alloc.mark_as_freed(); } @@ -1515,11 +1554,12 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar for(const auto& a : te.args) { sub_args.push_back( state.param_to_value(a) ); + LOG_DEBUG("#" << (sub_args.size() - 1) << " " << sub_args.back()); } if( te.fcn.is_Intrinsic() ) { const auto& fe = te.fcn.as_Intrinsic(); - state.write_lvalue(te.ret_val, MIRI_Invoke_Intrinsic(modtree, fe.name, fe.params, ::std::move(sub_args))); + state.write_lvalue(te.ret_val, MIRI_Invoke_Intrinsic(modtree, thread, fe.name, fe.params, ::std::move(sub_args))); } else { @@ -1534,7 +1574,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar LOG_DEBUG("> Indirect call " << v); // TODO: Assert type // TODO: Assert offset/content. - assert(v.read_usize(v.m_offset) == 0); + assert(v.read_usize(0) == 0); auto& alloc_ptr = v.m_alloc ? v.m_alloc : v.m_value->allocation; LOG_ASSERT(alloc_ptr, "Calling value that can't be a pointer (no allocation)"); fcn_alloc_ptr = alloc_ptr.alloc().get_relocation(v.m_offset); @@ -1545,7 +1585,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ::HIR::Path path, ::std::vector ar } LOG_DEBUG("Call " << *fcn_p); - auto v = MIRI_Invoke(modtree, *fcn_p, ::std::move(sub_args)); + auto v = MIRI_Invoke(modtree, thread, *fcn_p, ::std::move(sub_args)); LOG_DEBUG(te.ret_val << " = " << v << " (resume " << path << ")"); state.write_lvalue(te.ret_val, ::std::move(v)); } @@ -1562,7 +1602,7 @@ extern "C" { long sysconf(int); } -Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& abi, ::std::vector args) +Value MIRI_Invoke_Extern(ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args) { if( link_name == "__rust_allocate" ) { @@ -1712,7 +1752,45 @@ Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& ab rv.write_i32(0, 0); return rv; } - else if( link_name == "pthread_key_create" || link_name == "pthread_key_delete" ) + else if( link_name == "pthread_key_create" ) + { + size_t size; + auto key_ref = args.at(0).read_pointer_valref_mut(0, 4); + + auto key = ThreadState::s_next_tls_key ++; + key_ref.m_alloc.alloc().write_u32( key_ref.m_offset, key ); + + auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + return rv; + } + else if( link_name == "pthread_getspecific" ) + { + auto key = args.at(0).read_u32(0); + + // Get a pointer-sized value from storage + uint64_t v = key < thread.tls_values.size() ? thread.tls_values[key] : 0; + + auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, v); + return rv; + } + else if( link_name == "pthread_setspecific" ) + { + auto key = args.at(0).read_u32(0); + auto v = args.at(1).read_u64(0); + + // Get a pointer-sized value from storage + if( key >= thread.tls_values.size() ) { + thread.tls_values.resize(key+1); + } + thread.tls_values[key] = v; + + auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + return rv; + } + else if( link_name == "pthread_key_delete" ) { auto rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); @@ -1758,7 +1836,7 @@ Value MIRI_Invoke_Extern(const ::std::string& link_name, const ::std::string& ab } throw ""; } -Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args) +Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args) { Value rv; TRACE_FUNCTION_R(name, rv); @@ -1798,6 +1876,24 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, const ::std::string& name, cons const auto& ty = ty_params.tys.at(0); rv = alloc.alloc().read_value(ofs, ty.get_size()); } + else if( name == "atomic_cxchg" ) + { + const auto& ty_T = ty_params.tys.at(0); + // TODO: Get a ValueRef to the target location + auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size()); + const auto& old_v = args.at(1); + const auto& new_v = args.at(1); + rv = Value::with_size( ty_T.get_size() + 1, false ); + rv.write_value(0, data_ref.read_value(0, old_v.size())); + if( data_ref.compare(old_v.data_ptr(), old_v.size()) == 0 ) { + data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v ); + rv.write_u8( old_v.size(), 1 ); + } + else { + rv.write_u8( old_v.size(), 0 ); + } + return rv; + } else if( name == "transmute" ) { // Transmute requires the same size, so just copying the value works @@ -1919,7 +2015,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, const ::std::string& name, cons auto ptr = val.read_value(0, POINTER_SIZE);; for(size_t i = 0; i < item_count; i ++) { - drop_value(modtree, ptr, ity); + drop_value(modtree, thread, ptr, ity); ptr.write_usize(0, ptr.read_usize(0) + item_size); } } diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index af462e40..468425e9 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -211,6 +211,20 @@ void* ValueCommon::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& throw ""; } } +ValueRef ValueCommon::read_pointer_valref_mut(size_t rd_ofs, size_t size) +{ + auto ofs = read_usize(rd_ofs); + auto reloc = get_relocation(rd_ofs); + if( !reloc ) + { + LOG_ERROR("Getting ValRef to null pointer (no relocation)"); + } + else + { + // TODO: Validate size + return ValueRef(reloc, ofs, size); + } +} void Allocation::resize(size_t new_size) @@ -231,7 +245,7 @@ void Allocation::check_bytes_valid(size_t ofs, size_t size) const { if( !(this->mask[i/8] & (1 << i%8)) ) { - ::std::cerr << "ERROR: Invalid bytes in value" << ::std::endl; + LOG_ERROR("Invalid bytes in value"); throw "ERROR"; } } @@ -749,7 +763,7 @@ extern ::std::ostream& operator<<(::std::ostream& os, const ValueRef& v) { case AllocationPtr::Ty::Allocation: { const auto& alloc = alloc_ptr.alloc(); - + auto flags = os.flags(); os << ::std::hex; for(size_t i = v.m_offset; i < ::std::min(alloc.size(), v.m_offset + v.m_size); i++) @@ -823,6 +837,41 @@ extern ::std::ostream& operator<<(::std::ostream& os, const ValueRef& v) return os; } +Value ValueRef::read_value(size_t ofs, size_t size) const +{ + if( size == 0 ) + return Value(); + if( !(ofs < m_size && size <= m_size && ofs + size <= m_size) ) { + LOG_ERROR("Read exceeds bounds, " << ofs << " + " << size << " > " << m_size << " - from " << *this); + } + if( m_alloc ) { + switch(m_alloc.get_ty()) + { + case AllocationPtr::Ty::Allocation: + return m_alloc.alloc().read_value(m_offset + ofs, size); + case AllocationPtr::Ty::StdString: { + auto rv = Value::with_size(size, false); + //ASSERT_BUG(ofs <= m_alloc.str().size(), ""); + //ASSERT_BUG(size <= m_alloc.str().size(), ""); + //ASSERT_BUG(ofs+size <= m_alloc.str().size(), ""); + assert(m_offset+ofs <= m_alloc.str().size() && size <= m_alloc.str().size() && m_offset+ofs+size <= m_alloc.str().size()); + rv.write_bytes(0, m_alloc.str().data() + m_offset + ofs, size); + return rv; + } + default: + //ASSERT_BUG(m_alloc.is_alloc(), "read_value on non-data backed Value - " << ); + throw "TODO"; + } + } + else { + return m_value->read_value(m_offset + ofs, size); + } +} +bool ValueRef::compare(const void* other, size_t other_len) const +{ + check_bytes_valid(0, other_len); + return ::std::memcmp(data_ptr(), other, other_len) == 0; +} uint64_t ValueRef::read_usize(size_t ofs) const { uint64_t v = 0; diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index 95f8b508..2b3bd4e6 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -15,6 +15,7 @@ namespace HIR { } class Allocation; struct Value; +struct ValueRef; struct FFIPointer { @@ -160,6 +161,8 @@ struct ValueCommon //LOG_FATAL("Attempting to get an uninit pointer to immutable data"); return rv; } + /// Read a pointer and return a ValueRef to it (mutable data) + ValueRef read_pointer_valref_mut(size_t rd_ofs, size_t size); }; class Allocation: @@ -223,6 +226,8 @@ struct Value: void create_allocation(); size_t size() const { return allocation ? allocation.alloc().size() : direct_data.size; } + const uint8_t* data_ptr() const { return allocation ? allocation.alloc().data_ptr() : direct_data.data; } + uint8_t* data_ptr() { return allocation ? allocation.alloc().data_ptr() : direct_data.data; } AllocationPtr get_relocation(size_t ofs) const override { if( this->allocation && this->allocation.is_alloc() ) @@ -259,20 +264,23 @@ struct ValueRef m_offset(ofs), m_size(size) { - switch(m_alloc.get_ty()) + if( m_alloc ) { - case AllocationPtr::Ty::Allocation: - assert(ofs < m_alloc.alloc().size()); - assert(size <= m_alloc.alloc().size()); - assert(ofs+size <= m_alloc.alloc().size()); - break; - case AllocationPtr::Ty::StdString: - assert(ofs < m_alloc.str().size()); - assert(size <= m_alloc.str().size()); - assert(ofs+size <= m_alloc.str().size()); - break; - default: - throw "TODO"; + switch(m_alloc.get_ty()) + { + case AllocationPtr::Ty::Allocation: + assert(ofs < m_alloc.alloc().size()); + assert(size <= m_alloc.alloc().size()); + assert(ofs+size <= m_alloc.alloc().size()); + break; + case AllocationPtr::Ty::StdString: + assert(ofs < m_alloc.str().size()); + assert(size <= m_alloc.str().size()); + assert(ofs+size <= m_alloc.str().size()); + break; + default: + throw "TODO"; + } } } ValueRef(Value& val): @@ -294,7 +302,7 @@ struct ValueRef else return AllocationPtr(); } - else if( m_value->allocation ) + else if( m_value && m_value->allocation ) { if( m_value->allocation.is_alloc() ) return m_value->allocation.alloc().get_relocation(ofs); @@ -306,9 +314,30 @@ struct ValueRef return AllocationPtr(); } } - Value read_value(size_t ofs, size_t size) const { + Value read_value(size_t ofs, size_t size) const; + const uint8_t* data_ptr() const { + if( m_alloc ) { + switch(m_alloc.get_ty()) + { + case AllocationPtr::Ty::Allocation: + return m_alloc.alloc().data_ptr() + m_offset; + break; + case AllocationPtr::Ty::StdString: + return reinterpret_cast(m_alloc.str().data() + m_offset); + default: + throw "TODO"; + } + } + else if( m_value ) { + return m_value->data_ptr() + m_offset; + } + else { + return nullptr; + } + } + void read_bytes(size_t ofs, void* dst, size_t size) const { if( size == 0 ) - return Value(); + return ; assert(ofs < m_size); assert(size <= m_size); assert(ofs+size <= m_size); @@ -316,26 +345,22 @@ struct ValueRef switch(m_alloc.get_ty()) { case AllocationPtr::Ty::Allocation: - return m_alloc.alloc().read_value(m_offset + ofs, size); - case AllocationPtr::Ty::StdString: { - auto rv = Value::with_size(size, false); - //ASSERT_BUG(ofs <= m_alloc.str().size(), ""); - //ASSERT_BUG(size <= m_alloc.str().size(), ""); - //ASSERT_BUG(ofs+size <= m_alloc.str().size(), ""); + m_alloc.alloc().read_bytes(m_offset + ofs, dst, size); + break; + case AllocationPtr::Ty::StdString: assert(m_offset+ofs <= m_alloc.str().size() && size <= m_alloc.str().size() && m_offset+ofs+size <= m_alloc.str().size()); - rv.write_bytes(0, m_alloc.str().data() + m_offset + ofs, size); - return rv; - } + ::std::memcpy(dst, m_alloc.str().data() + m_offset + ofs, size); + break; default: //ASSERT_BUG(m_alloc.is_alloc(), "read_value on non-data backed Value - " << ); throw "TODO"; } } else { - return m_value->read_value(m_offset + ofs, size); + m_value->read_bytes(m_offset + ofs, dst, size); } } - void read_bytes(size_t ofs, void* dst, size_t size) const { + void check_bytes_valid(size_t ofs, size_t size) const { if( size == 0 ) return ; assert(ofs < m_size); @@ -345,11 +370,10 @@ struct ValueRef switch(m_alloc.get_ty()) { case AllocationPtr::Ty::Allocation: - m_alloc.alloc().read_bytes(m_offset + ofs, dst, size); + m_alloc.alloc().check_bytes_valid(m_offset + ofs, size); break; case AllocationPtr::Ty::StdString: assert(m_offset+ofs <= m_alloc.str().size() && size <= m_alloc.str().size() && m_offset+ofs+size <= m_alloc.str().size()); - ::std::memcpy(dst, m_alloc.str().data() + m_offset + ofs, size); break; default: //ASSERT_BUG(m_alloc.is_alloc(), "read_value on non-data backed Value - " << ); @@ -357,10 +381,12 @@ struct ValueRef } } else { - m_value->read_bytes(m_offset + ofs, dst, size); + m_value->check_bytes_valid(m_offset + ofs, size); } } + bool compare(const void* other, size_t other_len) const; + // TODO: Figure out how to make this use `ValueCommon` when it can't write. uint8_t read_u8(size_t ofs) const { uint8_t rv; read_bytes(ofs, &rv, 1); return rv; } uint16_t read_u16(size_t ofs) const { uint16_t rv; read_bytes(ofs, &rv, 2); return rv; } -- cgit v1.2.3 From 9f8469d5145ea51f2d4b2b9d1eb32d1029cfbeb5 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 13 May 2018 08:54:44 +0800 Subject: Standalone MIRI - Atomic add, catch_panic --- tools/standalone_miri/main.cpp | 94 ++++++++++++++++++++++++++++++++---------- 1 file changed, 72 insertions(+), 22 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 1b33087a..e5ef9c15 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -42,7 +42,7 @@ struct ThreadState unsigned ThreadState::s_next_tls_key = 1; Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, ::std::vector args); -Value MIRI_Invoke_Extern(ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args); +Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args); Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args); int main(int argc, const char* argv[]) @@ -98,7 +98,7 @@ public: virtual bool multiply(const PrimitiveValue& v) = 0; virtual bool divide(const PrimitiveValue& v) = 0; virtual bool modulo(const PrimitiveValue& v) = 0; - virtual void write_to_value(Value& tgt, size_t ofs) const = 0; + virtual void write_to_value(ValueCommon& tgt, size_t ofs) const = 0; template const T& check(const char* opname) const @@ -157,14 +157,14 @@ struct PrimitiveUInt: struct PrimitiveU64: public PrimitiveUInt { PrimitiveU64(uint64_t v): PrimitiveUInt(v) {} - void write_to_value(Value& tgt, size_t ofs) const override { + void write_to_value(ValueCommon& tgt, size_t ofs) const override { tgt.write_u64(ofs, this->v); } }; struct PrimitiveU32: public PrimitiveUInt { PrimitiveU32(uint32_t v): PrimitiveUInt(v) {} - void write_to_value(Value& tgt, size_t ofs) const override { + void write_to_value(ValueCommon& tgt, size_t ofs) const override { tgt.write_u32(ofs, this->v); } }; @@ -218,14 +218,14 @@ struct PrimitiveSInt: struct PrimitiveI64: public PrimitiveSInt { PrimitiveI64(int64_t v): PrimitiveSInt(v) {} - void write_to_value(Value& tgt, size_t ofs) const override { + void write_to_value(ValueCommon& tgt, size_t ofs) const override { tgt.write_i64(ofs, this->v); } }; struct PrimitiveI32: public PrimitiveSInt { PrimitiveI32(int32_t v): PrimitiveSInt(v) {} - void write_to_value(Value& tgt, size_t ofs) const override { + void write_to_value(ValueCommon& tgt, size_t ofs) const override { tgt.write_i32(ofs, this->v); } }; @@ -340,23 +340,30 @@ namespace // No destructor } } - else if( ty.wrappers[0].type == TypeWrapper::Ty::Borrow ) + else { - if( ty.wrappers[0].size == static_cast(::HIR::BorrowType::Move) ) - { - LOG_TODO("Drop - " << ty << " - dereference and go to inner"); - // TODO: Clear validity on the entire inner value. - } - else + switch( ty.wrappers[0].type ) { + case TypeWrapper::Ty::Borrow: + if( ty.wrappers[0].size == static_cast(::HIR::BorrowType::Move) ) + { + LOG_TODO("Drop - " << ty << " - dereference and go to inner"); + // TODO: Clear validity on the entire inner value. + } + else + { + // No destructor + } + break; + case TypeWrapper::Ty::Pointer: // No destructor + break; + // TODO: Arrays + default: + LOG_TODO("Drop - " << ty << " - array?"); + break; } } - // TODO: Arrays - else - { - LOG_TODO("Drop - " << ty << " - array?"); - } } } @@ -396,7 +403,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: if( fcn.external.link_name != "" ) { // External function! - ret = MIRI_Invoke_Extern(thread, fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); + ret = MIRI_Invoke_Extern(modtree, thread, fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); LOG_DEBUG(path << " = " << ret); return ret; } @@ -1515,7 +1522,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: // Save as the default, error for multiple defaults if( default_target != SIZE_MAX ) { - LOG_FATAL("Two variants with no tag in Switch"); + LOG_FATAL("Two variants with no tag in Switch - " << ty); } default_target = i; } @@ -1602,7 +1609,7 @@ extern "C" { long sysconf(int); } -Value MIRI_Invoke_Extern(ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args) +Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args) { if( link_name == "__rust_allocate" ) { @@ -1654,6 +1661,27 @@ Value MIRI_Invoke_Extern(ThreadState& thread, const ::std::string& link_name, co // Just let it drop. return Value(); } + else if( link_name == "__rust_maybe_catch_panic" ) + { + auto fcn_path = args.at(0).get_relocation(0).fcn(); + auto arg = args.at(1); + auto data_ptr = args.at(2).read_pointer_valref_mut(0, POINTER_SIZE); + auto vtable_ptr = args.at(3).read_pointer_valref_mut(0, POINTER_SIZE); + + ::std::vector sub_args; + sub_args.push_back( ::std::move(arg) ); + + // TODO: Catch the panic out of this. + MIRI_Invoke(modtree, thread, fcn_path, ::std::move(sub_args)); + + auto rv = Value(::HIR::TypeRef(RawType::U32)); + rv.write_u32(0,0); + return rv; + } + else if( link_name == "__rust_start_panic" ) + { + LOG_TODO("__rust_start_panic"); + } #ifdef _WIN32 // WinAPI functions used by libstd else if( link_name == "AddVectoredExceptionHandler" ) @@ -1870,12 +1898,33 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st LOG_TRACE("Deref " << ptr_val.allocation.alloc()); auto alloc = ptr_val.allocation.alloc().get_relocation(0); LOG_ASSERT(alloc, "Deref of a value with no relocation"); + // TODO: Atomic lock the allocation. - // TODO: Atomic side of this? size_t ofs = ptr_val.read_usize(0); const auto& ty = ty_params.tys.at(0); rv = alloc.alloc().read_value(ofs, ty.get_size()); } + else if( name == "atomic_xadd" || name == "atomic_xadd_relaxed" ) + { + const auto& ty_T = ty_params.tys.at(0); + auto ptr_ofs = args.at(0).read_usize(0); + auto ptr_alloc = args.at(0).allocation.alloc().get_relocation(0); + auto v = args.at(1).read_value(0, ty_T.get_size()); + + // TODO: Atomic lock the allocation. + if( !ptr_alloc || !ptr_alloc.is_alloc() ) { + LOG_ERROR("atomic pointer has no allocation"); + } + + // - Result is the original value + rv = ptr_alloc.alloc().read_value(ptr_ofs, ty_T.get_size()); + + auto val_l = PrimitiveValueVirt::from_value(ty_T, rv); + const auto val_r = PrimitiveValueVirt::from_value(ty_T, v); + val_l.get().add( val_r.get() ); + + val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs ); + } else if( name == "atomic_cxchg" ) { const auto& ty_T = ty_params.tys.at(0); @@ -2112,6 +2161,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st { case AllocationPtr::Ty::Allocation: { auto v = src_alloc.alloc().read_value(src_ofs, byte_count); + LOG_DEBUG("v = " << v); dst_alloc.alloc().write_value(dst_ofs, ::std::move(v)); } break; case AllocationPtr::Ty::StdString: -- cgit v1.2.3 From ac6f3ffba823e539c4c9afd93b7edf7122f463cc Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 13 May 2018 09:27:13 +0800 Subject: Standalone MIRI - Better vtable handling, fix to offset with null pointers --- tools/standalone_miri/hir_sim.cpp | 30 +++++++++++-------- tools/standalone_miri/hir_sim.hpp | 6 ++-- tools/standalone_miri/main.cpp | 31 +++++++++---------- tools/standalone_miri/module_tree.cpp | 56 +++++++++++++++++------------------ 4 files changed, 65 insertions(+), 58 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/hir_sim.cpp b/tools/standalone_miri/hir_sim.cpp index 604f65a4..f3b4d400 100644 --- a/tools/standalone_miri/hir_sim.cpp +++ b/tools/standalone_miri/hir_sim.cpp @@ -166,32 +166,34 @@ const HIR::TypeRef* HIR::TypeRef::get_usized_type(size_t& running_inner_size) co return nullptr; } } -const HIR::TypeRef* HIR::TypeRef::get_meta_type() const +HIR::TypeRef HIR::TypeRef::get_meta_type() const { - static ::HIR::TypeRef static_usize = ::HIR::TypeRef(RawType::USize); if( this->wrappers.empty() ) { switch(this->inner_type) { case RawType::Composite: if( this->composite_type->dst_meta == RawType::Unreachable ) - return nullptr; - return &this->composite_type->dst_meta; - case RawType::TraitObject: - LOG_TODO("get_meta_type on TraitObject - " << *this); + return TypeRef(RawType::Unreachable); + return this->composite_type->dst_meta; + case RawType::TraitObject: { + auto rv = ::HIR::TypeRef( this->composite_type ); + rv.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, static_cast(BorrowType::Shared) }); + return rv; + } case RawType::Str: - return &static_usize; + return TypeRef(RawType::USize); default: - return nullptr; + return TypeRef(RawType::Unreachable); } } else if( this->wrappers[0].type == TypeWrapper::Ty::Slice ) { - return &static_usize; + return TypeRef(RawType::USize); } else { - return nullptr; + return TypeRef(RawType::Unreachable); } } @@ -305,7 +307,11 @@ namespace HIR { os << "function_?"; break; case RawType::TraitObject: - os << "traitobject_?"; + os << "dyn "; + if( x.composite_type ) + os << x.composite_type->my_path; + else + os << "?"; break; case RawType::Bool: os << "bool"; break; case RawType::Char: os << "char"; break; @@ -385,4 +391,4 @@ namespace HIR { } return os; } -} \ No newline at end of file +} diff --git a/tools/standalone_miri/hir_sim.hpp b/tools/standalone_miri/hir_sim.hpp index 7154de13..1dc9bcc4 100644 --- a/tools/standalone_miri/hir_sim.hpp +++ b/tools/standalone_miri/hir_sim.hpp @@ -23,7 +23,7 @@ struct DataType; enum class RawType { Unreachable, - Function, + Function, // TODO: Needs a way of indicating the signature? Unit, Bool, @@ -39,7 +39,7 @@ enum class RawType Char, Str, Composite, // Struct, Enum, Union, tuple, ... - TraitObject, // Data pointer is `*const ()`, metadata type stored in `composite_type` + TraitObject, // Data pointer is `*const ()`, vtable type stored in `composite_type` }; struct TypeWrapper { @@ -120,7 +120,7 @@ namespace HIR { size_t get_size(size_t ofs=0) const; bool has_slice_meta() const; // The attached metadata is a count const TypeRef* get_usized_type(size_t& running_inner_size) const; - const TypeRef* get_meta_type() const; + TypeRef get_meta_type() const; TypeRef get_inner() const; TypeRef wrap(TypeWrapper::Ty ty, size_t size) const; TypeRef get_field(size_t idx, size_t& ofs) const; diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index e5ef9c15..16cfd972 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -503,7 +503,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: ty = composite_ty.get_field(e.field_index, inner_ofs); LOG_DEBUG("Field - " << composite_ty << "#" << e.field_index << " = @" << inner_ofs << " " << ty); base_val.m_offset += inner_ofs; - if( !ty.get_meta_type() ) + if( ty.get_meta_type() == HIR::TypeRef(RawType::Unreachable) ) { LOG_ASSERT(base_val.m_size >= ty.get_size(), "Field didn't fit in the value - " << ty.get_size() << " required, but " << base_val.m_size << " avail"); base_val.m_size = ty.get_size(); @@ -542,12 +542,12 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: } size_t size; - const auto* meta_ty = ty.get_meta_type(); + const auto meta_ty = ty.get_meta_type(); ::std::shared_ptr meta_val; // If the type has metadata, store it. - if( meta_ty ) + if( meta_ty != RawType::Unreachable ) { - auto meta_size = meta_ty->get_size(); + auto meta_size = meta_ty.get_size(); LOG_ASSERT(val.m_size == POINTER_SIZE + meta_size, "Deref of " << ty << ", but pointer isn't correct size"); meta_val = ::std::make_shared( val.read_value(POINTER_SIZE, meta_size) ); @@ -768,14 +768,14 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: else LOG_DEBUG("- alloc=" << alloc); size_t ofs = src_base_value.m_offset; - const auto* meta = src_ty.get_meta_type(); + const auto meta = src_ty.get_meta_type(); bool is_slice_like = src_ty.has_slice_meta(); src_ty.wrappers.insert(src_ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, static_cast(re.type) }); new_val = Value(src_ty); // ^ Pointer value new_val.write_usize(0, ofs); - if( meta ) + if( meta != RawType::Unreachable ) { LOG_ASSERT(src_base_value.m_metadata, "Borrow of an unsized value, but no metadata avaliable"); new_val.write_value(POINTER_SIZE, *src_base_value.m_metadata); @@ -1460,7 +1460,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: alloc = AllocationPtr(v.m_value->allocation); } size_t ofs = v.m_offset; - assert(!ty.get_meta_type()); + assert(ty.get_meta_type() == RawType::Unreachable); auto ptr_ty = ty.wrap(TypeWrapper::Ty::Borrow, 2); @@ -1954,20 +1954,21 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st } else if( name == "offset" ) { - auto ptr_val = ::std::move(args.at(0)); + auto ptr_alloc = args.at(0).get_relocation(0); + auto ptr_ofs = args.at(0).read_usize(0); auto& ofs_val = args.at(1); - auto r = ptr_val.allocation.alloc().get_relocation(0); - auto orig_ofs = ptr_val.read_usize(0); auto delta_counts = ofs_val.read_usize(0); - auto new_ofs = orig_ofs + delta_counts * ty_params.tys.at(0).get_size(); + auto new_ofs = ptr_ofs + delta_counts * ty_params.tys.at(0).get_size(); if(POINTER_SIZE != 8) { new_ofs &= 0xFFFFFFFF; } - ptr_val.write_usize(0, new_ofs); - ptr_val.allocation.alloc().relocations.push_back({ 0, r }); - rv = ::std::move(ptr_val); + rv = ::std::move(args.at(0)); + rv.write_usize(0, new_ofs); + if( ptr_alloc ) { + rv.allocation.alloc().relocations.push_back({ 0, ptr_alloc }); + } } // effectively ptr::write else if( name == "move_val_init" ) @@ -2008,7 +2009,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st size_t fixed_size = 0; if( const auto* ity = ty.get_usized_type(fixed_size) ) { - const auto& meta_ty = *ty.get_meta_type(); + const auto meta_ty = ty.get_meta_type(); LOG_DEBUG("size_of_val - " << ty << " ity=" << *ity << " meta_ty=" << meta_ty << " fixed_size=" << fixed_size); size_t flex_size = 0; if( !ity->wrappers.empty() ) diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index a75cfa8f..fdc8f587 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -32,6 +32,8 @@ struct Parser RawType parse_core_type(); ::HIR::TypeRef parse_type(); ::HIR::GenericPath parse_tuple(); + + const DataType* get_composite(::HIR::GenericPath gp); }; void ModuleTree::load_file(const ::std::string& path) @@ -1130,19 +1132,8 @@ RawType Parser::parse_core_type() // Tuples! Should point to a composite ::HIR::GenericPath gp = parse_tuple(); - // Look up this type, then create a TypeRef referring to the type in the datastore - // - May need to create an unpopulated type? - auto it = tree.data_types.find(gp); - if( it == tree.data_types.end() ) - { - // TODO: Later on need to check if the type is valid. - auto v = ::std::make_unique(DataType {}); - v->my_path = gp; - auto ir = tree.data_types.insert(::std::make_pair( ::std::move(gp), ::std::move(v)) ); - it = ir.first; - } // Good. - return ::HIR::TypeRef(it->second.get()); + return ::HIR::TypeRef( this->get_composite(::std::move(gp)) ); } else if( lex.consume_if('[') ) { @@ -1155,7 +1146,6 @@ RawType Parser::parse_core_type() } else { - // TODO: How to handle arrays? rv.wrappers.insert( rv.wrappers.begin(), { TypeWrapper::Ty::Slice, 0 }); } lex.check_consume(']'); @@ -1196,19 +1186,7 @@ RawType Parser::parse_core_type() else if( lex.next() == "::" ) { auto path = parse_genericpath(); - // Look up this type, then create a TypeRef referring to the type in the datastore - // - May need to create an unpopulated type? - auto it = tree.data_types.find(path); - if( it == tree.data_types.end() ) - { - // TODO: Later on need to check if the type is valid. - auto v = ::std::make_unique(DataType {}); - v->my_path = path; - auto ir = tree.data_types.insert(::std::make_pair( ::std::move(path), ::std::move(v)) ); - it = ir.first; - } - // Good. - return ::HIR::TypeRef(it->second.get()); + return ::HIR::TypeRef( this->get_composite(::std::move(path))); } else if( lex.next() == "extern" || lex.next() == "fn" || lex.next() == "unsafe" ) { @@ -1282,8 +1260,17 @@ RawType Parser::parse_core_type() markers.push_back(parse_genericpath()); } lex.consume_if(')'); - return ::HIR::TypeRef(RawType::TraitObject); - // TODO: Generate the vtable path and locate that struct + + auto rv = ::HIR::TypeRef(RawType::TraitObject); + if( base_trait != ::HIR::GenericPath() ) + { + // Generate vtable path + auto vtable_path = base_trait; + vtable_path.m_simplepath.ents.back() += "#vtable"; + // - TODO: Associated types? + rv.composite_type = this->get_composite( ::std::move(vtable_path) ); + } + return rv; } else if( lex.next() == TokenClass::Ident ) { @@ -1295,6 +1282,19 @@ RawType Parser::parse_core_type() throw "ERROR"; } } +const DataType* Parser::get_composite(::HIR::GenericPath gp) +{ + auto it = tree.data_types.find(gp); + if( it == tree.data_types.end() ) + { + // TODO: Later on need to check if the type is valid. + auto v = ::std::make_unique(DataType {}); + v->my_path = gp; + auto ir = tree.data_types.insert(::std::make_pair( ::std::move(gp), ::std::move(v)) ); + it = ir.first; + } + return it->second.get(); +} ::HIR::SimplePath ModuleTree::find_lang_item(const char* name) const { -- cgit v1.2.3 From d3334162fa91fe6fd5d02912d9f82794306e646a Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 13 May 2018 09:54:54 +0800 Subject: Standalone MIRI - Create allocations for static data --- tools/standalone_miri/module_tree.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index fdc8f587..c70f17dd 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -146,8 +146,11 @@ bool Parser::parse_one() if( lex.next() == TokenClass::String ) { auto reloc_str = ::std::move(lex.consume().strval); - // TODO: Figure out how to create this allocation... - //s.val.allocation.alloc().relocations.push_back({ ofs, AllocationPtr::new_string(reloc_str) }); + + auto a = Allocation::new_alloc( reloc_str.size() ); + //a.alloc().set_tag(); + a.alloc().write_bytes(0, reloc_str.data(), reloc_str.size()); + s.val.allocation.alloc().relocations.push_back({ ofs, ::std::move(a) }); } else if( lex.next() == "::" || lex.next() == "<" ) { -- cgit v1.2.3 From c7b3036cefcd0dc412cb400455324d7ca8cd518e Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 13 May 2018 09:55:13 +0800 Subject: Standalone MIRI - memrchr and better null checking --- tools/standalone_miri/main.cpp | 22 ++++++++++++++++++++++ tools/standalone_miri/value.cpp | 3 +++ 2 files changed, 25 insertions(+) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 16cfd972..4ee503d3 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -1857,6 +1857,28 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: } return rv; } + else if( link_name == "memrchr" ) + { + auto ptr_alloc = args.at(0).get_relocation(0); + auto c = args.at(1).read_i32(0); + auto n = args.at(2).read_usize(0); + const void* ptr = args.at(0).read_pointer_const(0, n); + + const void* ret = memrchr(ptr, c, n); + + auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv.create_allocation(); + if( ret ) + { + rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast(ret) - static_cast(ptr) )); + rv.allocation.alloc().relocations.push_back({ 0, ptr_alloc }); + } + else + { + rv.write_usize(0, 0); + } + return rv; + } // Allocators! else { diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index 468425e9..db352019 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -169,6 +169,9 @@ void* ValueCommon::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& if( ofs != 0 ) { LOG_FATAL("Read a non-zero offset with no relocation"); } + if( req_valid > 0 ) { + LOG_ERROR("Attempting to read a null pointer"); + } out_is_mut = false; out_size = 0; return nullptr; -- cgit v1.2.3 From 51e08ea81248930fdaf94acb4d893e8a47f406f2 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 13 May 2018 10:37:05 +0800 Subject: Standalone MIRI - Misc cleanups --- tools/standalone_miri/main.cpp | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 4ee503d3..d210849c 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -674,7 +674,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: } break; TU_ARM(c, ItemAddr, ce) { // Create a value with a special backing allocation of zero size that references the specified item. - if( const auto* fn = modtree.get_function_opt(ce) ) { + if( /*const auto* fn =*/ modtree.get_function_opt(ce) ) { ty = ::HIR::TypeRef(RawType::Function); return Value::new_fnptr(ce); } @@ -769,7 +769,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: LOG_DEBUG("- alloc=" << alloc); size_t ofs = src_base_value.m_offset; const auto meta = src_ty.get_meta_type(); - bool is_slice_like = src_ty.has_slice_meta(); + //bool is_slice_like = src_ty.has_slice_meta(); src_ty.wrappers.insert(src_ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, static_cast(re.type) }); new_val = Value(src_ty); @@ -1205,11 +1205,13 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: new_val = Value(ty_l); switch(ty_l.inner_type) { + // TODO: U128 case RawType::U64: new_val.write_u64(0, Ops::do_bitwise(v_l.read_u64(0), static_cast(shift), re.op)); break; case RawType::U32: new_val.write_u32(0, Ops::do_bitwise(v_l.read_u32(0), static_cast(shift), re.op)); break; case RawType::U16: new_val.write_u16(0, Ops::do_bitwise(v_l.read_u16(0), static_cast(shift), re.op)); break; case RawType::U8 : new_val.write_u8 (0, Ops::do_bitwise(v_l.read_u8 (0), static_cast(shift), re.op)); break; case RawType::USize: new_val.write_usize(0, Ops::do_bitwise(v_l.read_usize(0), static_cast(shift), re.op)); break; + // TODO: Is signed allowed? default: LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); } @@ -1222,24 +1224,27 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: new_val = Value(ty_l); switch(ty_l.inner_type) { + // TODO: U128/I128 case RawType::U64: + case RawType::I64: new_val.write_u64( 0, Ops::do_bitwise(v_l.read_u64(0), v_r.read_u64(0), re.op) ); break; case RawType::U32: + case RawType::I32: new_val.write_u32( 0, static_cast(Ops::do_bitwise(v_l.read_u32(0), v_r.read_u32(0), re.op)) ); break; case RawType::U16: + case RawType::I16: new_val.write_u16( 0, static_cast(Ops::do_bitwise(v_l.read_u16(0), v_r.read_u16(0), re.op)) ); break; case RawType::U8: + case RawType::I8: new_val.write_u8 ( 0, static_cast(Ops::do_bitwise(v_l.read_u8 (0), v_r.read_u8 (0), re.op)) ); break; case RawType::USize: + case RawType::ISize: new_val.write_usize( 0, Ops::do_bitwise(v_l.read_usize(0), v_r.read_usize(0), re.op) ); break; - case RawType::I32: - new_val.write_i32( 0, static_cast(Ops::do_bitwise(v_l.read_i32(0), v_r.read_i32(0), re.op)) ); - break; default: LOG_TODO("BinOp bitwise - " << se.src << " w/ " << ty_l); } @@ -1276,20 +1281,26 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: switch(ty.inner_type) { case RawType::U128: + case RawType::I128: LOG_TODO("UniOp::INV U128"); case RawType::U64: + case RawType::I64: new_val.write_u64( 0, ~v.read_u64(0) ); break; case RawType::U32: + case RawType::I32: new_val.write_u32( 0, ~v.read_u32(0) ); break; case RawType::U16: + case RawType::I16: new_val.write_u16( 0, ~v.read_u16(0) ); break; case RawType::U8: + case RawType::I8: new_val.write_u8 ( 0, ~v.read_u8 (0) ); break; case RawType::USize: + case RawType::ISize: new_val.write_usize( 0, ~v.read_usize(0) ); break; case RawType::Bool: @@ -1320,7 +1331,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: new_val.write_isize( 0, -v.read_isize(0) ); break; default: - LOG_TODO("UniOp::INV - w/ type " << ty); + LOG_ERROR("UniOp::INV not valid on type " << ty); } break; } @@ -1474,7 +1485,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: } } break; TU_ARM(stmt, SetDropFlag, se) { - bool val = (se.other == ~0 ? false : state.drop_flags.at(se.other)) != se.new_val; + bool val = (se.other == ~0u ? false : state.drop_flags.at(se.other)) != se.new_val; LOG_DEBUG("- " << val); state.drop_flags.at(se.idx) = val; } break; @@ -1782,7 +1793,6 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: } else if( link_name == "pthread_key_create" ) { - size_t size; auto key_ref = args.at(0).read_pointer_valref_mut(0, 4); auto key = ThreadState::s_next_tls_key ++; @@ -1907,7 +1917,6 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st // TODO: Atomic side of this? size_t ofs = ptr_val.read_usize(0); - const auto& ty = ty_params.tys.at(0); alloc.alloc().write_value(ofs, ::std::move(data_val)); } else if( name == "atomic_load" || name == "atomic_load_relaxed" ) @@ -2007,7 +2016,6 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st LOG_ASSERT(alloc, "Deref of a value with no relocation"); size_t ofs = ptr_val.read_usize(0); - const auto& ty = ty_params.tys.at(0); alloc.alloc().write_value(ofs, ::std::move(data_val)); LOG_DEBUG(alloc.alloc()); } -- cgit v1.2.3 From 689722fa920cfa74880922ac626cc935b202acc4 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 13 May 2018 14:08:55 +0800 Subject: Standalone MIRI - Shallow drops and better tracing --- tools/standalone_miri/main.cpp | 76 ++++++++++++++++++++++++++++++----- tools/standalone_miri/module_tree.cpp | 2 +- tools/standalone_miri/value.cpp | 52 ++++++++++++++++-------- tools/standalone_miri/value.hpp | 11 +++-- 4 files changed, 109 insertions(+), 32 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index d210849c..97ca8e6f 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -314,8 +314,22 @@ struct Ops { namespace { - void drop_value(ModuleTree& modtree, ThreadState& thread, Value ptr, const ::HIR::TypeRef& ty) + void drop_value(ModuleTree& modtree, ThreadState& thread, Value ptr, const ::HIR::TypeRef& ty, bool is_shallow=false) { + if( is_shallow ) + { + // HACK: Only works for Box where the first pointer is the data pointer + auto box_ptr_vr = ptr.read_pointer_valref_mut(0, POINTER_SIZE); + auto ofs = box_ptr_vr.read_usize(0); + auto alloc = box_ptr_vr.get_relocation(0); + if( ofs != 0 || !alloc || !alloc.is_alloc() ) { + LOG_ERROR("Attempting to shallow drop with invalid pointer (no relocation or non-zero offset) - " << box_ptr_vr); + } + + LOG_DEBUG("drop_value SHALLOW deallocate " << alloc); + alloc.alloc().mark_as_freed(); + return ; + } if( ty.wrappers.empty() ) { if( ty.inner_type == RawType::Composite ) @@ -1479,7 +1493,8 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: ptr_val.write_usize(0, ofs); ptr_val.allocation.alloc().relocations.push_back(Relocation { 0, ::std::move(alloc) }); - drop_value(modtree, thread, ptr_val, ty); + // TODO: Shallow drop + drop_value(modtree, thread, ptr_val, ty, /*shallow=*/se.kind == ::MIR::eDropKind::SHALLOW); // TODO: Clear validity on the entire inner value. //alloc.mark_as_freed(); } @@ -1618,6 +1633,7 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: extern "C" { long sysconf(int); + ssize_t write(int, const void*, size_t); } Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args) @@ -1661,14 +1677,12 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: auto alloc_ptr = args.at(0).allocation.alloc().get_relocation(0); auto ptr_ofs = args.at(0).read_usize(0); LOG_ASSERT(ptr_ofs == 0, "__rust_deallocate with offset pointer"); + LOG_DEBUG("__rust_deallocate(ptr=" << alloc_ptr << ")"); LOG_ASSERT(alloc_ptr, "__rust_deallocate with no backing allocation attached to pointer"); LOG_ASSERT(alloc_ptr.is_alloc(), "__rust_deallocate with no backing allocation attached to pointer"); auto& alloc = alloc_ptr.alloc(); - // TODO: Figure out how to prevent this ever being written again. - //alloc.mark_as_freed(); - for(auto& v : alloc.mask) - v = 0; + alloc.mark_as_freed(); // Just let it drop. return Value(); } @@ -1693,6 +1707,10 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: { LOG_TODO("__rust_start_panic"); } + else if( link_name == "rust_begin_unwind" ) + { + LOG_TODO("rust_begin_unwind"); + } #ifdef _WIN32 // WinAPI functions used by libstd else if( link_name == "AddVectoredExceptionHandler" ) @@ -1758,6 +1776,18 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: } #else // POSIX + else if( link_name == "write" ) + { + auto fd = args.at(0).read_i32(0); + auto count = args.at(2).read_isize(0); + const auto* buf = args.at(1).read_pointer_const(0, count); + + ssize_t val = write(fd, buf, count); + + auto rv = Value(::HIR::TypeRef(RawType::ISize)); + rv.write_isize(0, val); + return rv; + } else if( link_name == "sysconf" ) { auto name = args.at(0).read_i32(0); @@ -1767,7 +1797,7 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: rv.write_usize(0, val); return rv; } - else if( link_name == "pthread_mutex_init" || link_name == "pthread_mutex_lock" || link_name == "pthread_mutex_unlock" ) + else if( link_name == "pthread_mutex_init" || link_name == "pthread_mutex_lock" || link_name == "pthread_mutex_unlock" || link_name == "pthread_mutex_destroy" ) { auto rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); @@ -1902,7 +1932,11 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st TRACE_FUNCTION_R(name, rv); for(const auto& a : args) LOG_DEBUG("#" << (&a - args.data()) << ": " << a); - if( name == "atomic_store" ) + if( name == "atomic_fence" || name == "atomic_fence_acq" ) + { + return Value(); + } + else if( name == "atomic_store" ) { auto& ptr_val = args.at(0); auto& data_val = args.at(1); @@ -1956,6 +1990,27 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs ); } + else if( name == "atomic_xsub" || name == "atomic_xsub_relaxed" || name == "atomic_xsub_rel" ) + { + const auto& ty_T = ty_params.tys.at(0); + auto ptr_ofs = args.at(0).read_usize(0); + auto ptr_alloc = args.at(0).allocation.alloc().get_relocation(0); + auto v = args.at(1).read_value(0, ty_T.get_size()); + + // TODO: Atomic lock the allocation. + if( !ptr_alloc || !ptr_alloc.is_alloc() ) { + LOG_ERROR("atomic pointer has no allocation"); + } + + // - Result is the original value + rv = ptr_alloc.alloc().read_value(ptr_ofs, ty_T.get_size()); + + auto val_l = PrimitiveValueVirt::from_value(ty_T, rv); + const auto val_r = PrimitiveValueVirt::from_value(ty_T, v); + val_l.get().subtract( val_r.get() ); + + val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs ); + } else if( name == "atomic_cxchg" ) { const auto& ty_T = ty_params.tys.at(0); @@ -2086,13 +2141,14 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st case TypeWrapper::Ty::Pointer: break; case TypeWrapper::Ty::Borrow: + // TODO: Only &move has a destructor break; } LOG_ASSERT(ty.wrappers[0].type == TypeWrapper::Ty::Slice, "drop_in_place should only exist for slices - " << ty); const auto& ity = ty.get_inner(); size_t item_size = ity.get_size(); - auto ptr = val.read_value(0, POINTER_SIZE);; + auto ptr = val.read_value(0, POINTER_SIZE); for(size_t i = 0; i < item_count; i ++) { drop_value(modtree, thread, ptr, ity); @@ -2101,7 +2157,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st } else { - LOG_TODO("drop_in_place - " << ty); + drop_value(modtree, thread, val, ty); } } // ---------------------------------------------------------------- diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index c70f17dd..88d8ff88 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -675,7 +675,7 @@ bool Parser::parse_one() case '<': if( t.strval[1] == '<' ) op = ::MIR::eBinOp::BIT_SHL; - else if( lex.consume_if('=') ) + else if( t.strval[1] == '=' ) op = ::MIR::eBinOp::LE; else op = ::MIR::eBinOp::LT; diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index db352019..cdace6e2 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -232,6 +232,8 @@ ValueRef ValueCommon::read_pointer_valref_mut(size_t rd_ofs, size_t size) void Allocation::resize(size_t new_size) { + if( this->is_freed ) + LOG_ERROR("Use of freed memory " << this); //size_t old_size = this->size(); //size_t extra_bytes = (new_size > old_size ? new_size - old_size : 0); @@ -246,9 +248,9 @@ void Allocation::check_bytes_valid(size_t ofs, size_t size) const } for(size_t i = ofs; i < ofs + size; i++) { - if( !(this->mask[i/8] & (1 << i%8)) ) + if( !(this->mask[i/8] & (1 << (i%8))) ) { - LOG_ERROR("Invalid bytes in value"); + LOG_ERROR("Invalid bytes in value - " << ofs << "+" << size << " - " << *this); throw "ERROR"; } } @@ -258,14 +260,18 @@ void Allocation::mark_bytes_valid(size_t ofs, size_t size) assert( ofs+size <= this->mask.size() * 8 ); for(size_t i = ofs; i < ofs + size; i++) { - this->mask[i/8] |= (1 << i%8); + this->mask[i/8] |= (1 << (i%8)); } } Value Allocation::read_value(size_t ofs, size_t size) const { Value rv; + TRACE_FUNCTION_R("Allocation::read_value " << this << " " << ofs << "+" << size, *this << " | " << rv); + if( this->is_freed ) + LOG_ERROR("Use of freed memory " << this); + LOG_DEBUG(*this); - // TODO: Determine if this can become an inline allocation. + // Determine if this can become an inline allocation. bool has_reloc = false; for(const auto& r : this->relocations) { @@ -292,14 +298,12 @@ Value Allocation::read_value(size_t ofs, size_t size) const for(size_t i = 0; i < size; i ++) { size_t j = ofs + i; - bool v = (this->mask[j/8] & (1 << j%8)) != 0; + const uint8_t test_mask = (1 << (j%8)); + const uint8_t set_mask = (1 << (i%8)); + bool v = (this->mask[j/8] & test_mask) != 0; if( v ) { - rv.allocation.alloc().mask[i/8] |= (1 << i%8); - } - else - { - rv.allocation.alloc().mask[i/8] &= ~(1 << i%8); + rv.allocation.alloc().mask[i/8] |= set_mask; } } } @@ -315,21 +319,23 @@ Value Allocation::read_value(size_t ofs, size_t size) const for(size_t i = 0; i < size; i ++) { size_t j = ofs + i; - bool v = (this->mask[j/8] & (1 << j%8)) != 0; + const uint8_t tst_mask = 1 << (j%8); + const uint8_t set_mask = 1 << (i%8); + bool v = (this->mask[j/8] & tst_mask) != 0; if( v ) { - rv.direct_data.mask[i/8] |= (1 << i%8); + rv.direct_data.mask[i/8] |= set_mask; } - //else - //{ - // rv.direct_data.mask[i/8] &= ~(1 << i%8); - //} } } return rv; } void Allocation::read_bytes(size_t ofs, void* dst, size_t count) const { + if( this->is_freed ) + LOG_ERROR("Use of freed memory " << this); + + LOG_DEBUG("Allocation::read_bytes " << this << " " << ofs << "+" << count); if(count == 0) return ; @@ -352,6 +358,11 @@ void Allocation::read_bytes(size_t ofs, void* dst, size_t count) const } void Allocation::write_value(size_t ofs, Value v) { + TRACE_FUNCTION_R("Allocation::write_value " << this << " " << ofs << "+" << v.size() << " " << v, *this); + if( this->is_freed ) + LOG_ERROR("Use of freed memory " << this); + //if( this->is_read_only ) + // LOG_ERROR("Writing to read-only allocation " << this); if( v.allocation ) { size_t v_size = v.allocation.alloc().size(); @@ -416,8 +427,15 @@ void Allocation::write_value(size_t ofs, Value v) } void Allocation::write_bytes(size_t ofs, const void* src, size_t count) { + //LOG_DEBUG("Allocation::write_bytes " << this << " " << ofs << "+" << count); + if( this->is_freed ) + LOG_ERROR("Use of freed memory " << this); + //if( this->is_read_only ) + // LOG_ERROR("Writing to read-only allocation " << this); + if(count == 0) return ; + TRACE_FUNCTION_R("Allocation::write_bytes " << this << " " << ofs << "+" << count, *this); if(ofs >= this->size() ) { LOG_ERROR("Out of bounds write, " << ofs << "+" << count << " > " << this->size()); throw "ERROR"; @@ -459,7 +477,7 @@ void Allocation::write_bytes(size_t ofs, const void* src, size_t count) if( i != 0 ) os << " "; - if( x.mask[i/8] & (1 << i%8) ) + if( x.mask[i/8] & (1 << (i%8)) ) { os << ::std::setw(2) << ::std::setfill('0') << (int)x.data_ptr()[i]; } diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index 2b3bd4e6..aa41b838 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -171,6 +171,7 @@ class Allocation: friend class AllocationPtr; size_t refcount; // TODO: Read-only flag? + bool is_freed = false; public: static AllocationPtr new_alloc(size_t size); @@ -189,10 +190,12 @@ public: } return AllocationPtr(); } - //void mark_as_freed() { - // for(auto& v : mask) - // v = 0; - //} + void mark_as_freed() { + is_freed = true; + relocations.clear(); + for(auto& v : mask) + v = 0; + } void resize(size_t new_size); -- cgit v1.2.3 From 872827f5d8db975f41eabe1ec1048e50b3bc166f Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 13 May 2018 17:00:44 +0800 Subject: Standalone MIRI - Working hello.rs --- tools/standalone_miri/main.cpp | 35 ++++++++++++++++++++++++++++++++--- tools/standalone_miri/module_tree.cpp | 4 ++++ 2 files changed, 36 insertions(+), 3 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 97ca8e6f..bd86967c 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -1803,6 +1803,12 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: rv.write_i32(0, 0); return rv; } + else if( link_name == "pthread_rwlock_rdlock" ) + { + auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + return rv; + } else if( link_name == "pthread_mutexattr_init" || link_name == "pthread_mutexattr_settype" || link_name == "pthread_mutexattr_destroy" ) { auto rv = Value(::HIR::TypeRef(RawType::I32)); @@ -1932,7 +1938,20 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st TRACE_FUNCTION_R(name, rv); for(const auto& a : args) LOG_DEBUG("#" << (&a - args.data()) << ": " << a); - if( name == "atomic_fence" || name == "atomic_fence_acq" ) + if( name == "type_id" ) + { + const auto& ty_T = ty_params.tys.at(0); + static ::std::vector type_ids; + auto it = ::std::find(type_ids.begin(), type_ids.end(), ty_T); + if( it == type_ids.end() ) + { + it = type_ids.insert(it, ty_T); + } + + rv = Value::with_size(POINTER_SIZE, false); + rv.write_usize(0, it - type_ids.begin()); + } + else if( name == "atomic_fence" || name == "atomic_fence_acq" ) { return Value(); } @@ -2011,16 +2030,26 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs ); } + else if( name == "atomic_xchg" ) + { + const auto& ty_T = ty_params.tys.at(0); + auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size()); + const auto& new_v = args.at(1); + + rv = data_ref.read_value(0, new_v.size()); + data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v ); + } else if( name == "atomic_cxchg" ) { const auto& ty_T = ty_params.tys.at(0); // TODO: Get a ValueRef to the target location auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size()); const auto& old_v = args.at(1); - const auto& new_v = args.at(1); + const auto& new_v = args.at(2); rv = Value::with_size( ty_T.get_size() + 1, false ); rv.write_value(0, data_ref.read_value(0, old_v.size())); - if( data_ref.compare(old_v.data_ptr(), old_v.size()) == 0 ) { + LOG_DEBUG("> *ptr = " << data_ref); + if( data_ref.compare(old_v.data_ptr(), old_v.size()) == true ) { data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v ); rv.write_u8( old_v.size(), 1 ); } diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index 88d8ff88..ad41b33a 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -102,6 +102,7 @@ bool Parser::parse_one() auto abi = ::std::move(lex.check_consume(TokenClass::String).strval); lex.check_consume(';'); + LOG_DEBUG("fn " << p); auto p2 = p; tree.functions.insert( ::std::make_pair(::std::move(p), Function { ::std::move(p2), ::std::move(arg_tys), rv_ty, {link_name, abi}, {} }) ); } @@ -109,6 +110,7 @@ bool Parser::parse_one() { auto body = parse_body(); + LOG_DEBUG("fn " << p); auto p2 = p; tree.functions.insert( ::std::make_pair(::std::move(p), Function { ::std::move(p2), ::std::move(arg_tys), rv_ty, {}, ::std::move(body) }) ); } @@ -170,6 +172,7 @@ bool Parser::parse_one() } lex.check_consume(';'); + LOG_DEBUG("static " << p); tree.statics.insert(::std::make_pair( ::std::move(p), ::std::move(s) )); } else if( lex.consume_if("type") ) @@ -290,6 +293,7 @@ bool Parser::parse_one() throw "ERROR"; } + LOG_DEBUG("type " << p); auto it = this->tree.data_types.find(p); if( it != this->tree.data_types.end() ) { -- cgit v1.2.3 From ee65f12f4aeb27238c8a2fc07fbe84eceafdde26 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 13 May 2018 21:29:27 +0800 Subject: Standalone MIRI - Refactor to remove linkage of host and VM stack --- tools/standalone_miri/main.cpp | 2400 +++++++++++++++++++++------------------- 1 file changed, 1268 insertions(+), 1132 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index bd86967c..1ab5b955 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -41,9 +41,58 @@ struct ThreadState }; unsigned ThreadState::s_next_tls_key = 1; -Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, ::std::vector args); -Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args); -Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args); +class InterpreterThread +{ + friend struct MirHelpers; + struct StackFrame + { + ::std::function cb; + const Function& fcn; + Value ret; + ::std::vector args; + ::std::vector locals; + ::std::vector drop_flags; + + unsigned bb_idx; + unsigned stmt_idx; + + StackFrame(const Function& fcn, ::std::vector args); + static StackFrame make_wrapper(::std::function cb) { + static Function f; + StackFrame rv(f, {}); + rv.cb = ::std::move(cb); + return rv; + } + }; + + ModuleTree& m_modtree; + ThreadState m_thread; + ::std::vector m_stack; + +public: + InterpreterThread(ModuleTree& modtree): + m_modtree(modtree) + { + } + ~InterpreterThread(); + + void start(const ::HIR::Path& p, ::std::vector args); + // Returns `true` if the call stack empties + bool step_one(Value& out_thread_result); + +private: + bool pop_stack(Value& out_thread_result); + + // Returns true if the call was resolved instantly + bool call_path(Value& ret_val, const ::HIR::Path& p, ::std::vector args); + // Returns true if the call was resolved instantly + bool call_extern(Value& ret_val, const ::std::string& name, const ::std::string& abi, ::std::vector args); + // Returns true if the call was resolved instantly + bool call_intrinsic(Value& ret_val, const ::std::string& name, const ::HIR::PathParams& pp, ::std::vector args); + + // Returns true if the call was resolved instantly + bool drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_shallow=false); +}; int main(int argc, const char* argv[]) { @@ -63,16 +112,22 @@ int main(int argc, const char* argv[]) argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); auto val_argv = Value(argv_ty); - val_argc.write_bytes(0, "\0\0\0\0\0\0\0", 8); - val_argv.write_bytes(0, "\0\0\0\0\0\0\0", argv_ty.get_size()); + val_argc.write_isize(0, 0); + val_argv.write_usize(0, 0); try { - ThreadState ts; + InterpreterThread root_thread(tree); + ::std::vector args; args.push_back(::std::move(val_argc)); args.push_back(::std::move(val_argv)); - auto rv = MIRI_Invoke( tree, ts, tree.find_lang_item("start"), ::std::move(args) ); + Value rv; + root_thread.start(tree.find_lang_item("start"), ::std::move(args)); + while( !root_thread.step_one(rv) ) + { + } + ::std::cout << rv << ::std::endl; } catch(const DebugExceptionTodo& /*e*/) @@ -311,726 +366,573 @@ struct Ops { } }; -namespace +struct MirHelpers { + InterpreterThread& thread; + InterpreterThread::StackFrame& frame; - void drop_value(ModuleTree& modtree, ThreadState& thread, Value ptr, const ::HIR::TypeRef& ty, bool is_shallow=false) + MirHelpers(InterpreterThread& thread, InterpreterThread::StackFrame& frame): + thread(thread), + frame(frame) { - if( is_shallow ) - { - // HACK: Only works for Box where the first pointer is the data pointer - auto box_ptr_vr = ptr.read_pointer_valref_mut(0, POINTER_SIZE); - auto ofs = box_ptr_vr.read_usize(0); - auto alloc = box_ptr_vr.get_relocation(0); - if( ofs != 0 || !alloc || !alloc.is_alloc() ) { - LOG_ERROR("Attempting to shallow drop with invalid pointer (no relocation or non-zero offset) - " << box_ptr_vr); - } - - LOG_DEBUG("drop_value SHALLOW deallocate " << alloc); - alloc.alloc().mark_as_freed(); - return ; - } - if( ty.wrappers.empty() ) + } + + ValueRef get_value_and_type(const ::MIR::LValue& lv, ::HIR::TypeRef& ty) + { + switch(lv.tag()) { - if( ty.inner_type == RawType::Composite ) + case ::MIR::LValue::TAGDEAD: throw ""; + // --> Slots + TU_ARM(lv, Return, _e) { + ty = this->frame.fcn.ret_ty; + return ValueRef(this->frame.ret); + } break; + TU_ARM(lv, Local, e) { + ty = this->frame.fcn.m_mir.locals.at(e); + return ValueRef(this->frame.locals.at(e)); + } break; + TU_ARM(lv, Argument, e) { + ty = this->frame.fcn.args.at(e.idx); + return ValueRef(this->frame.args.at(e.idx)); + } break; + TU_ARM(lv, Static, e) { + /*const*/ auto& s = this->thread.m_modtree.get_static(e); + ty = s.ty; + return ValueRef(s.val); + } break; + // --> Modifiers + TU_ARM(lv, Index, e) { + auto idx = get_value_ref(*e.idx).read_usize(0); + ::HIR::TypeRef array_ty; + auto base_val = get_value_and_type(*e.val, array_ty); + if( array_ty.wrappers.empty() ) + LOG_ERROR("Indexing non-array/slice - " << array_ty); + if( array_ty.wrappers.front().type == TypeWrapper::Ty::Array ) { - if( ty.composite_type->drop_glue != ::HIR::Path() ) - { - LOG_DEBUG("Drop - " << ty); - - MIRI_Invoke(modtree, thread, ty.composite_type->drop_glue, { ptr }); - } - else - { - // No drop glue - } + ty = array_ty.get_inner(); + base_val.m_offset += ty.get_size() * idx; + return base_val; } - else if( ty.inner_type == RawType::TraitObject ) + else if( array_ty.wrappers.front().type == TypeWrapper::Ty::Slice ) { - LOG_TODO("Drop - " << ty << " - trait object"); + LOG_TODO("Slice index"); } else { - // No destructor + LOG_ERROR("Indexing non-array/slice - " << array_ty); + throw "ERROR"; } - } - else - { - switch( ty.wrappers[0].type ) + } break; + TU_ARM(lv, Field, e) { + ::HIR::TypeRef composite_ty; + auto base_val = get_value_and_type(*e.val, composite_ty); + // TODO: if there's metadata present in the base, but the inner doesn't have metadata, clear the metadata + size_t inner_ofs; + ty = composite_ty.get_field(e.field_index, inner_ofs); + LOG_DEBUG("Field - " << composite_ty << "#" << e.field_index << " = @" << inner_ofs << " " << ty); + base_val.m_offset += inner_ofs; + if( ty.get_meta_type() == HIR::TypeRef(RawType::Unreachable) ) { - case TypeWrapper::Ty::Borrow: - if( ty.wrappers[0].size == static_cast(::HIR::BorrowType::Move) ) + LOG_ASSERT(base_val.m_size >= ty.get_size(), "Field didn't fit in the value - " << ty.get_size() << " required, but " << base_val.m_size << " avail"); + base_val.m_size = ty.get_size(); + } + return base_val; + } + TU_ARM(lv, Downcast, e) { + ::HIR::TypeRef composite_ty; + auto base_val = get_value_and_type(*e.val, composite_ty); + LOG_DEBUG("Downcast - " << composite_ty); + + size_t inner_ofs; + ty = composite_ty.get_field(e.variant_index, inner_ofs); + base_val.m_offset += inner_ofs; + return base_val; + } + TU_ARM(lv, Deref, e) { + ::HIR::TypeRef ptr_ty; + auto val = get_value_and_type(*e.val, ptr_ty); + ty = ptr_ty.get_inner(); + LOG_DEBUG("val = " << val << ", (inner) ty=" << ty); + + LOG_ASSERT(val.m_size >= POINTER_SIZE, "Deref of a value that doesn't fit a pointer - " << ty); + size_t ofs = val.read_usize(0); + + // There MUST be a relocation at this point with a valid allocation. + auto& val_alloc = val.m_alloc ? val.m_alloc : val.m_value->allocation; + LOG_ASSERT(val_alloc, "Deref of a value with no allocation (hence no relocations)"); + LOG_ASSERT(val_alloc.is_alloc(), "Deref of a value with a non-data allocation"); + LOG_TRACE("Deref " << val_alloc.alloc() << " + " << ofs << " to give value of type " << ty); + auto alloc = val_alloc.alloc().get_relocation(val.m_offset); + // NOTE: No alloc can happen when dereferencing a zero-sized pointer + if( alloc.is_alloc() ) + { + LOG_DEBUG("> " << lv << " alloc=" << alloc.alloc()); + } + size_t size; + + const auto meta_ty = ty.get_meta_type(); + ::std::shared_ptr meta_val; + // If the type has metadata, store it. + if( meta_ty != RawType::Unreachable ) + { + auto meta_size = meta_ty.get_size(); + LOG_ASSERT(val.m_size == POINTER_SIZE + meta_size, "Deref of " << ty << ", but pointer isn't correct size"); + meta_val = ::std::make_shared( val.read_value(POINTER_SIZE, meta_size) ); + + // TODO: Get a more sane size from the metadata + if( alloc ) { - LOG_TODO("Drop - " << ty << " - dereference and go to inner"); - // TODO: Clear validity on the entire inner value. + LOG_DEBUG("> Meta " << *meta_val << ", size = " << alloc.get_size() << " - " << ofs); + size = alloc.get_size() - ofs; } else { - // No destructor + size = 0; } - break; - case TypeWrapper::Ty::Pointer: - // No destructor - break; - // TODO: Arrays - default: - LOG_TODO("Drop - " << ty << " - array?"); - break; } + else + { + LOG_ASSERT(val.m_size == POINTER_SIZE, "Deref of a value that isn't a pointer-sized value (size=" << val.m_size << ") - " << val << ": " << ptr_ty); + size = ty.get_size(); + if( !alloc ) { + LOG_ERROR("Deref of a value with no relocation - " << val); + } + } + + LOG_DEBUG("alloc=" << alloc << ", ofs=" << ofs << ", size=" << size); + auto rv = ValueRef(::std::move(alloc), ofs, size); + rv.m_metadata = ::std::move(meta_val); + return rv; + } break; } + throw ""; } - -} - -Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, ::std::vector args) -{ - Value ret; - - const auto& fcn = modtree.get_function(path); - - - // TODO: Support overriding certain functions + ValueRef get_value_ref(const ::MIR::LValue& lv) { - if( path == ::HIR::SimplePath { "std", { "sys", "imp", "c", "SetThreadStackGuarantee" } } ) - { - ret = Value(::HIR::TypeRef{RawType::I32}); - ret.write_i32(0, 120); // ERROR_CALL_NOT_IMPLEMENTED - return ret; - } - - // - No guard page needed - if( path == ::HIR::SimplePath { "std", {"sys", "imp", "thread", "guard", "init" } } ) - { - ret = Value::with_size(16, false); - ret.write_u64(0, 0); - ret.write_u64(8, 0); - return ret; - } - - // - No stack overflow handling needed - if( path == ::HIR::SimplePath { "std", { "sys", "imp", "stack_overflow", "imp", "init" } } ) - { - return ret; - } + ::HIR::TypeRef tmp; + return get_value_and_type(lv, tmp); } - if( fcn.external.link_name != "" ) + ::HIR::TypeRef get_lvalue_ty(const ::MIR::LValue& lv) { - // External function! - ret = MIRI_Invoke_Extern(modtree, thread, fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); - LOG_DEBUG(path << " = " << ret); - return ret; + ::HIR::TypeRef ty; + get_value_and_type(lv, ty); + return ty; } - // Recursion limit. - if( thread.call_stack_depth > 40 ) { - LOG_ERROR("Recursion limit exceeded"); - } - auto _ = thread.enter_function(); + Value read_lvalue_with_ty(const ::MIR::LValue& lv, ::HIR::TypeRef& ty) + { + auto base_value = get_value_and_type(lv, ty); - TRACE_FUNCTION_R(path, path << " = " << ret); - for(size_t i = 0; i < args.size(); i ++) + return base_value.read_value(0, ty.get_size()); + } + Value read_lvalue(const ::MIR::LValue& lv) { - LOG_DEBUG("- Argument(" << i << ") = " << args[i]); - // TODO: Check argument sizes against prototype? + ::HIR::TypeRef ty; + return read_lvalue_with_ty(lv, ty); } - - ret = Value(fcn.ret_ty == RawType::Unreachable ? ::HIR::TypeRef() : fcn.ret_ty); - - struct State + void write_lvalue(const ::MIR::LValue& lv, Value val) { - ModuleTree& modtree; - const Function& fcn; - Value& ret; - ::std::vector args; - ::std::vector locals; - ::std::vector drop_flags; - - State(ModuleTree& modtree, const Function& fcn, Value& ret, ::std::vector args): - modtree(modtree), - fcn(fcn), - ret(ret), - args(::std::move(args)), - drop_flags(fcn.m_mir.drop_flags) - { - locals.reserve(fcn.m_mir.locals.size()); - for(const auto& ty : fcn.m_mir.locals) - { - if( ty == RawType::Unreachable ) { - // HACK: Locals can be !, but they can NEVER be accessed - locals.push_back(Value()); - } - else { - locals.push_back(Value(ty)); - } - } - } - - ValueRef get_value_and_type(const ::MIR::LValue& lv, ::HIR::TypeRef& ty) - { - switch(lv.tag()) - { - case ::MIR::LValue::TAGDEAD: throw ""; - TU_ARM(lv, Return, _e) { - ty = fcn.ret_ty; - return ValueRef(ret, 0, ret.size()); - } break; - TU_ARM(lv, Local, e) { - ty = fcn.m_mir.locals.at(e); - return ValueRef(locals.at(e), 0, locals.at(e).size()); - } break; - TU_ARM(lv, Argument, e) { - ty = fcn.args.at(e.idx); - return ValueRef(args.at(e.idx), 0, args.at(e.idx).size()); - } break; - TU_ARM(lv, Static, e) { - /*const*/ auto& s = modtree.get_static(e); - ty = s.ty; - return ValueRef(s.val, 0, s.val.size()); - } break; - TU_ARM(lv, Index, e) { - auto idx = get_value_ref(*e.idx).read_usize(0); - ::HIR::TypeRef array_ty; - auto base_val = get_value_and_type(*e.val, array_ty); - if( array_ty.wrappers.empty() ) - throw "ERROR"; - if( array_ty.wrappers.front().type == TypeWrapper::Ty::Array ) - { - ty = array_ty.get_inner(); - base_val.m_offset += ty.get_size() * idx; - return base_val; - } - else if( array_ty.wrappers.front().type == TypeWrapper::Ty::Slice ) - { - throw "TODO"; - } - else - { - throw "ERROR"; - } - } break; - TU_ARM(lv, Field, e) { - ::HIR::TypeRef composite_ty; - auto base_val = get_value_and_type(*e.val, composite_ty); - // TODO: if there's metadata present in the base, but the inner doesn't have metadata, clear the metadata - size_t inner_ofs; - ty = composite_ty.get_field(e.field_index, inner_ofs); - LOG_DEBUG("Field - " << composite_ty << "#" << e.field_index << " = @" << inner_ofs << " " << ty); - base_val.m_offset += inner_ofs; - if( ty.get_meta_type() == HIR::TypeRef(RawType::Unreachable) ) - { - LOG_ASSERT(base_val.m_size >= ty.get_size(), "Field didn't fit in the value - " << ty.get_size() << " required, but " << base_val.m_size << " avail"); - base_val.m_size = ty.get_size(); - } - return base_val; - } - TU_ARM(lv, Downcast, e) { - ::HIR::TypeRef composite_ty; - auto base_val = get_value_and_type(*e.val, composite_ty); - LOG_DEBUG("Downcast - " << composite_ty); - - size_t inner_ofs; - ty = composite_ty.get_field(e.variant_index, inner_ofs); - base_val.m_offset += inner_ofs; - return base_val; - } - TU_ARM(lv, Deref, e) { - ::HIR::TypeRef ptr_ty; - auto val = get_value_and_type(*e.val, ptr_ty); - ty = ptr_ty.get_inner(); - LOG_DEBUG("val = " << val << ", (inner) ty=" << ty); - - LOG_ASSERT(val.m_size >= POINTER_SIZE, "Deref of a value that doesn't fit a pointer - " << ty); - size_t ofs = val.read_usize(0); - - // There MUST be a relocation at this point with a valid allocation. - auto& val_alloc = val.m_alloc ? val.m_alloc : val.m_value->allocation; - LOG_ASSERT(val_alloc, "Deref of a value with no allocation (hence no relocations)"); - LOG_ASSERT(val_alloc.is_alloc(), "Deref of a value with a non-data allocation"); - LOG_TRACE("Deref " << val_alloc.alloc() << " + " << ofs << " to give value of type " << ty); - auto alloc = val_alloc.alloc().get_relocation(val.m_offset); - // NOTE: No alloc can happen when dereferencing a zero-sized pointer - if( alloc.is_alloc() ) - { - LOG_DEBUG("> " << lv << " alloc=" << alloc.alloc()); - } - size_t size; - - const auto meta_ty = ty.get_meta_type(); - ::std::shared_ptr meta_val; - // If the type has metadata, store it. - if( meta_ty != RawType::Unreachable ) - { - auto meta_size = meta_ty.get_size(); - LOG_ASSERT(val.m_size == POINTER_SIZE + meta_size, "Deref of " << ty << ", but pointer isn't correct size"); - meta_val = ::std::make_shared( val.read_value(POINTER_SIZE, meta_size) ); + //LOG_DEBUG(lv << " = " << val); + ::HIR::TypeRef ty; + auto base_value = get_value_and_type(lv, ty); - // TODO: Get a more sane size from the metadata - if( alloc ) - { - LOG_DEBUG("> Meta " << *meta_val << ", size = " << alloc.get_size() << " - " << ofs); - size = alloc.get_size() - ofs; - } - else - { - size = 0; - } - } - else - { - LOG_ASSERT(val.m_size == POINTER_SIZE, "Deref of a value that isn't a pointer-sized value (size=" << val.m_size << ") - " << val << ": " << ptr_ty); - size = ty.get_size(); - if( !alloc ) { - LOG_ERROR("Deref of a value with no relocation - " << val); - } - } - - LOG_DEBUG("alloc=" << alloc << ", ofs=" << ofs << ", size=" << size); - auto rv = ValueRef(::std::move(alloc), ofs, size); - rv.m_metadata = ::std::move(meta_val); - return rv; - } break; - } - throw ""; - } - ValueRef get_value_ref(const ::MIR::LValue& lv) - { - ::HIR::TypeRef tmp; - return get_value_and_type(lv, tmp); + if(base_value.m_alloc) { + base_value.m_alloc.alloc().write_value(base_value.m_offset, ::std::move(val)); } - - ::HIR::TypeRef get_lvalue_ty(const ::MIR::LValue& lv) - { - ::HIR::TypeRef ty; - get_value_and_type(lv, ty); - return ty; + else { + base_value.m_value->write_value(base_value.m_offset, ::std::move(val)); } + } - Value read_lvalue_with_ty(const ::MIR::LValue& lv, ::HIR::TypeRef& ty) - { - auto base_value = get_value_and_type(lv, ty); - - return base_value.read_value(0, ty.get_size()); - } - Value read_lvalue(const ::MIR::LValue& lv) - { - ::HIR::TypeRef ty; - return read_lvalue_with_ty(lv, ty); - } - void write_lvalue(const ::MIR::LValue& lv, Value val) + Value const_to_value(const ::MIR::Constant& c, ::HIR::TypeRef& ty) + { + switch(c.tag()) { - //LOG_DEBUG(lv << " = " << val); - ::HIR::TypeRef ty; - auto base_value = get_value_and_type(lv, ty); - - if(base_value.m_alloc) { - base_value.m_alloc.alloc().write_value(base_value.m_offset, ::std::move(val)); + case ::MIR::Constant::TAGDEAD: throw ""; + TU_ARM(c, Int, ce) { + ty = ::HIR::TypeRef(ce.t); + Value val = Value(ty); + val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian + // TODO: If the write was clipped, sign-extend + return val; + } break; + TU_ARM(c, Uint, ce) { + ty = ::HIR::TypeRef(ce.t); + Value val = Value(ty); + val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian + return val; + } break; + TU_ARM(c, Bool, ce) { + Value val = Value(::HIR::TypeRef { RawType::Bool }); + val.write_bytes(0, &ce.v, 1); + return val; + } break; + TU_ARM(c, Float, ce) { + ty = ::HIR::TypeRef(ce.t); + Value val = Value(ty); + if( ce.t.raw_type == RawType::F64 ) { + val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian/format? + } + else if( ce.t.raw_type == RawType::F32 ) { + float v = static_cast(ce.v); + val.write_bytes(0, &v, ::std::min(ty.get_size(), sizeof(v))); // TODO: Endian/format? } else { - base_value.m_value->write_value(base_value.m_offset, ::std::move(val)); + throw ::std::runtime_error("BUG: Invalid type in Constant::Float"); } - } - - Value const_to_value(const ::MIR::Constant& c, ::HIR::TypeRef& ty) - { - switch(c.tag()) - { - case ::MIR::Constant::TAGDEAD: throw ""; - TU_ARM(c, Int, ce) { - ty = ::HIR::TypeRef(ce.t); - Value val = Value(ty); - val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian - // TODO: If the write was clipped, sign-extend - return val; - } break; - TU_ARM(c, Uint, ce) { - ty = ::HIR::TypeRef(ce.t); - Value val = Value(ty); - val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian - return val; - } break; - TU_ARM(c, Bool, ce) { - Value val = Value(::HIR::TypeRef { RawType::Bool }); - val.write_bytes(0, &ce.v, 1); - return val; - } break; - TU_ARM(c, Float, ce) { - ty = ::HIR::TypeRef(ce.t); - Value val = Value(ty); - if( ce.t.raw_type == RawType::F64 ) { - val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian/format? - } - else if( ce.t.raw_type == RawType::F32 ) { - float v = static_cast(ce.v); - val.write_bytes(0, &v, ::std::min(ty.get_size(), sizeof(v))); // TODO: Endian/format? - } - else { - throw ::std::runtime_error("BUG: Invalid type in Constant::Float"); - } - return val; - } break; - TU_ARM(c, Const, ce) { - LOG_BUG("Constant::Const in mmir"); - } break; - TU_ARM(c, Bytes, ce) { - LOG_TODO("Constant::Bytes"); - } break; - TU_ARM(c, StaticString, ce) { - ty = ::HIR::TypeRef(RawType::Str); + return val; + } break; + TU_ARM(c, Const, ce) { + LOG_BUG("Constant::Const in mmir"); + } break; + TU_ARM(c, Bytes, ce) { + LOG_TODO("Constant::Bytes"); + } break; + TU_ARM(c, StaticString, ce) { + ty = ::HIR::TypeRef(RawType::Str); + ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); + Value val = Value(ty); + val.write_usize(0, 0); + val.write_usize(POINTER_SIZE, ce.size()); + val.allocation.alloc().relocations.push_back(Relocation { 0, AllocationPtr::new_string(&ce) }); + LOG_DEBUG(c << " = " << val); + //return Value::new_dataptr(ce.data()); + return val; + } break; + // --> Accessor + TU_ARM(c, ItemAddr, ce) { + // Create a value with a special backing allocation of zero size that references the specified item. + if( /*const auto* fn =*/ this->thread.m_modtree.get_function_opt(ce) ) { + ty = ::HIR::TypeRef(RawType::Function); + return Value::new_fnptr(ce); + } + if( const auto* s = this->thread.m_modtree.get_static_opt(ce) ) { + ty = s->ty; ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); Value val = Value(ty); val.write_usize(0, 0); - val.write_usize(POINTER_SIZE, ce.size()); - val.allocation.alloc().relocations.push_back(Relocation { 0, AllocationPtr::new_string(&ce) }); - LOG_DEBUG(c << " = " << val); - //return Value::new_dataptr(ce.data()); + val.allocation.alloc().relocations.push_back(Relocation { 0, s->val.allocation }); return val; - } break; - TU_ARM(c, ItemAddr, ce) { - // Create a value with a special backing allocation of zero size that references the specified item. - if( /*const auto* fn =*/ modtree.get_function_opt(ce) ) { - ty = ::HIR::TypeRef(RawType::Function); - return Value::new_fnptr(ce); - } - if( const auto* s = modtree.get_static_opt(ce) ) { - ty = s->ty; - ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); - Value val = Value(ty); - val.write_usize(0, 0); - val.allocation.alloc().relocations.push_back(Relocation { 0, s->val.allocation }); - return val; - } - LOG_TODO("Constant::ItemAddr - " << ce << " - not found"); - } break; } - throw ""; - } - Value const_to_value(const ::MIR::Constant& c) - { - ::HIR::TypeRef ty; - return const_to_value(c, ty); - } - Value param_to_value(const ::MIR::Param& p, ::HIR::TypeRef& ty) - { - switch(p.tag()) - { - case ::MIR::Param::TAGDEAD: throw ""; - TU_ARM(p, Constant, pe) - return const_to_value(pe, ty); - TU_ARM(p, LValue, pe) - return read_lvalue_with_ty(pe, ty); - } - throw ""; + LOG_ERROR("Constant::ItemAddr - " << ce << " - not found"); + } break; } - Value param_to_value(const ::MIR::Param& p) + throw ""; + } + Value const_to_value(const ::MIR::Constant& c) + { + ::HIR::TypeRef ty; + return const_to_value(c, ty); + } + Value param_to_value(const ::MIR::Param& p, ::HIR::TypeRef& ty) + { + switch(p.tag()) { - ::HIR::TypeRef ty; - return param_to_value(p, ty); + case ::MIR::Param::TAGDEAD: throw ""; + TU_ARM(p, Constant, pe) + return const_to_value(pe, ty); + TU_ARM(p, LValue, pe) + return read_lvalue_with_ty(pe, ty); } + throw ""; + } + Value param_to_value(const ::MIR::Param& p) + { + ::HIR::TypeRef ty; + return param_to_value(p, ty); + } - ValueRef get_value_ref_param(const ::MIR::Param& p, Value& tmp, ::HIR::TypeRef& ty) + ValueRef get_value_ref_param(const ::MIR::Param& p, Value& tmp, ::HIR::TypeRef& ty) + { + switch(p.tag()) { - switch(p.tag()) - { - case ::MIR::Param::TAGDEAD: throw ""; - TU_ARM(p, Constant, pe) - tmp = const_to_value(pe, ty); - return ValueRef(tmp, 0, ty.get_size()); - TU_ARM(p, LValue, pe) - return get_value_and_type(pe, ty); - } - throw ""; + case ::MIR::Param::TAGDEAD: throw ""; + TU_ARM(p, Constant, pe) + tmp = const_to_value(pe, ty); + return ValueRef(tmp, 0, ty.get_size()); + TU_ARM(p, LValue, pe) + return get_value_and_type(pe, ty); } - } state { modtree, fcn, ret, ::std::move(args) }; + throw ""; + } +}; - size_t bb_idx = 0; - for(;;) +// ==================================================================== +// +// ==================================================================== +InterpreterThread::~InterpreterThread() +{ + for(size_t i = 0; i < m_stack.size(); i++) + { + const auto& frame = m_stack[m_stack.size() - 1 - i]; + ::std::cout << "#" << i << ": " << frame.fcn.my_path << " BB" << frame.bb_idx << "/"; + if( frame.stmt_idx == frame.fcn.m_mir.blocks.at(frame.bb_idx).statements.size() ) + ::std::cout << "TERM"; + else + ::std::cout << frame.stmt_idx; + ::std::cout << ::std::endl; + } +} +void InterpreterThread::start(const ::HIR::Path& p, ::std::vector args) +{ + Value v; + if( this->call_path(v, p, ::std::move(args)) ) { - const auto& bb = fcn.m_mir.blocks.at(bb_idx); + LOG_TODO("Handle immediate return thread entry"); + } +} +bool InterpreterThread::step_one(Value& out_thread_result) +{ + assert( !this->m_stack.empty() ); + assert( !this->m_stack.back().cb ); + auto& cur_frame = this->m_stack.back(); + TRACE_FUNCTION_R(cur_frame.fcn.my_path, ""); + const auto& bb = cur_frame.fcn.m_mir.blocks.at( cur_frame.bb_idx ); - for(const auto& stmt : bb.statements) + MirHelpers state { *this, cur_frame }; + + if( cur_frame.stmt_idx < bb.statements.size() ) + { + const auto& stmt = bb.statements[cur_frame.stmt_idx]; + LOG_DEBUG("=== BB" << cur_frame.bb_idx << "/" << cur_frame.stmt_idx << ": " << stmt); + switch(stmt.tag()) { - LOG_DEBUG("=== BB" << bb_idx << "/" << (&stmt - bb.statements.data()) << ": " << stmt); - switch(stmt.tag()) + case ::MIR::Statement::TAGDEAD: throw ""; + TU_ARM(stmt, Assign, se) { + Value new_val; + switch(se.src.tag()) { - case ::MIR::Statement::TAGDEAD: throw ""; - TU_ARM(stmt, Assign, se) { - Value new_val; - switch(se.src.tag()) + case ::MIR::RValue::TAGDEAD: throw ""; + TU_ARM(se.src, Use, re) { + new_val = state.read_lvalue(re); + } break; + TU_ARM(se.src, Constant, re) { + new_val = state.const_to_value(re); + } break; + TU_ARM(se.src, Borrow, re) { + ::HIR::TypeRef src_ty; + ValueRef src_base_value = state.get_value_and_type(re.val, src_ty); + auto alloc = src_base_value.m_alloc; + if( !alloc && src_base_value.m_value ) { - case ::MIR::RValue::TAGDEAD: throw ""; - TU_ARM(se.src, Use, re) { - new_val = state.read_lvalue(re); - } break; - TU_ARM(se.src, Constant, re) { - new_val = state.const_to_value(re); - } break; - TU_ARM(se.src, Borrow, re) { - ::HIR::TypeRef src_ty; - ValueRef src_base_value = state.get_value_and_type(re.val, src_ty); - auto alloc = src_base_value.m_alloc; - if( !alloc && src_base_value.m_value ) - { - if( !src_base_value.m_value->allocation ) - { - src_base_value.m_value->create_allocation(); - } - alloc = AllocationPtr(src_base_value.m_value->allocation); - } - if( alloc.is_alloc() ) - LOG_DEBUG("- alloc=" << alloc << " (" << alloc.alloc() << ")"); - else - LOG_DEBUG("- alloc=" << alloc); - size_t ofs = src_base_value.m_offset; - const auto meta = src_ty.get_meta_type(); - //bool is_slice_like = src_ty.has_slice_meta(); - src_ty.wrappers.insert(src_ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, static_cast(re.type) }); - - new_val = Value(src_ty); - // ^ Pointer value - new_val.write_usize(0, ofs); - if( meta != RawType::Unreachable ) + if( !src_base_value.m_value->allocation ) { - LOG_ASSERT(src_base_value.m_metadata, "Borrow of an unsized value, but no metadata avaliable"); - new_val.write_value(POINTER_SIZE, *src_base_value.m_metadata); + src_base_value.m_value->create_allocation(); } - // - Add the relocation after writing the value (writing clears the relocations) - new_val.allocation.alloc().relocations.push_back(Relocation { 0, ::std::move(alloc) }); - } break; - TU_ARM(se.src, Cast, re) { - // Determine the type of cast, is it a reinterpret or is it a value transform? - // - Float <-> integer is a transform, anything else should be a reinterpret. - ::HIR::TypeRef src_ty; - auto src_value = state.get_value_and_type(re.val, src_ty); - - new_val = Value(re.type); - if( re.type == src_ty ) - { - // No-op cast - new_val = src_value.read_value(0, re.type.get_size()); + alloc = AllocationPtr(src_base_value.m_value->allocation); + } + if( alloc.is_alloc() ) + LOG_DEBUG("- alloc=" << alloc << " (" << alloc.alloc() << ")"); + else + LOG_DEBUG("- alloc=" << alloc); + size_t ofs = src_base_value.m_offset; + const auto meta = src_ty.get_meta_type(); + //bool is_slice_like = src_ty.has_slice_meta(); + src_ty.wrappers.insert(src_ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, static_cast(re.type) }); + + new_val = Value(src_ty); + // ^ Pointer value + new_val.write_usize(0, ofs); + if( meta != RawType::Unreachable ) + { + LOG_ASSERT(src_base_value.m_metadata, "Borrow of an unsized value, but no metadata avaliable"); + new_val.write_value(POINTER_SIZE, *src_base_value.m_metadata); + } + // - Add the relocation after writing the value (writing clears the relocations) + new_val.allocation.alloc().relocations.push_back(Relocation { 0, ::std::move(alloc) }); + } break; + TU_ARM(se.src, Cast, re) { + // Determine the type of cast, is it a reinterpret or is it a value transform? + // - Float <-> integer is a transform, anything else should be a reinterpret. + ::HIR::TypeRef src_ty; + auto src_value = state.get_value_and_type(re.val, src_ty); + + new_val = Value(re.type); + if( re.type == src_ty ) + { + // No-op cast + new_val = src_value.read_value(0, re.type.get_size()); + } + else if( !re.type.wrappers.empty() ) + { + // Destination can only be a raw pointer + if( re.type.wrappers.at(0).type != TypeWrapper::Ty::Pointer ) { + throw "ERROR"; } - else if( !re.type.wrappers.empty() ) + if( !src_ty.wrappers.empty() ) { - // Destination can only be a raw pointer - if( re.type.wrappers.at(0).type != TypeWrapper::Ty::Pointer ) { + // Source can be either + if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer + && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { throw "ERROR"; } - if( !src_ty.wrappers.empty() ) - { - // Source can be either - if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer - && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { - throw "ERROR"; - } - if( src_ty.get_size() > re.type.get_size() ) { - // TODO: How to casting fat to thin? - //LOG_TODO("Handle casting fat to thin, " << src_ty << " -> " << re.type); - new_val = src_value.read_value(0, re.type.get_size()); - } - else - { - new_val = src_value.read_value(0, re.type.get_size()); - } + if( src_ty.get_size() > re.type.get_size() ) { + // TODO: How to casting fat to thin? + //LOG_TODO("Handle casting fat to thin, " << src_ty << " -> " << re.type); + new_val = src_value.read_value(0, re.type.get_size()); } - else + else { - if( src_ty == RawType::Function ) - { - } - else if( src_ty == RawType::USize ) - { - } - else - { - ::std::cerr << "ERROR: Trying to pointer (" << re.type <<" ) from invalid type (" << src_ty << ")\n"; - throw "ERROR"; - } new_val = src_value.read_value(0, re.type.get_size()); } } - else if( !src_ty.wrappers.empty() ) + else { - // TODO: top wrapper MUST be a pointer - if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer - && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { - throw "ERROR"; + if( src_ty == RawType::Function ) + { } - // TODO: MUST be a thin pointer? - - // TODO: MUST be an integer (usize only?) - if( re.type != RawType::USize && re.type != RawType::ISize ) { - LOG_ERROR("Casting from a pointer to non-usize - " << re.type << " to " << src_ty); + else if( src_ty == RawType::USize ) + { + } + else + { + ::std::cerr << "ERROR: Trying to pointer (" << re.type <<" ) from invalid type (" << src_ty << ")\n"; throw "ERROR"; } new_val = src_value.read_value(0, re.type.get_size()); } - else + } + else if( !src_ty.wrappers.empty() ) + { + // TODO: top wrapper MUST be a pointer + if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer + && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { + throw "ERROR"; + } + // TODO: MUST be a thin pointer? + + // TODO: MUST be an integer (usize only?) + if( re.type != RawType::USize && re.type != RawType::ISize ) { + LOG_ERROR("Casting from a pointer to non-usize - " << re.type << " to " << src_ty); + throw "ERROR"; + } + new_val = src_value.read_value(0, re.type.get_size()); + } + else + { + // TODO: What happens if there'a cast of something with a relocation? + switch(re.type.inner_type) { - // TODO: What happens if there'a cast of something with a relocation? - switch(re.type.inner_type) + case RawType::Unreachable: throw "BUG"; + case RawType::Composite: + case RawType::TraitObject: + case RawType::Function: + case RawType::Str: + case RawType::Unit: + LOG_ERROR("Casting to " << re.type << " is invalid"); + throw "ERROR"; + case RawType::F32: { + float dst_val = 0.0; + // Can be an integer, or F64 (pointer is impossible atm) + switch(src_ty.inner_type) + { + case RawType::Unreachable: throw "BUG"; + case RawType::Composite: throw "ERROR"; + case RawType::TraitObject: throw "ERROR"; + case RawType::Function: throw "ERROR"; + case RawType::Char: throw "ERROR"; + case RawType::Str: throw "ERROR"; + case RawType::Unit: throw "ERROR"; + case RawType::Bool: throw "ERROR"; + case RawType::F32: throw "BUG"; + case RawType::F64: dst_val = static_cast( src_value.read_f64(0) ); break; + case RawType::USize: throw "TODO";// /*dst_val = src_value.read_usize();*/ break; + case RawType::ISize: throw "TODO";// /*dst_val = src_value.read_isize();*/ break; + case RawType::U8: dst_val = static_cast( src_value.read_u8 (0) ); break; + case RawType::I8: dst_val = static_cast( src_value.read_i8 (0) ); break; + case RawType::U16: dst_val = static_cast( src_value.read_u16(0) ); break; + case RawType::I16: dst_val = static_cast( src_value.read_i16(0) ); break; + case RawType::U32: dst_val = static_cast( src_value.read_u32(0) ); break; + case RawType::I32: dst_val = static_cast( src_value.read_i32(0) ); break; + case RawType::U64: dst_val = static_cast( src_value.read_u64(0) ); break; + case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); break; + case RawType::U128: throw "TODO";// /*dst_val = src_value.read_u128();*/ break; + case RawType::I128: throw "TODO";// /*dst_val = src_value.read_i128();*/ break; + } + new_val.write_f32(0, dst_val); + } break; + case RawType::F64: { + double dst_val = 0.0; + // Can be an integer, or F32 (pointer is impossible atm) + switch(src_ty.inner_type) { case RawType::Unreachable: throw "BUG"; - case RawType::Composite: + case RawType::Composite: throw "ERROR"; + case RawType::TraitObject: throw "ERROR"; + case RawType::Function: throw "ERROR"; + case RawType::Char: throw "ERROR"; + case RawType::Str: throw "ERROR"; + case RawType::Unit: throw "ERROR"; + case RawType::Bool: throw "ERROR"; + case RawType::F64: throw "BUG"; + case RawType::F32: dst_val = static_cast( src_value.read_f32(0) ); break; + case RawType::USize: dst_val = static_cast( src_value.read_usize(0) ); break; + case RawType::ISize: dst_val = static_cast( src_value.read_isize(0) ); break; + case RawType::U8: dst_val = static_cast( src_value.read_u8 (0) ); break; + case RawType::I8: dst_val = static_cast( src_value.read_i8 (0) ); break; + case RawType::U16: dst_val = static_cast( src_value.read_u16(0) ); break; + case RawType::I16: dst_val = static_cast( src_value.read_i16(0) ); break; + case RawType::U32: dst_val = static_cast( src_value.read_u32(0) ); break; + case RawType::I32: dst_val = static_cast( src_value.read_i32(0) ); break; + case RawType::U64: dst_val = static_cast( src_value.read_u64(0) ); break; + case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); break; + case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break; + case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break; + } + new_val.write_f64(0, dst_val); + } break; + case RawType::Bool: + LOG_TODO("Cast to " << re.type); + case RawType::Char: + LOG_TODO("Cast to " << re.type); + case RawType::USize: + case RawType::U8: + case RawType::U16: + case RawType::U32: + case RawType::U64: + case RawType::ISize: + case RawType::I8: + case RawType::I16: + case RawType::I32: + case RawType::I64: + { + uint64_t dst_val = 0; + // Can be an integer, or F32 (pointer is impossible atm) + switch(src_ty.inner_type) + { + case RawType::Unreachable: + LOG_BUG("Casting unreachable"); case RawType::TraitObject: - case RawType::Function: case RawType::Str: + LOG_FATAL("Cast of unsized type - " << src_ty); + case RawType::Function: + LOG_ASSERT(re.type.inner_type == RawType::USize, "Function pointers can only be casted to usize, instead " << re.type); + new_val = src_value.read_value(0, re.type.get_size()); + break; + case RawType::Char: + LOG_ASSERT(re.type.inner_type == RawType::U32, "Char can only be casted to u32, instead " << re.type); + new_val = src_value.read_value(0, 4); + break; case RawType::Unit: - LOG_ERROR("Casting to " << re.type << " is invalid"); - throw "ERROR"; - case RawType::F32: { - float dst_val = 0.0; - // Can be an integer, or F64 (pointer is impossible atm) - switch(src_ty.inner_type) - { - case RawType::Unreachable: throw "BUG"; - case RawType::Composite: throw "ERROR"; - case RawType::TraitObject: throw "ERROR"; - case RawType::Function: throw "ERROR"; - case RawType::Char: throw "ERROR"; - case RawType::Str: throw "ERROR"; - case RawType::Unit: throw "ERROR"; - case RawType::Bool: throw "ERROR"; - case RawType::F32: throw "BUG"; - case RawType::F64: dst_val = static_cast( src_value.read_f64(0) ); break; - case RawType::USize: throw "TODO";// /*dst_val = src_value.read_usize();*/ break; - case RawType::ISize: throw "TODO";// /*dst_val = src_value.read_isize();*/ break; - case RawType::U8: dst_val = static_cast( src_value.read_u8 (0) ); break; - case RawType::I8: dst_val = static_cast( src_value.read_i8 (0) ); break; - case RawType::U16: dst_val = static_cast( src_value.read_u16(0) ); break; - case RawType::I16: dst_val = static_cast( src_value.read_i16(0) ); break; - case RawType::U32: dst_val = static_cast( src_value.read_u32(0) ); break; - case RawType::I32: dst_val = static_cast( src_value.read_i32(0) ); break; - case RawType::U64: dst_val = static_cast( src_value.read_u64(0) ); break; - case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); break; - case RawType::U128: throw "TODO";// /*dst_val = src_value.read_u128();*/ break; - case RawType::I128: throw "TODO";// /*dst_val = src_value.read_i128();*/ break; + LOG_FATAL("Cast of unit"); + case RawType::Composite: { + const auto& dt = *src_ty.composite_type; + if( dt.variants.size() == 0 ) { + LOG_FATAL("Cast of composite - " << src_ty); } - new_val.write_f32(0, dst_val); - } break; - case RawType::F64: { - double dst_val = 0.0; - // Can be an integer, or F32 (pointer is impossible atm) - switch(src_ty.inner_type) - { - case RawType::Unreachable: throw "BUG"; - case RawType::Composite: throw "ERROR"; - case RawType::TraitObject: throw "ERROR"; - case RawType::Function: throw "ERROR"; - case RawType::Char: throw "ERROR"; - case RawType::Str: throw "ERROR"; - case RawType::Unit: throw "ERROR"; - case RawType::Bool: throw "ERROR"; - case RawType::F64: throw "BUG"; - case RawType::F32: dst_val = static_cast( src_value.read_f32(0) ); break; - case RawType::USize: dst_val = static_cast( src_value.read_usize(0) ); break; - case RawType::ISize: dst_val = static_cast( src_value.read_isize(0) ); break; - case RawType::U8: dst_val = static_cast( src_value.read_u8 (0) ); break; - case RawType::I8: dst_val = static_cast( src_value.read_i8 (0) ); break; - case RawType::U16: dst_val = static_cast( src_value.read_u16(0) ); break; - case RawType::I16: dst_val = static_cast( src_value.read_i16(0) ); break; - case RawType::U32: dst_val = static_cast( src_value.read_u32(0) ); break; - case RawType::I32: dst_val = static_cast( src_value.read_i32(0) ); break; - case RawType::U64: dst_val = static_cast( src_value.read_u64(0) ); break; - case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); break; - case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break; - case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break; + // TODO: Check that all variants have the same tag offset + LOG_ASSERT(dt.fields.size() == 1, ""); + LOG_ASSERT(dt.fields[0].first == 0, ""); + for(size_t i = 0; i < dt.variants.size(); i ++ ) { + LOG_ASSERT(dt.variants[i].base_field == 0, ""); + LOG_ASSERT(dt.variants[i].field_path.empty(), ""); } - new_val.write_f64(0, dst_val); - } break; - case RawType::Bool: - LOG_TODO("Cast to " << re.type); - case RawType::Char: - LOG_TODO("Cast to " << re.type); - case RawType::USize: - case RawType::U8: - case RawType::U16: - case RawType::U32: - case RawType::U64: - case RawType::ISize: - case RawType::I8: - case RawType::I16: - case RawType::I32: - case RawType::I64: - { - uint64_t dst_val = 0; - // Can be an integer, or F32 (pointer is impossible atm) - switch(src_ty.inner_type) + ::HIR::TypeRef tag_ty = dt.fields[0].second; + LOG_ASSERT(tag_ty.wrappers.empty(), ""); + switch(tag_ty.inner_type) { - case RawType::Unreachable: - LOG_BUG("Casting unreachable"); - case RawType::TraitObject: - case RawType::Str: - LOG_FATAL("Cast of unsized type - " << src_ty); - case RawType::Function: - LOG_ASSERT(re.type.inner_type == RawType::USize, "Function pointers can only be casted to usize, instead " << re.type); - new_val = src_value.read_value(0, re.type.get_size()); - break; - case RawType::Char: - LOG_ASSERT(re.type.inner_type == RawType::U32, "Char can only be casted to u32, instead " << re.type); - new_val = src_value.read_value(0, 4); - break; - case RawType::Unit: - LOG_FATAL("Cast of unit"); - case RawType::Composite: { - const auto& dt = *src_ty.composite_type; - if( dt.variants.size() == 0 ) { - LOG_FATAL("Cast of composite - " << src_ty); - } - // TODO: Check that all variants have the same tag offset - LOG_ASSERT(dt.fields.size() == 1, ""); - LOG_ASSERT(dt.fields[0].first == 0, ""); - for(size_t i = 0; i < dt.variants.size(); i ++ ) { - LOG_ASSERT(dt.variants[i].base_field == 0, ""); - LOG_ASSERT(dt.variants[i].field_path.empty(), ""); - } - ::HIR::TypeRef tag_ty = dt.fields[0].second; - LOG_ASSERT(tag_ty.wrappers.empty(), ""); - switch(tag_ty.inner_type) - { - case RawType::USize: - dst_val = static_cast( src_value.read_usize(0) ); - if(0) - case RawType::ISize: - dst_val = static_cast( src_value.read_isize(0) ); - if(0) - case RawType::U8: - dst_val = static_cast( src_value.read_u8 (0) ); - if(0) - case RawType::I8: - dst_val = static_cast( src_value.read_i8 (0) ); - if(0) - case RawType::U16: - dst_val = static_cast( src_value.read_u16(0) ); - if(0) - case RawType::I16: - dst_val = static_cast( src_value.read_i16(0) ); - if(0) - case RawType::U32: - dst_val = static_cast( src_value.read_u32(0) ); - if(0) - case RawType::I32: - dst_val = static_cast( src_value.read_i32(0) ); - if(0) - case RawType::U64: - dst_val = static_cast( src_value.read_u64(0) ); - if(0) - case RawType::I64: - dst_val = static_cast( src_value.read_i64(0) ); - break; - default: - LOG_FATAL("Bad tag type in cast - " << tag_ty); - } - } if(0) - case RawType::Bool: - dst_val = static_cast( src_value.read_u8 (0) ); - if(0) - case RawType::F64: - dst_val = static_cast( src_value.read_f64(0) ); - if(0) - case RawType::F32: - dst_val = static_cast( src_value.read_f32(0) ); - if(0) case RawType::USize: dst_val = static_cast( src_value.read_usize(0) ); if(0) @@ -1060,457 +962,503 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: if(0) case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); - - switch(re.type.inner_type) - { - case RawType::USize: - new_val.write_usize(0, dst_val); - break; - case RawType::U8: - new_val.write_u8(0, static_cast(dst_val)); - break; - case RawType::U16: - new_val.write_u16(0, static_cast(dst_val)); - break; - case RawType::U32: - new_val.write_u32(0, static_cast(dst_val)); - break; - case RawType::U64: - new_val.write_u64(0, dst_val); - break; - case RawType::ISize: - new_val.write_usize(0, static_cast(dst_val)); - break; - case RawType::I8: - new_val.write_i8(0, static_cast(dst_val)); - break; - case RawType::I16: - new_val.write_i16(0, static_cast(dst_val)); - break; - case RawType::I32: - new_val.write_i32(0, static_cast(dst_val)); - break; - case RawType::I64: - new_val.write_i64(0, static_cast(dst_val)); - break; - default: - throw ""; - } break; - case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break; - case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break; - } - } break; - case RawType::U128: - case RawType::I128: - LOG_TODO("Cast to " << re.type); - } - } - } break; - TU_ARM(se.src, BinOp, re) { - ::HIR::TypeRef ty_l, ty_r; - Value tmp_l, tmp_r; - auto v_l = state.get_value_ref_param(re.val_l, tmp_l, ty_l); - auto v_r = state.get_value_ref_param(re.val_r, tmp_r, ty_r); - LOG_DEBUG(v_l << " (" << ty_l <<") ? " << v_r << " (" << ty_r <<")"); - - switch(re.op) - { - case ::MIR::eBinOp::EQ: - case ::MIR::eBinOp::NE: - case ::MIR::eBinOp::GT: - case ::MIR::eBinOp::GE: - case ::MIR::eBinOp::LT: - case ::MIR::eBinOp::LE: { - LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); - int res = 0; - // TODO: Handle comparison of the relocations too - - const auto& alloc_l = v_l.m_value ? v_l.m_value->allocation : v_l.m_alloc; - const auto& alloc_r = v_r.m_value ? v_r.m_value->allocation : v_r.m_alloc; - auto reloc_l = alloc_l ? v_l.get_relocation(v_l.m_offset) : AllocationPtr(); - auto reloc_r = alloc_r ? v_r.get_relocation(v_r.m_offset) : AllocationPtr(); - - if( reloc_l != reloc_r ) - { - res = (reloc_l < reloc_r ? -1 : 1); - } - LOG_DEBUG("res=" << res << ", " << reloc_l << " ? " << reloc_r); - - if( ty_l.wrappers.empty() ) - { - switch(ty_l.inner_type) - { - case RawType::U64: res = res != 0 ? res : Ops::do_compare(v_l.read_u64(0), v_r.read_u64(0)); break; - case RawType::U32: res = res != 0 ? res : Ops::do_compare(v_l.read_u32(0), v_r.read_u32(0)); break; - case RawType::U16: res = res != 0 ? res : Ops::do_compare(v_l.read_u16(0), v_r.read_u16(0)); break; - case RawType::U8 : res = res != 0 ? res : Ops::do_compare(v_l.read_u8 (0), v_r.read_u8 (0)); break; - case RawType::I64: res = res != 0 ? res : Ops::do_compare(v_l.read_i64(0), v_r.read_i64(0)); break; - case RawType::I32: res = res != 0 ? res : Ops::do_compare(v_l.read_i32(0), v_r.read_i32(0)); break; - case RawType::I16: res = res != 0 ? res : Ops::do_compare(v_l.read_i16(0), v_r.read_i16(0)); break; - case RawType::I8 : res = res != 0 ? res : Ops::do_compare(v_l.read_i8 (0), v_r.read_i8 (0)); break; - case RawType::USize: res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); break; - case RawType::ISize: res = res != 0 ? res : Ops::do_compare(v_l.read_isize(0), v_r.read_isize(0)); break; default: - LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); + LOG_FATAL("Bad tag type in cast - " << tag_ty); } - } - else if( ty_l.wrappers.front().type == TypeWrapper::Ty::Pointer ) - { - // TODO: Technically only EQ/NE are valid. - - res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); + } if(0) + case RawType::Bool: + dst_val = static_cast( src_value.read_u8 (0) ); + if(0) + case RawType::F64: + dst_val = static_cast( src_value.read_f64(0) ); + if(0) + case RawType::F32: + dst_val = static_cast( src_value.read_f32(0) ); + if(0) + case RawType::USize: + dst_val = static_cast( src_value.read_usize(0) ); + if(0) + case RawType::ISize: + dst_val = static_cast( src_value.read_isize(0) ); + if(0) + case RawType::U8: + dst_val = static_cast( src_value.read_u8 (0) ); + if(0) + case RawType::I8: + dst_val = static_cast( src_value.read_i8 (0) ); + if(0) + case RawType::U16: + dst_val = static_cast( src_value.read_u16(0) ); + if(0) + case RawType::I16: + dst_val = static_cast( src_value.read_i16(0) ); + if(0) + case RawType::U32: + dst_val = static_cast( src_value.read_u32(0) ); + if(0) + case RawType::I32: + dst_val = static_cast( src_value.read_i32(0) ); + if(0) + case RawType::U64: + dst_val = static_cast( src_value.read_u64(0) ); + if(0) + case RawType::I64: + dst_val = static_cast( src_value.read_i64(0) ); - // Compare fat metadata. - if( res == 0 && v_l.m_size > POINTER_SIZE ) + switch(re.type.inner_type) { - reloc_l = alloc_l ? alloc_l.alloc().get_relocation(POINTER_SIZE) : AllocationPtr(); - reloc_r = alloc_r ? alloc_r.alloc().get_relocation(POINTER_SIZE) : AllocationPtr(); - - if( res == 0 && reloc_l != reloc_r ) - { - res = (reloc_l < reloc_r ? -1 : 1); - } - res = res != 0 ? res : Ops::do_compare(v_l.read_usize(POINTER_SIZE), v_r.read_usize(POINTER_SIZE)); + case RawType::USize: + new_val.write_usize(0, dst_val); + break; + case RawType::U8: + new_val.write_u8(0, static_cast(dst_val)); + break; + case RawType::U16: + new_val.write_u16(0, static_cast(dst_val)); + break; + case RawType::U32: + new_val.write_u32(0, static_cast(dst_val)); + break; + case RawType::U64: + new_val.write_u64(0, dst_val); + break; + case RawType::ISize: + new_val.write_usize(0, static_cast(dst_val)); + break; + case RawType::I8: + new_val.write_i8(0, static_cast(dst_val)); + break; + case RawType::I16: + new_val.write_i16(0, static_cast(dst_val)); + break; + case RawType::I32: + new_val.write_i32(0, static_cast(dst_val)); + break; + case RawType::I64: + new_val.write_i64(0, static_cast(dst_val)); + break; + default: + throw ""; } - } - else - { - LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); - } - bool res_bool; - switch(re.op) - { - case ::MIR::eBinOp::EQ: res_bool = (res == 0); break; - case ::MIR::eBinOp::NE: res_bool = (res != 0); break; - case ::MIR::eBinOp::GT: res_bool = (res == 1); break; - case ::MIR::eBinOp::GE: res_bool = (res == 1 || res == 0); break; - case ::MIR::eBinOp::LT: res_bool = (res == -1); break; - case ::MIR::eBinOp::LE: res_bool = (res == -1 || res == 0); break; break; - default: - LOG_BUG("Unknown comparison"); - } - new_val = Value(::HIR::TypeRef(RawType::Bool)); - new_val.write_u8(0, res_bool ? 1 : 0); - } break; - case ::MIR::eBinOp::BIT_SHL: - case ::MIR::eBinOp::BIT_SHR: { - LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); - LOG_ASSERT(ty_r.wrappers.empty(), "Bitwise operator with non-primitive - " << ty_r); - size_t max_bits = ty_r.get_size() * 8; - uint8_t shift; - auto check_cast = [&](auto v){ LOG_ASSERT(0 <= v && v <= max_bits, "Shift out of range - " << v); return static_cast(v); }; - switch(ty_r.inner_type) - { - case RawType::U64: shift = check_cast(v_r.read_u64(0)); break; - case RawType::U32: shift = check_cast(v_r.read_u32(0)); break; - case RawType::U16: shift = check_cast(v_r.read_u16(0)); break; - case RawType::U8 : shift = check_cast(v_r.read_u8 (0)); break; - case RawType::I64: shift = check_cast(v_r.read_i64(0)); break; - case RawType::I32: shift = check_cast(v_r.read_i32(0)); break; - case RawType::I16: shift = check_cast(v_r.read_i16(0)); break; - case RawType::I8 : shift = check_cast(v_r.read_i8 (0)); break; - case RawType::USize: shift = check_cast(v_r.read_usize(0)); break; - case RawType::ISize: shift = check_cast(v_r.read_isize(0)); break; - default: - LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); - } - new_val = Value(ty_l); - switch(ty_l.inner_type) - { - // TODO: U128 - case RawType::U64: new_val.write_u64(0, Ops::do_bitwise(v_l.read_u64(0), static_cast(shift), re.op)); break; - case RawType::U32: new_val.write_u32(0, Ops::do_bitwise(v_l.read_u32(0), static_cast(shift), re.op)); break; - case RawType::U16: new_val.write_u16(0, Ops::do_bitwise(v_l.read_u16(0), static_cast(shift), re.op)); break; - case RawType::U8 : new_val.write_u8 (0, Ops::do_bitwise(v_l.read_u8 (0), static_cast(shift), re.op)); break; - case RawType::USize: new_val.write_usize(0, Ops::do_bitwise(v_l.read_usize(0), static_cast(shift), re.op)); break; - // TODO: Is signed allowed? - default: - LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); + case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break; + case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break; } } break; - case ::MIR::eBinOp::BIT_AND: - case ::MIR::eBinOp::BIT_OR: - case ::MIR::eBinOp::BIT_XOR: - LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); - LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); - new_val = Value(ty_l); - switch(ty_l.inner_type) - { - // TODO: U128/I128 - case RawType::U64: - case RawType::I64: - new_val.write_u64( 0, Ops::do_bitwise(v_l.read_u64(0), v_r.read_u64(0), re.op) ); - break; - case RawType::U32: - case RawType::I32: - new_val.write_u32( 0, static_cast(Ops::do_bitwise(v_l.read_u32(0), v_r.read_u32(0), re.op)) ); - break; - case RawType::U16: - case RawType::I16: - new_val.write_u16( 0, static_cast(Ops::do_bitwise(v_l.read_u16(0), v_r.read_u16(0), re.op)) ); - break; - case RawType::U8: - case RawType::I8: - new_val.write_u8 ( 0, static_cast(Ops::do_bitwise(v_l.read_u8 (0), v_r.read_u8 (0), re.op)) ); - break; - case RawType::USize: - case RawType::ISize: - new_val.write_usize( 0, Ops::do_bitwise(v_l.read_usize(0), v_r.read_usize(0), re.op) ); - break; - default: - LOG_TODO("BinOp bitwise - " << se.src << " w/ " << ty_l); - } - - break; - default: - LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); - auto val_l = PrimitiveValueVirt::from_value(ty_l, v_l); - auto val_r = PrimitiveValueVirt::from_value(ty_r, v_r); - switch(re.op) - { - case ::MIR::eBinOp::ADD: val_l.get().add( val_r.get() ); break; - case ::MIR::eBinOp::SUB: val_l.get().subtract( val_r.get() ); break; - case ::MIR::eBinOp::MUL: val_l.get().multiply( val_r.get() ); break; - case ::MIR::eBinOp::DIV: val_l.get().divide( val_r.get() ); break; - case ::MIR::eBinOp::MOD: val_l.get().modulo( val_r.get() ); break; - - default: - LOG_TODO("Unsupported binary operator?"); - } - new_val = Value(ty_l); - val_l.get().write_to_value(new_val, 0); - break; + case RawType::U128: + case RawType::I128: + LOG_TODO("Cast to " << re.type); } - } break; - TU_ARM(se.src, UniOp, re) { - ::HIR::TypeRef ty; - auto v = state.get_value_and_type(re.val, ty); - LOG_ASSERT(ty.wrappers.empty(), "UniOp on wrapped type - " << ty); - new_val = Value(ty); - switch(re.op) + } + } break; + TU_ARM(se.src, BinOp, re) { + ::HIR::TypeRef ty_l, ty_r; + Value tmp_l, tmp_r; + auto v_l = state.get_value_ref_param(re.val_l, tmp_l, ty_l); + auto v_r = state.get_value_ref_param(re.val_r, tmp_r, ty_r); + LOG_DEBUG(v_l << " (" << ty_l <<") ? " << v_r << " (" << ty_r <<")"); + + switch(re.op) + { + case ::MIR::eBinOp::EQ: + case ::MIR::eBinOp::NE: + case ::MIR::eBinOp::GT: + case ::MIR::eBinOp::GE: + case ::MIR::eBinOp::LT: + case ::MIR::eBinOp::LE: { + LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); + int res = 0; + // TODO: Handle comparison of the relocations too + + const auto& alloc_l = v_l.m_value ? v_l.m_value->allocation : v_l.m_alloc; + const auto& alloc_r = v_r.m_value ? v_r.m_value->allocation : v_r.m_alloc; + auto reloc_l = alloc_l ? v_l.get_relocation(v_l.m_offset) : AllocationPtr(); + auto reloc_r = alloc_r ? v_r.get_relocation(v_r.m_offset) : AllocationPtr(); + + if( reloc_l != reloc_r ) { - case ::MIR::eUniOp::INV: - switch(ty.inner_type) - { - case RawType::U128: - case RawType::I128: - LOG_TODO("UniOp::INV U128"); - case RawType::U64: - case RawType::I64: - new_val.write_u64( 0, ~v.read_u64(0) ); - break; - case RawType::U32: - case RawType::I32: - new_val.write_u32( 0, ~v.read_u32(0) ); - break; - case RawType::U16: - case RawType::I16: - new_val.write_u16( 0, ~v.read_u16(0) ); - break; - case RawType::U8: - case RawType::I8: - new_val.write_u8 ( 0, ~v.read_u8 (0) ); - break; - case RawType::USize: - case RawType::ISize: - new_val.write_usize( 0, ~v.read_usize(0) ); - break; - case RawType::Bool: - new_val.write_u8 ( 0, v.read_u8 (0) == 0 ); - break; - default: - LOG_TODO("UniOp::INV - w/ type " << ty); - } - break; - case ::MIR::eUniOp::NEG: - switch(ty.inner_type) - { - case RawType::I128: - LOG_TODO("UniOp::NEG I128"); - case RawType::I64: - new_val.write_i64( 0, -v.read_i64(0) ); - break; - case RawType::I32: - new_val.write_i32( 0, -v.read_i32(0) ); - break; - case RawType::I16: - new_val.write_i16( 0, -v.read_i16(0) ); - break; - case RawType::I8: - new_val.write_i8 ( 0, -v.read_i8 (0) ); - break; - case RawType::ISize: - new_val.write_isize( 0, -v.read_isize(0) ); - break; + res = (reloc_l < reloc_r ? -1 : 1); + } + LOG_DEBUG("res=" << res << ", " << reloc_l << " ? " << reloc_r); + + if( ty_l.wrappers.empty() ) + { + switch(ty_l.inner_type) + { + case RawType::U64: res = res != 0 ? res : Ops::do_compare(v_l.read_u64(0), v_r.read_u64(0)); break; + case RawType::U32: res = res != 0 ? res : Ops::do_compare(v_l.read_u32(0), v_r.read_u32(0)); break; + case RawType::U16: res = res != 0 ? res : Ops::do_compare(v_l.read_u16(0), v_r.read_u16(0)); break; + case RawType::U8 : res = res != 0 ? res : Ops::do_compare(v_l.read_u8 (0), v_r.read_u8 (0)); break; + case RawType::I64: res = res != 0 ? res : Ops::do_compare(v_l.read_i64(0), v_r.read_i64(0)); break; + case RawType::I32: res = res != 0 ? res : Ops::do_compare(v_l.read_i32(0), v_r.read_i32(0)); break; + case RawType::I16: res = res != 0 ? res : Ops::do_compare(v_l.read_i16(0), v_r.read_i16(0)); break; + case RawType::I8 : res = res != 0 ? res : Ops::do_compare(v_l.read_i8 (0), v_r.read_i8 (0)); break; + case RawType::USize: res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); break; + case RawType::ISize: res = res != 0 ? res : Ops::do_compare(v_l.read_isize(0), v_r.read_isize(0)); break; default: - LOG_ERROR("UniOp::INV not valid on type " << ty); + LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); } - break; } - } break; - TU_ARM(se.src, DstMeta, re) { - auto ptr = state.get_value_ref(re.val); + else if( ty_l.wrappers.front().type == TypeWrapper::Ty::Pointer ) + { + // TODO: Technically only EQ/NE are valid. - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = ptr.read_value(POINTER_SIZE, dst_ty.get_size()); - } break; - TU_ARM(se.src, DstPtr, re) { - auto ptr = state.get_value_ref(re.val); + res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); - new_val = ptr.read_value(0, POINTER_SIZE); - } break; - TU_ARM(se.src, MakeDst, re) { - // - Get target type, just for some assertions - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - - auto ptr = state.param_to_value(re.ptr_val ); - auto meta = state.param_to_value(re.meta_val); - LOG_DEBUG("ty=" << dst_ty << ", ptr=" << ptr << ", meta=" << meta); - - new_val.write_value(0, ::std::move(ptr)); - new_val.write_value(POINTER_SIZE, ::std::move(meta)); - } break; - TU_ARM(se.src, Tuple, re) { - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); + // Compare fat metadata. + if( res == 0 && v_l.m_size > POINTER_SIZE ) + { + reloc_l = alloc_l ? alloc_l.alloc().get_relocation(POINTER_SIZE) : AllocationPtr(); + reloc_r = alloc_r ? alloc_r.alloc().get_relocation(POINTER_SIZE) : AllocationPtr(); - for(size_t i = 0; i < re.vals.size(); i++) + if( res == 0 && reloc_l != reloc_r ) + { + res = (reloc_l < reloc_r ? -1 : 1); + } + res = res != 0 ? res : Ops::do_compare(v_l.read_usize(POINTER_SIZE), v_r.read_usize(POINTER_SIZE)); + } + } + else { - auto fld_ofs = dst_ty.composite_type->fields.at(i).first; - new_val.write_value(fld_ofs, state.param_to_value(re.vals[i])); + LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); } - } break; - TU_ARM(se.src, Array, re) { - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - // TODO: Assert that type is an array - auto inner_ty = dst_ty.get_inner(); - size_t stride = inner_ty.get_size(); - - size_t ofs = 0; - for(const auto& v : re.vals) + bool res_bool; + switch(re.op) { - new_val.write_value(ofs, state.param_to_value(v)); - ofs += stride; + case ::MIR::eBinOp::EQ: res_bool = (res == 0); break; + case ::MIR::eBinOp::NE: res_bool = (res != 0); break; + case ::MIR::eBinOp::GT: res_bool = (res == 1); break; + case ::MIR::eBinOp::GE: res_bool = (res == 1 || res == 0); break; + case ::MIR::eBinOp::LT: res_bool = (res == -1); break; + case ::MIR::eBinOp::LE: res_bool = (res == -1 || res == 0); break; + break; + default: + LOG_BUG("Unknown comparison"); } + new_val = Value(::HIR::TypeRef(RawType::Bool)); + new_val.write_u8(0, res_bool ? 1 : 0); } break; - TU_ARM(se.src, SizedArray, re) { - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - // TODO: Assert that type is an array - auto inner_ty = dst_ty.get_inner(); - size_t stride = inner_ty.get_size(); - - size_t ofs = 0; - for(size_t i = 0; i < re.count; i++) + case ::MIR::eBinOp::BIT_SHL: + case ::MIR::eBinOp::BIT_SHR: { + LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); + LOG_ASSERT(ty_r.wrappers.empty(), "Bitwise operator with non-primitive - " << ty_r); + size_t max_bits = ty_r.get_size() * 8; + uint8_t shift; + auto check_cast = [&](auto v){ LOG_ASSERT(0 <= v && v <= max_bits, "Shift out of range - " << v); return static_cast(v); }; + switch(ty_r.inner_type) { - new_val.write_value(ofs, state.param_to_value(re.val)); - ofs += stride; + case RawType::U64: shift = check_cast(v_r.read_u64(0)); break; + case RawType::U32: shift = check_cast(v_r.read_u32(0)); break; + case RawType::U16: shift = check_cast(v_r.read_u16(0)); break; + case RawType::U8 : shift = check_cast(v_r.read_u8 (0)); break; + case RawType::I64: shift = check_cast(v_r.read_i64(0)); break; + case RawType::I32: shift = check_cast(v_r.read_i32(0)); break; + case RawType::I16: shift = check_cast(v_r.read_i16(0)); break; + case RawType::I8 : shift = check_cast(v_r.read_i8 (0)); break; + case RawType::USize: shift = check_cast(v_r.read_usize(0)); break; + case RawType::ISize: shift = check_cast(v_r.read_isize(0)); break; + default: + LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); + } + new_val = Value(ty_l); + switch(ty_l.inner_type) + { + // TODO: U128 + case RawType::U64: new_val.write_u64(0, Ops::do_bitwise(v_l.read_u64(0), static_cast(shift), re.op)); break; + case RawType::U32: new_val.write_u32(0, Ops::do_bitwise(v_l.read_u32(0), static_cast(shift), re.op)); break; + case RawType::U16: new_val.write_u16(0, Ops::do_bitwise(v_l.read_u16(0), static_cast(shift), re.op)); break; + case RawType::U8 : new_val.write_u8 (0, Ops::do_bitwise(v_l.read_u8 (0), static_cast(shift), re.op)); break; + case RawType::USize: new_val.write_usize(0, Ops::do_bitwise(v_l.read_usize(0), static_cast(shift), re.op)); break; + // TODO: Is signed allowed? + default: + LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); } } break; - TU_ARM(se.src, Variant, re) { - // 1. Get the composite by path. - const auto& data_ty = state.modtree.get_composite(re.path); - auto dst_ty = ::HIR::TypeRef(&data_ty); - new_val = Value(dst_ty); - LOG_DEBUG("Variant " << new_val); - // Three cases: - // - Unions (no tag) - // - Data enums (tag and data) - // - Value enums (no data) - const auto& var = data_ty.variants.at(re.index); - if( var.data_field != SIZE_MAX ) + case ::MIR::eBinOp::BIT_AND: + case ::MIR::eBinOp::BIT_OR: + case ::MIR::eBinOp::BIT_XOR: + LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); + LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); + new_val = Value(ty_l); + switch(ty_l.inner_type) + { + // TODO: U128/I128 + case RawType::U64: + case RawType::I64: + new_val.write_u64( 0, Ops::do_bitwise(v_l.read_u64(0), v_r.read_u64(0), re.op) ); + break; + case RawType::U32: + case RawType::I32: + new_val.write_u32( 0, static_cast(Ops::do_bitwise(v_l.read_u32(0), v_r.read_u32(0), re.op)) ); + break; + case RawType::U16: + case RawType::I16: + new_val.write_u16( 0, static_cast(Ops::do_bitwise(v_l.read_u16(0), v_r.read_u16(0), re.op)) ); + break; + case RawType::U8: + case RawType::I8: + new_val.write_u8 ( 0, static_cast(Ops::do_bitwise(v_l.read_u8 (0), v_r.read_u8 (0), re.op)) ); + break; + case RawType::USize: + case RawType::ISize: + new_val.write_usize( 0, Ops::do_bitwise(v_l.read_usize(0), v_r.read_usize(0), re.op) ); + break; + default: + LOG_TODO("BinOp bitwise - " << se.src << " w/ " << ty_l); + } + + break; + default: + LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); + auto val_l = PrimitiveValueVirt::from_value(ty_l, v_l); + auto val_r = PrimitiveValueVirt::from_value(ty_r, v_r); + switch(re.op) { - const auto& fld = data_ty.fields.at(re.index); + case ::MIR::eBinOp::ADD: val_l.get().add( val_r.get() ); break; + case ::MIR::eBinOp::SUB: val_l.get().subtract( val_r.get() ); break; + case ::MIR::eBinOp::MUL: val_l.get().multiply( val_r.get() ); break; + case ::MIR::eBinOp::DIV: val_l.get().divide( val_r.get() ); break; + case ::MIR::eBinOp::MOD: val_l.get().modulo( val_r.get() ); break; - new_val.write_value(fld.first, state.param_to_value(re.val)); + default: + LOG_TODO("Unsupported binary operator?"); } - LOG_DEBUG("Variant " << new_val); - if( var.base_field != SIZE_MAX ) + new_val = Value(ty_l); + val_l.get().write_to_value(new_val, 0); + break; + } + } break; + TU_ARM(se.src, UniOp, re) { + ::HIR::TypeRef ty; + auto v = state.get_value_and_type(re.val, ty); + LOG_ASSERT(ty.wrappers.empty(), "UniOp on wrapped type - " << ty); + new_val = Value(ty); + switch(re.op) + { + case ::MIR::eUniOp::INV: + switch(ty.inner_type) { - ::HIR::TypeRef tag_ty; - size_t tag_ofs = dst_ty.get_field_ofs(var.base_field, var.field_path, tag_ty); - LOG_ASSERT(tag_ty.get_size() == var.tag_data.size(), ""); - new_val.write_bytes(tag_ofs, var.tag_data.data(), var.tag_data.size()); + case RawType::U128: + case RawType::I128: + LOG_TODO("UniOp::INV U128"); + case RawType::U64: + case RawType::I64: + new_val.write_u64( 0, ~v.read_u64(0) ); + break; + case RawType::U32: + case RawType::I32: + new_val.write_u32( 0, ~v.read_u32(0) ); + break; + case RawType::U16: + case RawType::I16: + new_val.write_u16( 0, ~v.read_u16(0) ); + break; + case RawType::U8: + case RawType::I8: + new_val.write_u8 ( 0, ~v.read_u8 (0) ); + break; + case RawType::USize: + case RawType::ISize: + new_val.write_usize( 0, ~v.read_usize(0) ); + break; + case RawType::Bool: + new_val.write_u8 ( 0, v.read_u8 (0) == 0 ); + break; + default: + LOG_TODO("UniOp::INV - w/ type " << ty); } - else + break; + case ::MIR::eUniOp::NEG: + switch(ty.inner_type) { - // Union, no tag + case RawType::I128: + LOG_TODO("UniOp::NEG I128"); + case RawType::I64: + new_val.write_i64( 0, -v.read_i64(0) ); + break; + case RawType::I32: + new_val.write_i32( 0, -v.read_i32(0) ); + break; + case RawType::I16: + new_val.write_i16( 0, -v.read_i16(0) ); + break; + case RawType::I8: + new_val.write_i8 ( 0, -v.read_i8 (0) ); + break; + case RawType::ISize: + new_val.write_isize( 0, -v.read_isize(0) ); + break; + default: + LOG_ERROR("UniOp::INV not valid on type " << ty); } - LOG_DEBUG("Variant " << new_val); - } break; - TU_ARM(se.src, Struct, re) { - const auto& data_ty = state.modtree.get_composite(re.path); + break; + } + } break; + TU_ARM(se.src, DstMeta, re) { + auto ptr = state.get_value_ref(re.val); + + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = ptr.read_value(POINTER_SIZE, dst_ty.get_size()); + } break; + TU_ARM(se.src, DstPtr, re) { + auto ptr = state.get_value_ref(re.val); - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - LOG_ASSERT(dst_ty.composite_type == &data_ty, "Destination type of RValue::Struct isn't the same as the input"); + new_val = ptr.read_value(0, POINTER_SIZE); + } break; + TU_ARM(se.src, MakeDst, re) { + // - Get target type, just for some assertions + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + + auto ptr = state.param_to_value(re.ptr_val ); + auto meta = state.param_to_value(re.meta_val); + LOG_DEBUG("ty=" << dst_ty << ", ptr=" << ptr << ", meta=" << meta); + + new_val.write_value(0, ::std::move(ptr)); + new_val.write_value(POINTER_SIZE, ::std::move(meta)); + } break; + TU_ARM(se.src, Tuple, re) { + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); - for(size_t i = 0; i < re.vals.size(); i++) - { - auto fld_ofs = data_ty.fields.at(i).first; - new_val.write_value(fld_ofs, state.param_to_value(re.vals[i])); - } - } break; + for(size_t i = 0; i < re.vals.size(); i++) + { + auto fld_ofs = dst_ty.composite_type->fields.at(i).first; + new_val.write_value(fld_ofs, state.param_to_value(re.vals[i])); } - LOG_DEBUG("- " << new_val); - state.write_lvalue(se.dst, ::std::move(new_val)); } break; - case ::MIR::Statement::TAG_Asm: - LOG_TODO(stmt); - break; - TU_ARM(stmt, Drop, se) { - if( se.flag_idx == ~0u || state.drop_flags.at(se.flag_idx) ) + TU_ARM(se.src, Array, re) { + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + // TODO: Assert that type is an array + auto inner_ty = dst_ty.get_inner(); + size_t stride = inner_ty.get_size(); + + size_t ofs = 0; + for(const auto& v : re.vals) { - ::HIR::TypeRef ty; - auto v = state.get_value_and_type(se.slot, ty); + new_val.write_value(ofs, state.param_to_value(v)); + ofs += stride; + } + } break; + TU_ARM(se.src, SizedArray, re) { + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + // TODO: Assert that type is an array + auto inner_ty = dst_ty.get_inner(); + size_t stride = inner_ty.get_size(); + + size_t ofs = 0; + for(size_t i = 0; i < re.count; i++) + { + new_val.write_value(ofs, state.param_to_value(re.val)); + ofs += stride; + } + } break; + TU_ARM(se.src, Variant, re) { + // 1. Get the composite by path. + const auto& data_ty = this->m_modtree.get_composite(re.path); + auto dst_ty = ::HIR::TypeRef(&data_ty); + new_val = Value(dst_ty); + LOG_DEBUG("Variant " << new_val); + // Three cases: + // - Unions (no tag) + // - Data enums (tag and data) + // - Value enums (no data) + const auto& var = data_ty.variants.at(re.index); + if( var.data_field != SIZE_MAX ) + { + const auto& fld = data_ty.fields.at(re.index); + + new_val.write_value(fld.first, state.param_to_value(re.val)); + } + LOG_DEBUG("Variant " << new_val); + if( var.base_field != SIZE_MAX ) + { + ::HIR::TypeRef tag_ty; + size_t tag_ofs = dst_ty.get_field_ofs(var.base_field, var.field_path, tag_ty); + LOG_ASSERT(tag_ty.get_size() == var.tag_data.size(), ""); + new_val.write_bytes(tag_ofs, var.tag_data.data(), var.tag_data.size()); + } + else + { + // Union, no tag + } + LOG_DEBUG("Variant " << new_val); + } break; + TU_ARM(se.src, Struct, re) { + const auto& data_ty = m_modtree.get_composite(re.path); + + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + LOG_ASSERT(dst_ty.composite_type == &data_ty, "Destination type of RValue::Struct isn't the same as the input"); - // - Take a pointer to the inner - auto alloc = v.m_alloc; - if( !alloc ) + for(size_t i = 0; i < re.vals.size(); i++) + { + auto fld_ofs = data_ty.fields.at(i).first; + new_val.write_value(fld_ofs, state.param_to_value(re.vals[i])); + } + } break; + } + LOG_DEBUG("- " << new_val); + state.write_lvalue(se.dst, ::std::move(new_val)); + } break; + case ::MIR::Statement::TAG_Asm: + LOG_TODO(stmt); + break; + TU_ARM(stmt, Drop, se) { + if( se.flag_idx == ~0u || cur_frame.drop_flags.at(se.flag_idx) ) + { + ::HIR::TypeRef ty; + auto v = state.get_value_and_type(se.slot, ty); + + // - Take a pointer to the inner + auto alloc = v.m_alloc; + if( !alloc ) + { + if( !v.m_value->allocation ) { - if( !v.m_value->allocation ) - { - v.m_value->create_allocation(); - } - alloc = AllocationPtr(v.m_value->allocation); + v.m_value->create_allocation(); } - size_t ofs = v.m_offset; - assert(ty.get_meta_type() == RawType::Unreachable); + alloc = AllocationPtr(v.m_value->allocation); + } + size_t ofs = v.m_offset; + assert(ty.get_meta_type() == RawType::Unreachable); - auto ptr_ty = ty.wrap(TypeWrapper::Ty::Borrow, 2); + auto ptr_ty = ty.wrap(TypeWrapper::Ty::Borrow, 2); - auto ptr_val = Value(ptr_ty); - ptr_val.write_usize(0, ofs); - ptr_val.allocation.alloc().relocations.push_back(Relocation { 0, ::std::move(alloc) }); + auto ptr_val = Value(ptr_ty); + ptr_val.write_usize(0, ofs); + ptr_val.allocation.alloc().relocations.push_back(Relocation { 0, ::std::move(alloc) }); - // TODO: Shallow drop - drop_value(modtree, thread, ptr_val, ty, /*shallow=*/se.kind == ::MIR::eDropKind::SHALLOW); - // TODO: Clear validity on the entire inner value. - //alloc.mark_as_freed(); + if( !drop_value(ptr_val, ty, /*shallow=*/se.kind == ::MIR::eDropKind::SHALLOW) ) + { + return false; } - } break; - TU_ARM(stmt, SetDropFlag, se) { - bool val = (se.other == ~0u ? false : state.drop_flags.at(se.other)) != se.new_val; - LOG_DEBUG("- " << val); - state.drop_flags.at(se.idx) = val; - } break; - case ::MIR::Statement::TAG_ScopeEnd: - LOG_TODO(stmt); - break; } + } break; + TU_ARM(stmt, SetDropFlag, se) { + bool val = (se.other == ~0u ? false : cur_frame.drop_flags.at(se.other)) != se.new_val; + LOG_DEBUG("- " << val); + cur_frame.drop_flags.at(se.idx) = val; + } break; + case ::MIR::Statement::TAG_ScopeEnd: + LOG_TODO(stmt); + break; } - - LOG_DEBUG("=== BB" << bb_idx << "/TERM: " << bb.terminator); + + cur_frame.stmt_idx += 1; + } + else + { + LOG_DEBUG("=== BB" << cur_frame.bb_idx << "/TERM: " << bb.terminator); switch(bb.terminator.tag()) { case ::MIR::Terminator::TAGDEAD: throw ""; @@ -1521,16 +1469,16 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: TU_ARM(bb.terminator, Panic, _te) LOG_TODO("Terminator::Panic"); TU_ARM(bb.terminator, Goto, te) - bb_idx = te; - continue; + cur_frame.bb_idx = te; + break; TU_ARM(bb.terminator, Return, _te) - LOG_DEBUG("RETURN " << state.ret); - return state.ret; + LOG_DEBUG("RETURN " << cur_frame.ret); + return this->pop_stack(out_thread_result); TU_ARM(bb.terminator, If, te) { uint8_t v = state.get_value_ref(te.cond).read_u8(0); LOG_ASSERT(v == 0 || v == 1, ""); - bb_idx = v ? te.bb0 : te.bb1; - } continue; + cur_frame.bb_idx = v ? te.bb0 : te.bb1; + } break; TU_ARM(bb.terminator, Switch, te) { ::HIR::TypeRef ty; auto v = state.get_value_and_type(te.val, ty); @@ -1578,8 +1526,8 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: { LOG_FATAL("Terminator::Switch on " << ty << " didn't find a variant"); } - bb_idx = te.targets.at(found_target); - } continue; + cur_frame.bb_idx = te.targets.at(found_target); + } break; TU_ARM(bb.terminator, SwitchValue, _te) LOG_TODO("Terminator::SwitchValue"); TU_ARM(bb.terminator, Call, te) { @@ -1589,10 +1537,15 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: sub_args.push_back( state.param_to_value(a) ); LOG_DEBUG("#" << (sub_args.size() - 1) << " " << sub_args.back()); } + Value rv; if( te.fcn.is_Intrinsic() ) { const auto& fe = te.fcn.as_Intrinsic(); - state.write_lvalue(te.ret_val, MIRI_Invoke_Intrinsic(modtree, thread, fe.name, fe.params, ::std::move(sub_args))); + if( !this->call_intrinsic(rv, fe.name, fe.params, ::std::move(sub_args)) ) + { + // Early return, don't want to update stmt_idx yet + return false; + } } else { @@ -1618,25 +1571,140 @@ Value MIRI_Invoke(ModuleTree& modtree, ThreadState& thread, ::HIR::Path path, :: } LOG_DEBUG("Call " << *fcn_p); - auto v = MIRI_Invoke(modtree, thread, *fcn_p, ::std::move(sub_args)); - LOG_DEBUG(te.ret_val << " = " << v << " (resume " << path << ")"); - state.write_lvalue(te.ret_val, ::std::move(v)); + if( !this->call_path(rv, *fcn_p, ::std::move(sub_args)) ) + { + // Early return, don't want to update stmt_idx yet + return false; + } + } + LOG_DEBUG(te.ret_val << " = " << rv << " (resume " << cur_frame.fcn.my_path << ")"); + state.write_lvalue(te.ret_val, rv); + cur_frame.bb_idx = te.ret_block; + } break; + } + cur_frame.stmt_idx = 0; + } + + return false; +} +bool InterpreterThread::pop_stack(Value& out_thread_result) +{ + assert( !this->m_stack.empty() ); + + auto res_v = ::std::move(this->m_stack.back().ret); + this->m_stack.pop_back(); + + if( this->m_stack.empty() ) + { + LOG_DEBUG("Thread complete, result " << res_v); + out_thread_result = ::std::move(res_v); + return true; + } + else + { + // Handle callback wrappers (e.g. for __rust_maybe_catch_panic) + if( this->m_stack.back().cb ) + { + if( !this->m_stack.back().cb(res_v, ::std::move(res_v)) ) + { + return false; } - bb_idx = te.ret_block; - } continue; + this->m_stack.pop_back(); + assert( !this->m_stack.empty() ); + assert( !this->m_stack.back().cb ); + } + + auto& cur_frame = this->m_stack.back(); + MirHelpers state { *this, cur_frame }; + + const auto& blk = cur_frame.fcn.m_mir.blocks.at( cur_frame.bb_idx ); + if( cur_frame.stmt_idx < blk.statements.size() ) + { + assert( blk.statements[cur_frame.stmt_idx].is_Drop() ); + cur_frame.stmt_idx ++; + LOG_DEBUG("DROP complete (resume " << cur_frame.fcn.my_path << ")"); + } + else + { + assert( blk.terminator.is_Call() ); + const auto& te = blk.terminator.as_Call(); + + LOG_DEBUG(te.ret_val << " = " << res_v << " (resume " << cur_frame.fcn.my_path << ")"); + + state.write_lvalue(te.ret_val, res_v); + cur_frame.stmt_idx = 0; + cur_frame.bb_idx = te.ret_block; + } + + return false; + } +} + +InterpreterThread::StackFrame::StackFrame(const Function& fcn, ::std::vector args): + fcn(fcn), + ret( fcn.ret_ty ), + args( ::std::move(args) ), + locals( ), + drop_flags( fcn.m_mir.drop_flags ), + bb_idx(0), + stmt_idx(0) +{ + this->locals.reserve( fcn.m_mir.locals.size() ); + for(const auto& ty : fcn.m_mir.locals) + { + if( ty == RawType::Unreachable ) { + // HACK: Locals can be !, but they can NEVER be accessed + this->locals.push_back( Value() ); + } + else { + this->locals.push_back( Value(ty) ); + } + } +} +bool InterpreterThread::call_path(Value& ret, const ::HIR::Path& path, ::std::vector args) +{ + // TODO: Support overriding certain functions + { + if( path == ::HIR::SimplePath { "std", { "sys", "imp", "c", "SetThreadStackGuarantee" } } ) + { + ret = Value(::HIR::TypeRef{RawType::I32}); + ret.write_i32(0, 120); // ERROR_CALL_NOT_IMPLEMENTED + return true; + } + + // - No guard page needed + if( path == ::HIR::SimplePath { "std", {"sys", "imp", "thread", "guard", "init" } } ) + { + ret = Value::with_size(16, false); + ret.write_u64(0, 0); + ret.write_u64(8, 0); + return true; + } + + // - No stack overflow handling needed + if( path == ::HIR::SimplePath { "std", { "sys", "imp", "stack_overflow", "imp", "init" } } ) + { + return true; } - throw ""; } - throw ""; + const auto& fcn = m_modtree.get_function(path); + + if( fcn.external.link_name != "" ) + { + // External function! + return this->call_extern(ret, fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); + } + + this->m_stack.push_back(StackFrame(fcn, ::std::move(args))); + return false; } extern "C" { long sysconf(int); ssize_t write(int, const void*, size_t); } - -Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std::string& link_name, const ::std::string& abi, ::std::vector args) +bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, const ::std::string& abi, ::std::vector args) { if( link_name == "__rust_allocate" ) { @@ -1645,11 +1713,11 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: LOG_DEBUG("__rust_allocate(size=" << size << ", align=" << align << ")"); ::HIR::TypeRef rty { RawType::Unit }; rty.wrappers.push_back({ TypeWrapper::Ty::Pointer, 0 }); - Value rv = Value(rty); + + rv = Value(rty); rv.write_usize(0, 0); // TODO: Use the alignment when making an allocation? rv.allocation.alloc().relocations.push_back({ 0, Allocation::new_alloc(size) }); - return rv; } else if( link_name == "__rust_reallocate" ) { @@ -1669,7 +1737,7 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: alloc.data.resize( (newsize + 8-1) / 8 ); alloc.mask.resize( (newsize + 8-1) / 8 ); // TODO: Should this instead make a new allocation to catch use-after-free? - return ::std::move(args.at(0)); + rv = ::std::move(args.at(0)); } else if( link_name == "__rust_deallocate" ) { @@ -1684,7 +1752,7 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: auto& alloc = alloc_ptr.alloc(); alloc.mark_as_freed(); // Just let it drop. - return Value(); + rv = Value(); } else if( link_name == "__rust_maybe_catch_panic" ) { @@ -1696,12 +1764,23 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: ::std::vector sub_args; sub_args.push_back( ::std::move(arg) ); - // TODO: Catch the panic out of this. - MIRI_Invoke(modtree, thread, fcn_path, ::std::move(sub_args)); + this->m_stack.push_back(StackFrame::make_wrapper([=](Value& out_rv, Value /*rv*/)->bool{ + out_rv = Value(::HIR::TypeRef(RawType::U32)); + out_rv.write_u32(0, 0); + return true; + })); - auto rv = Value(::HIR::TypeRef(RawType::U32)); - rv.write_u32(0,0); - return rv; + // TODO: Catch the panic out of this. + if( this->call_path(rv, fcn_path, ::std::move(sub_args)) ) + { + bool v = this->pop_stack(rv); + assert( v == false ); + return true; + } + else + { + return false; + } } else if( link_name == "__rust_start_panic" ) { @@ -1716,9 +1795,8 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: else if( link_name == "AddVectoredExceptionHandler" ) { LOG_DEBUG("Call `AddVectoredExceptionHandler` - Ignoring and returning non-null"); - auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv = Value(::HIR::TypeRef(RawType::USize)); rv.write_usize(0, 1); - return rv; } else if( link_name == "GetModuleHandleW" ) { @@ -1733,17 +1811,16 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: LOG_DEBUG("GetModuleHandleW(NULL)"); } - auto rv = GetModuleHandleW(static_cast(arg0)); - if(rv) + auto ret = GetModuleHandleW(static_cast(arg0)); + if(ret) { - return Value::new_ffiptr(FFIPointer { "GetModuleHandleW", rv }); + rv = Value::new_ffiptr(FFIPointer { "GetModuleHandleW", ret }); } else { - auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv = Value(::HIR::TypeRef(RawType::USize)); rv.create_allocation(); rv.write_usize(0,0); - return rv; } } else if( link_name == "GetProcAddress" ) @@ -1760,18 +1837,17 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: // TODO: Sanity check that it's a valid c string within its allocation LOG_DEBUG("FFI GetProcAddress(" << handle << ", \"" << static_cast(symname) << "\")"); - auto rv = GetProcAddress(static_cast(handle), static_cast(symname)); + auto ret = GetProcAddress(static_cast(handle), static_cast(symname)); - if( rv ) + if( ret ) { - return Value::new_ffiptr(FFIPointer { "GetProcAddress", rv }); + rv = Value::new_ffiptr(FFIPointer { "GetProcAddress", ret }); } else { - auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv = Value(::HIR::TypeRef(RawType::USize)); rv.create_allocation(); rv.write_usize(0,0); - return rv; } } #else @@ -1784,48 +1860,43 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: ssize_t val = write(fd, buf, count); - auto rv = Value(::HIR::TypeRef(RawType::ISize)); + rv = Value(::HIR::TypeRef(RawType::ISize)); rv.write_isize(0, val); - return rv; } else if( link_name == "sysconf" ) { auto name = args.at(0).read_i32(0); LOG_DEBUG("FFI sysconf(" << name << ")"); + long val = sysconf(name); - auto rv = Value(::HIR::TypeRef(RawType::USize)); + + rv = Value(::HIR::TypeRef(RawType::USize)); rv.write_usize(0, val); - return rv; } else if( link_name == "pthread_mutex_init" || link_name == "pthread_mutex_lock" || link_name == "pthread_mutex_unlock" || link_name == "pthread_mutex_destroy" ) { - auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); - return rv; } else if( link_name == "pthread_rwlock_rdlock" ) { - auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); - return rv; } else if( link_name == "pthread_mutexattr_init" || link_name == "pthread_mutexattr_settype" || link_name == "pthread_mutexattr_destroy" ) { - auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); - return rv; } else if( link_name == "pthread_condattr_init" || link_name == "pthread_condattr_destroy" || link_name == "pthread_condattr_setclock" ) { - auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); - return rv; } else if( link_name == "pthread_cond_init" || link_name == "pthread_cond_destroy" ) { - auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); - return rv; } else if( link_name == "pthread_key_create" ) { @@ -1834,20 +1905,18 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: auto key = ThreadState::s_next_tls_key ++; key_ref.m_alloc.alloc().write_u32( key_ref.m_offset, key ); - auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); - return rv; } else if( link_name == "pthread_getspecific" ) { auto key = args.at(0).read_u32(0); // Get a pointer-sized value from storage - uint64_t v = key < thread.tls_values.size() ? thread.tls_values[key] : 0; + uint64_t v = key < m_thread.tls_values.size() ? m_thread.tls_values[key] : 0; - auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv = Value(::HIR::TypeRef(RawType::USize)); rv.write_usize(0, v); - return rv; } else if( link_name == "pthread_setspecific" ) { @@ -1855,29 +1924,26 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: auto v = args.at(1).read_u64(0); // Get a pointer-sized value from storage - if( key >= thread.tls_values.size() ) { - thread.tls_values.resize(key+1); + if( key >= m_thread.tls_values.size() ) { + m_thread.tls_values.resize(key+1); } - thread.tls_values[key] = v; + m_thread.tls_values[key] = v; - auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); - return rv; } else if( link_name == "pthread_key_delete" ) { - auto rv = Value(::HIR::TypeRef(RawType::I32)); + rv = Value(::HIR::TypeRef(RawType::I32)); rv.write_i32(0, 0); - return rv; } #endif // std C else if( link_name == "signal" ) { LOG_DEBUG("Call `signal` - Ignoring and returning SIG_IGN"); - auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv = Value(::HIR::TypeRef(RawType::USize)); rv.write_usize(0, 1); - return rv; } // - `void *memchr(const void *s, int c, size_t n);` else if( link_name == "memchr" ) @@ -1890,7 +1956,7 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: const void* ret = memchr(ptr, c, n); - auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv = Value(::HIR::TypeRef(RawType::USize)); rv.create_allocation(); if( ret ) { @@ -1901,7 +1967,6 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: { rv.write_usize(0, 0); } - return rv; } else if( link_name == "memrchr" ) { @@ -1912,7 +1977,7 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: const void* ret = memrchr(ptr, c, n); - auto rv = Value(::HIR::TypeRef(RawType::USize)); + rv = Value(::HIR::TypeRef(RawType::USize)); rv.create_allocation(); if( ret ) { @@ -1923,18 +1988,17 @@ Value MIRI_Invoke_Extern(ModuleTree& modtree, ThreadState& thread, const ::std:: { rv.write_usize(0, 0); } - return rv; } // Allocators! else { LOG_TODO("Call external function " << link_name); } - throw ""; + return true; } -Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args) + +bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args) { - Value rv; TRACE_FUNCTION_R(name, rv); for(const auto& a : args) LOG_DEBUG("#" << (&a - args.data()) << ": " << a); @@ -1953,7 +2017,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st } else if( name == "atomic_fence" || name == "atomic_fence_acq" ) { - return Value(); + rv = Value(); } else if( name == "atomic_store" ) { @@ -1986,6 +2050,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st size_t ofs = ptr_val.read_usize(0); const auto& ty = ty_params.tys.at(0); + rv = alloc.alloc().read_value(ofs, ty.get_size()); } else if( name == "atomic_xadd" || name == "atomic_xadd_relaxed" ) @@ -2056,7 +2121,6 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st else { rv.write_u8( old_v.size(), 0 ); } - return rv; } else if( name == "transmute" ) { @@ -2180,13 +2244,17 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st auto ptr = val.read_value(0, POINTER_SIZE); for(size_t i = 0; i < item_count; i ++) { - drop_value(modtree, thread, ptr, ity); + // TODO: Nested calls? + if( !drop_value(ptr, ity) ) + { + LOG_DEBUG("Handle multiple queued calls"); + } ptr.write_usize(0, ptr.read_usize(0) + item_size); } } else { - drop_value(modtree, thread, val, ty); + return drop_value(val, ty); } } // ---------------------------------------------------------------- @@ -2203,7 +2271,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st ::HIR::GenericPath gp; gp.m_params.tys.push_back(ty); gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); - const auto& dty = modtree.get_composite(gp); + const auto& dty = m_modtree.get_composite(gp); rv = Value(::HIR::TypeRef(&dty)); lhs.get().write_to_value(rv, dty.fields[0].first); @@ -2221,7 +2289,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st ::HIR::GenericPath gp; gp.m_params.tys.push_back(ty); gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); - const auto& dty = modtree.get_composite(gp); + const auto& dty = m_modtree.get_composite(gp); rv = Value(::HIR::TypeRef(&dty)); lhs.get().write_to_value(rv, dty.fields[0].first); @@ -2239,7 +2307,7 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st ::HIR::GenericPath gp; gp.m_params.tys.push_back(ty); gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); - const auto& dty = modtree.get_composite(gp); + const auto& dty = m_modtree.get_composite(gp); rv = Value(::HIR::TypeRef(&dty)); lhs.get().write_to_value(rv, dty.fields[0].first); @@ -2298,7 +2366,75 @@ Value MIRI_Invoke_Intrinsic(ModuleTree& modtree, ThreadState& thread, const ::st { LOG_TODO("Call intrinsic \"" << name << "\""); } - return rv; + return true; +} + +bool InterpreterThread::drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_shallow/*=false*/) +{ + if( is_shallow ) + { + // HACK: Only works for Box where the first pointer is the data pointer + auto box_ptr_vr = ptr.read_pointer_valref_mut(0, POINTER_SIZE); + auto ofs = box_ptr_vr.read_usize(0); + auto alloc = box_ptr_vr.get_relocation(0); + if( ofs != 0 || !alloc || !alloc.is_alloc() ) { + LOG_ERROR("Attempting to shallow drop with invalid pointer (no relocation or non-zero offset) - " << box_ptr_vr); + } + + LOG_DEBUG("drop_value SHALLOW deallocate " << alloc); + alloc.alloc().mark_as_freed(); + return true; + } + if( ty.wrappers.empty() ) + { + if( ty.inner_type == RawType::Composite ) + { + if( ty.composite_type->drop_glue != ::HIR::Path() ) + { + LOG_DEBUG("Drop - " << ty); + + Value tmp; + return this->call_path(tmp, ty.composite_type->drop_glue, { ptr }); + } + else + { + // No drop glue + } + } + else if( ty.inner_type == RawType::TraitObject ) + { + LOG_TODO("Drop - " << ty << " - trait object"); + } + else + { + // No destructor + } + } + else + { + switch( ty.wrappers[0].type ) + { + case TypeWrapper::Ty::Borrow: + if( ty.wrappers[0].size == static_cast(::HIR::BorrowType::Move) ) + { + LOG_TODO("Drop - " << ty << " - dereference and go to inner"); + // TODO: Clear validity on the entire inner value. + } + else + { + // No destructor + } + break; + case TypeWrapper::Ty::Pointer: + // No destructor + break; + // TODO: Arrays + default: + LOG_TODO("Drop - " << ty << " - array?"); + break; + } + } + return true; } int ProgramOptions::parse(int argc, const char* argv[]) -- cgit v1.2.3 From 55ea64451a81be2f797094c9a4140a7a98ba6b5d Mon Sep 17 00:00:00 2001 From: John Hodge Date: Tue, 15 May 2018 21:25:47 +0800 Subject: Standalone MIRI - Split AllocationPtr into AllocationHandle and RelocationPtr --- tools/standalone_miri/main.cpp | 94 +++++++-------- tools/standalone_miri/module_tree.cpp | 6 +- tools/standalone_miri/value.cpp | 208 +++++++++++++++++++++------------- tools/standalone_miri/value.hpp | 190 +++++++++++++++++-------------- 4 files changed, 280 insertions(+), 218 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 1ab5b955..cd521501 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -153,7 +153,7 @@ public: virtual bool multiply(const PrimitiveValue& v) = 0; virtual bool divide(const PrimitiveValue& v) = 0; virtual bool modulo(const PrimitiveValue& v) = 0; - virtual void write_to_value(ValueCommon& tgt, size_t ofs) const = 0; + virtual void write_to_value(ValueCommonWrite& tgt, size_t ofs) const = 0; template const T& check(const char* opname) const @@ -212,14 +212,14 @@ struct PrimitiveUInt: struct PrimitiveU64: public PrimitiveUInt { PrimitiveU64(uint64_t v): PrimitiveUInt(v) {} - void write_to_value(ValueCommon& tgt, size_t ofs) const override { + void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { tgt.write_u64(ofs, this->v); } }; struct PrimitiveU32: public PrimitiveUInt { PrimitiveU32(uint32_t v): PrimitiveUInt(v) {} - void write_to_value(ValueCommon& tgt, size_t ofs) const override { + void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { tgt.write_u32(ofs, this->v); } }; @@ -273,14 +273,14 @@ struct PrimitiveSInt: struct PrimitiveI64: public PrimitiveSInt { PrimitiveI64(int64_t v): PrimitiveSInt(v) {} - void write_to_value(ValueCommon& tgt, size_t ofs) const override { + void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { tgt.write_i64(ofs, this->v); } }; struct PrimitiveI32: public PrimitiveSInt { PrimitiveI32(int32_t v): PrimitiveSInt(v) {} - void write_to_value(ValueCommon& tgt, size_t ofs) const override { + void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { tgt.write_i32(ofs, this->v); } }; @@ -458,11 +458,8 @@ struct MirHelpers size_t ofs = val.read_usize(0); // There MUST be a relocation at this point with a valid allocation. - auto& val_alloc = val.m_alloc ? val.m_alloc : val.m_value->allocation; - LOG_ASSERT(val_alloc, "Deref of a value with no allocation (hence no relocations)"); - LOG_ASSERT(val_alloc.is_alloc(), "Deref of a value with a non-data allocation"); - LOG_TRACE("Deref " << val_alloc.alloc() << " + " << ofs << " to give value of type " << ty); - auto alloc = val_alloc.alloc().get_relocation(val.m_offset); + auto alloc = val.get_relocation(val.m_offset); + LOG_TRACE("Deref " << alloc << " + " << ofs << " to give value of type " << ty); // NOTE: No alloc can happen when dereferencing a zero-sized pointer if( alloc.is_alloc() ) { @@ -595,7 +592,7 @@ struct MirHelpers Value val = Value(ty); val.write_usize(0, 0); val.write_usize(POINTER_SIZE, ce.size()); - val.allocation.alloc().relocations.push_back(Relocation { 0, AllocationPtr::new_string(&ce) }); + val.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_string(&ce) }); LOG_DEBUG(c << " = " << val); //return Value::new_dataptr(ce.data()); return val; @@ -612,7 +609,7 @@ struct MirHelpers ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); Value val = Value(ty); val.write_usize(0, 0); - val.allocation.alloc().relocations.push_back(Relocation { 0, s->val.allocation }); + val.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_alloc(s->val.allocation) }); return val; } LOG_ERROR("Constant::ItemAddr - " << ce << " - not found"); @@ -676,6 +673,7 @@ InterpreterThread::~InterpreterThread() } void InterpreterThread::start(const ::HIR::Path& p, ::std::vector args) { + assert( this->m_stack.empty() ); Value v; if( this->call_path(v, p, ::std::move(args)) ) { @@ -720,7 +718,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) { src_base_value.m_value->create_allocation(); } - alloc = AllocationPtr(src_base_value.m_value->allocation); + alloc = RelocationPtr::new_alloc( src_base_value.m_value->allocation ); } if( alloc.is_alloc() ) LOG_DEBUG("- alloc=" << alloc << " (" << alloc.alloc() << ")"); @@ -740,7 +738,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) new_val.write_value(POINTER_SIZE, *src_base_value.m_metadata); } // - Add the relocation after writing the value (writing clears the relocations) - new_val.allocation.alloc().relocations.push_back(Relocation { 0, ::std::move(alloc) }); + new_val.allocation->relocations.push_back(Relocation { 0, ::std::move(alloc) }); } break; TU_ARM(se.src, Cast, re) { // Determine the type of cast, is it a reinterpret or is it a value transform? @@ -1073,8 +1071,8 @@ bool InterpreterThread::step_one(Value& out_thread_result) const auto& alloc_l = v_l.m_value ? v_l.m_value->allocation : v_l.m_alloc; const auto& alloc_r = v_r.m_value ? v_r.m_value->allocation : v_r.m_alloc; - auto reloc_l = alloc_l ? v_l.get_relocation(v_l.m_offset) : AllocationPtr(); - auto reloc_r = alloc_r ? v_r.get_relocation(v_r.m_offset) : AllocationPtr(); + auto reloc_l = alloc_l ? v_l.get_relocation(v_l.m_offset) : RelocationPtr(); + auto reloc_r = alloc_r ? v_r.get_relocation(v_r.m_offset) : RelocationPtr(); if( reloc_l != reloc_r ) { @@ -1109,8 +1107,8 @@ bool InterpreterThread::step_one(Value& out_thread_result) // Compare fat metadata. if( res == 0 && v_l.m_size > POINTER_SIZE ) { - reloc_l = alloc_l ? alloc_l.alloc().get_relocation(POINTER_SIZE) : AllocationPtr(); - reloc_r = alloc_r ? alloc_r.alloc().get_relocation(POINTER_SIZE) : AllocationPtr(); + reloc_l = v_l.get_relocation(POINTER_SIZE); + reloc_r = v_r.get_relocation(POINTER_SIZE); if( res == 0 && reloc_l != reloc_r ) { @@ -1427,7 +1425,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) { v.m_value->create_allocation(); } - alloc = AllocationPtr(v.m_value->allocation); + alloc = RelocationPtr::new_alloc( v.m_value->allocation ); } size_t ofs = v.m_offset; assert(ty.get_meta_type() == RawType::Unreachable); @@ -1436,7 +1434,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) auto ptr_val = Value(ptr_ty); ptr_val.write_usize(0, ofs); - ptr_val.allocation.alloc().relocations.push_back(Relocation { 0, ::std::move(alloc) }); + ptr_val.allocation->relocations.push_back(Relocation { 0, ::std::move(alloc) }); if( !drop_value(ptr_val, ty, /*shallow=*/se.kind == ::MIR::eDropKind::SHALLOW) ) { @@ -1549,7 +1547,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) } else { - AllocationPtr fcn_alloc_ptr; + RelocationPtr fcn_alloc_ptr; const ::HIR::Path* fcn_p; if( te.fcn.is_Path() ) { fcn_p = &te.fcn.as_Path(); @@ -1561,12 +1559,10 @@ bool InterpreterThread::step_one(Value& out_thread_result) // TODO: Assert type // TODO: Assert offset/content. assert(v.read_usize(0) == 0); - auto& alloc_ptr = v.m_alloc ? v.m_alloc : v.m_value->allocation; - LOG_ASSERT(alloc_ptr, "Calling value that can't be a pointer (no allocation)"); - fcn_alloc_ptr = alloc_ptr.alloc().get_relocation(v.m_offset); + fcn_alloc_ptr = v.get_relocation(v.m_offset); if( !fcn_alloc_ptr ) LOG_FATAL("Calling value with no relocation - " << v); - LOG_ASSERT(fcn_alloc_ptr.get_ty() == AllocationPtr::Ty::Function, "Calling value that isn't a function pointer"); + LOG_ASSERT(fcn_alloc_ptr.get_ty() == RelocationPtr::Ty::Function, "Calling value that isn't a function pointer"); fcn_p = &fcn_alloc_ptr.fcn(); } @@ -1717,12 +1713,12 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c rv = Value(rty); rv.write_usize(0, 0); // TODO: Use the alignment when making an allocation? - rv.allocation.alloc().relocations.push_back({ 0, Allocation::new_alloc(size) }); + rv.allocation->relocations.push_back({ 0, RelocationPtr::new_alloc(Allocation::new_alloc(size)) }); } else if( link_name == "__rust_reallocate" ) { LOG_ASSERT(args.at(0).allocation, "__rust_reallocate first argument doesn't have an allocation"); - auto alloc_ptr = args.at(0).allocation.alloc().get_relocation(0); + auto alloc_ptr = args.at(0).get_relocation(0); auto ptr_ofs = args.at(0).read_usize(0); LOG_ASSERT(ptr_ofs == 0, "__rust_reallocate with offset pointer"); auto oldsize = args.at(1).read_usize(0); @@ -1742,7 +1738,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c else if( link_name == "__rust_deallocate" ) { LOG_ASSERT(args.at(0).allocation, "__rust_deallocate first argument doesn't have an allocation"); - auto alloc_ptr = args.at(0).allocation.alloc().get_relocation(0); + auto alloc_ptr = args.at(0).get_relocation(0); auto ptr_ofs = args.at(0).read_usize(0); LOG_ASSERT(ptr_ofs == 0, "__rust_deallocate with offset pointer"); LOG_DEBUG("__rust_deallocate(ptr=" << alloc_ptr << ")"); @@ -1948,8 +1944,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c // - `void *memchr(const void *s, int c, size_t n);` else if( link_name == "memchr" ) { - LOG_ASSERT(args.at(0).allocation.is_alloc(), ""); - auto ptr_alloc = args.at(0).allocation.alloc().get_relocation(0); + auto ptr_alloc = args.at(0).get_relocation(0); auto c = args.at(1).read_i32(0); auto n = args.at(2).read_usize(0); const void* ptr = args.at(0).read_pointer_const(0, n); @@ -1961,7 +1956,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c if( ret ) { rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast(ret) - static_cast(ptr) )); - rv.allocation.alloc().relocations.push_back({ 0, ptr_alloc }); + rv.allocation->relocations.push_back({ 0, ptr_alloc }); } else { @@ -1982,7 +1977,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c if( ret ) { rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast(ret) - static_cast(ptr) )); - rv.allocation.alloc().relocations.push_back({ 0, ptr_alloc }); + rv.allocation->relocations.push_back({ 0, ptr_alloc }); } else { @@ -2027,9 +2022,7 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_store of a value that isn't a pointer-sized value"); // There MUST be a relocation at this point with a valid allocation. - LOG_ASSERT(ptr_val.allocation, "Deref of a value with no allocation (hence no relocations)"); - LOG_TRACE("Deref " << ptr_val.allocation.alloc()); - auto alloc = ptr_val.allocation.alloc().get_relocation(0); + auto alloc = ptr_val.get_relocation(0); LOG_ASSERT(alloc, "Deref of a value with no relocation"); // TODO: Atomic side of this? @@ -2042,9 +2035,7 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_store of a value that isn't a pointer-sized value"); // There MUST be a relocation at this point with a valid allocation. - LOG_ASSERT(ptr_val.allocation, "Deref of a value with no allocation (hence no relocations)"); - LOG_TRACE("Deref " << ptr_val.allocation.alloc()); - auto alloc = ptr_val.allocation.alloc().get_relocation(0); + auto alloc = ptr_val.get_relocation(0); LOG_ASSERT(alloc, "Deref of a value with no relocation"); // TODO: Atomic lock the allocation. @@ -2057,7 +2048,7 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con { const auto& ty_T = ty_params.tys.at(0); auto ptr_ofs = args.at(0).read_usize(0); - auto ptr_alloc = args.at(0).allocation.alloc().get_relocation(0); + auto ptr_alloc = args.at(0).get_relocation(0); auto v = args.at(1).read_value(0, ty_T.get_size()); // TODO: Atomic lock the allocation. @@ -2078,7 +2069,7 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con { const auto& ty_T = ty_params.tys.at(0); auto ptr_ofs = args.at(0).read_usize(0); - auto ptr_alloc = args.at(0).allocation.alloc().get_relocation(0); + auto ptr_alloc = args.at(0).get_relocation(0); auto v = args.at(1).read_value(0, ty_T.get_size()); // TODO: Atomic lock the allocation. @@ -2146,7 +2137,7 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con rv = ::std::move(args.at(0)); rv.write_usize(0, new_ofs); if( ptr_alloc ) { - rv.allocation.alloc().relocations.push_back({ 0, ptr_alloc }); + rv.allocation->relocations.push_back({ 0, ptr_alloc }); } } // effectively ptr::write @@ -2160,12 +2151,13 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con // There MUST be a relocation at this point with a valid allocation. LOG_ASSERT(ptr_val.allocation, "Deref of a value with no allocation (hence no relocations)"); LOG_TRACE("Deref " << ptr_val << " and store " << data_val); - auto alloc = ptr_val.allocation.alloc().get_relocation(0); - LOG_ASSERT(alloc, "Deref of a value with no relocation"); + + auto ptr_alloc = ptr_val.get_relocation(0); + LOG_ASSERT(ptr_alloc, "Deref of a value with no relocation"); size_t ofs = ptr_val.read_usize(0); - alloc.alloc().write_value(ofs, ::std::move(data_val)); - LOG_DEBUG(alloc.alloc()); + ptr_alloc.alloc().write_value(ofs, ::std::move(data_val)); + LOG_DEBUG(ptr_alloc.alloc()); } else if( name == "uninit" ) { @@ -2330,9 +2322,9 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con else if( name == "copy_nonoverlapping" ) { auto src_ofs = args.at(0).read_usize(0); - auto src_alloc = args.at(0).allocation.alloc().get_relocation(0); + auto src_alloc = args.at(0).get_relocation(0); auto dst_ofs = args.at(1).read_usize(0); - auto dst_alloc = args.at(1).allocation.alloc().get_relocation(0); + auto dst_alloc = args.at(1).get_relocation(0); size_t ent_count = args.at(2).read_usize(0); size_t ent_size = ty_params.tys.at(0).get_size(); auto byte_count = ent_count * ent_size; @@ -2343,21 +2335,21 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con switch(src_alloc.get_ty()) { - case AllocationPtr::Ty::Allocation: { + case RelocationPtr::Ty::Allocation: { auto v = src_alloc.alloc().read_value(src_ofs, byte_count); LOG_DEBUG("v = " << v); dst_alloc.alloc().write_value(dst_ofs, ::std::move(v)); } break; - case AllocationPtr::Ty::StdString: + case RelocationPtr::Ty::StdString: LOG_ASSERT(src_ofs <= src_alloc.str().size(), ""); LOG_ASSERT(byte_count <= src_alloc.str().size(), ""); LOG_ASSERT(src_ofs + byte_count <= src_alloc.str().size(), ""); dst_alloc.alloc().write_bytes(dst_ofs, src_alloc.str().data() + src_ofs, byte_count); break; - case AllocationPtr::Ty::Function: + case RelocationPtr::Ty::Function: LOG_FATAL("Attempt to copy* a function"); break; - case AllocationPtr::Ty::FfiPointer: + case RelocationPtr::Ty::FfiPointer: LOG_BUG("Trying to copy from a FFI pointer"); break; } diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index ad41b33a..6a7a0b5f 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -151,13 +151,13 @@ bool Parser::parse_one() auto a = Allocation::new_alloc( reloc_str.size() ); //a.alloc().set_tag(); - a.alloc().write_bytes(0, reloc_str.data(), reloc_str.size()); - s.val.allocation.alloc().relocations.push_back({ ofs, ::std::move(a) }); + a->write_bytes(0, reloc_str.data(), reloc_str.size()); + s.val.allocation->relocations.push_back({ ofs, RelocationPtr::new_alloc(::std::move(a)) }); } else if( lex.next() == "::" || lex.next() == "<" ) { auto reloc_path = parse_path(); - s.val.allocation.alloc().relocations.push_back({ ofs, AllocationPtr::new_fcn(reloc_path) }); + s.val.allocation->relocations.push_back({ ofs, RelocationPtr::new_fcn(reloc_path) }); } else { diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index cdace6e2..d8eeee01 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -9,49 +9,79 @@ #include #include "debug.hpp" -AllocationPtr Allocation::new_alloc(size_t size) +AllocationHandle Allocation::new_alloc(size_t size) { Allocation* rv = new Allocation(); rv->refcount = 1; rv->data.resize( (size + 8-1) / 8 ); // QWORDS rv->mask.resize( (size + 8-1) / 8 ); // bitmap bytes //LOG_DEBUG(rv << " ALLOC"); - return AllocationPtr(rv); + return AllocationHandle(rv); } -AllocationPtr AllocationPtr::new_fcn(::HIR::Path p) +AllocationHandle::AllocationHandle(const AllocationHandle& x): + m_ptr(x.m_ptr) { - AllocationPtr rv; + if( m_ptr ) + { + assert(m_ptr->refcount != 0); + assert(m_ptr->refcount != SIZE_MAX); + m_ptr->refcount += 1; + //LOG_DEBUG(m_ptr << " REF++ " << m_ptr->refcount); + } +} +AllocationHandle::~AllocationHandle() +{ + if( m_ptr ) + { + m_ptr->refcount -= 1; + //LOG_DEBUG(m_ptr << " REF-- " << m_ptr->refcount); + if(m_ptr->refcount == 0) + { + delete m_ptr; + } + } +} + +RelocationPtr RelocationPtr::new_alloc(AllocationHandle alloc) +{ + RelocationPtr rv; + auto* ptr = alloc.m_ptr; + alloc.m_ptr = nullptr; + rv.m_ptr = reinterpret_cast( reinterpret_cast(ptr) + static_cast(Ty::Allocation) ); + return rv; +} +RelocationPtr RelocationPtr::new_fcn(::HIR::Path p) +{ + RelocationPtr rv; auto* ptr = new ::HIR::Path(::std::move(p)); rv.m_ptr = reinterpret_cast( reinterpret_cast(ptr) + static_cast(Ty::Function) ); return rv; } -AllocationPtr AllocationPtr::new_string(const ::std::string* ptr) +RelocationPtr RelocationPtr::new_string(const ::std::string* ptr) { - AllocationPtr rv; + RelocationPtr rv; rv.m_ptr = reinterpret_cast( reinterpret_cast(ptr) + static_cast(Ty::StdString) ); return rv; } -AllocationPtr AllocationPtr::new_ffi(FFIPointer info) +RelocationPtr RelocationPtr::new_ffi(FFIPointer info) { - AllocationPtr rv; + RelocationPtr rv; auto* ptr = new FFIPointer(info); rv.m_ptr = reinterpret_cast( reinterpret_cast(ptr) + static_cast(Ty::FfiPointer) ); return rv; } -AllocationPtr::AllocationPtr(const AllocationPtr& x): +RelocationPtr::RelocationPtr(const RelocationPtr& x): m_ptr(nullptr) { if( x ) { switch(x.get_ty()) { - case Ty::Allocation: - m_ptr = x.m_ptr; - assert(alloc().refcount != 0); - assert(alloc().refcount != SIZE_MAX); - alloc().refcount += 1; - //LOG_DEBUG(&alloc() << " REF++ " << alloc().refcount); - break; + case Ty::Allocation: { + auto tmp = AllocationHandle( reinterpret_cast(x.get_ptr()) ); + *this = RelocationPtr::new_alloc(tmp); + tmp.m_ptr = nullptr; + } break; case Ty::Function: { auto ptr_i = reinterpret_cast(new ::HIR::Path(x.fcn())); assert( (ptr_i & 3) == 0 ); @@ -75,21 +105,15 @@ AllocationPtr::AllocationPtr(const AllocationPtr& x): m_ptr = nullptr; } } -AllocationPtr::~AllocationPtr() +RelocationPtr::~RelocationPtr() { if( *this ) { switch(get_ty()) { - case Ty::Allocation: { - auto* ptr = &alloc(); - ptr->refcount -= 1; - //LOG_DEBUG(&alloc() << " REF-- " << ptr->refcount); - if(ptr->refcount == 0) - { - delete ptr; - } - } break; + case Ty::Allocation: + (void)AllocationHandle( reinterpret_cast(get_ptr()) ); + break; case Ty::Function: { auto* ptr = const_cast<::HIR::Path*>(&fcn()); delete ptr; @@ -104,7 +128,7 @@ AllocationPtr::~AllocationPtr() } } } -size_t AllocationPtr::get_size() const +size_t RelocationPtr::get_size() const { if( !*this ) return 0; @@ -123,22 +147,22 @@ size_t AllocationPtr::get_size() const throw "Unreachable"; } -::std::ostream& operator<<(::std::ostream& os, const AllocationPtr& x) +::std::ostream& operator<<(::std::ostream& os, const RelocationPtr& x) { if( x ) { switch(x.get_ty()) { - case AllocationPtr::Ty::Allocation: + case RelocationPtr::Ty::Allocation: os << &x.alloc(); break; - case AllocationPtr::Ty::Function: + case RelocationPtr::Ty::Function: os << x.fcn(); break; - case AllocationPtr::Ty::StdString: + case RelocationPtr::Ty::StdString: os << "\"" << x.str() << "\""; break; - case AllocationPtr::Ty::FfiPointer: + case RelocationPtr::Ty::FfiPointer: os << "FFI " << x.ffi().source_function << " " << x.ffi().ptr_value; break; } @@ -150,17 +174,17 @@ size_t AllocationPtr::get_size() const return os; } -uint64_t ValueCommon::read_usize(size_t ofs) const +uint64_t ValueCommonRead::read_usize(size_t ofs) const { uint64_t v = 0; this->read_bytes(ofs, &v, POINTER_SIZE); return v; } -void ValueCommon::write_usize(size_t ofs, uint64_t v) +void ValueCommonWrite::write_usize(size_t ofs, uint64_t v) { this->write_bytes(ofs, &v, POINTER_SIZE); } -void* ValueCommon::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& out_size, bool& out_is_mut) const +void* ValueCommonRead::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& out_size, bool& out_is_mut) const { auto ofs = read_usize(rd_ofs); auto reloc = get_relocation(rd_ofs); @@ -180,7 +204,7 @@ void* ValueCommon::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& { switch(reloc.get_ty()) { - case AllocationPtr::Ty::Allocation: { + case RelocationPtr::Ty::Allocation: { auto& a = reloc.alloc(); if( ofs > a.size() ) LOG_FATAL("Out-of-bounds pointer"); @@ -191,7 +215,7 @@ void* ValueCommon::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& out_is_mut = true; return a.data_ptr() + ofs; } - case AllocationPtr::Ty::StdString: { + case RelocationPtr::Ty::StdString: { const auto& s = reloc.str(); if( ofs > s.size() ) LOG_FATAL("Out-of-bounds pointer"); @@ -201,9 +225,9 @@ void* ValueCommon::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& out_is_mut = false; return const_cast( static_cast(s.data() + ofs) ); } - case AllocationPtr::Ty::Function: + case RelocationPtr::Ty::Function: LOG_FATAL("read_pointer w/ function"); - case AllocationPtr::Ty::FfiPointer: + case RelocationPtr::Ty::FfiPointer: if( req_valid ) LOG_FATAL("Can't request valid data from a FFI pointer"); // TODO: Have an idea of mutability and available size from FFI @@ -214,7 +238,7 @@ void* ValueCommon::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size_t& throw ""; } } -ValueRef ValueCommon::read_pointer_valref_mut(size_t rd_ofs, size_t size) +ValueRef ValueCommonRead::read_pointer_valref_mut(size_t rd_ofs, size_t size) { auto ofs = read_usize(rd_ofs); auto reloc = get_relocation(rd_ofs); @@ -290,7 +314,7 @@ Value Allocation::read_value(size_t ofs, size_t size) const { if( ofs <= r.slot_ofs && r.slot_ofs < ofs + size ) { - rv.allocation.alloc().relocations.push_back({ r.slot_ofs - ofs, r.backing_alloc }); + rv.allocation->relocations.push_back({ r.slot_ofs - ofs, r.backing_alloc }); } } @@ -303,7 +327,7 @@ Value Allocation::read_value(size_t ofs, size_t size) const bool v = (this->mask[j/8] & test_mask) != 0; if( v ) { - rv.allocation.alloc().mask[i/8] |= set_mask; + rv.allocation->mask[i/8] |= set_mask; } } } @@ -365,8 +389,8 @@ void Allocation::write_value(size_t ofs, Value v) // LOG_ERROR("Writing to read-only allocation " << this); if( v.allocation ) { - size_t v_size = v.allocation.alloc().size(); - const auto& src_alloc = v.allocation.alloc(); + size_t v_size = v.allocation->size(); + const auto& src_alloc = *v.allocation; // Take a copy of the source mask auto s_mask = src_alloc.mask; @@ -575,18 +599,18 @@ Value Value::new_fnptr(const ::HIR::Path& fn_path) { Value rv( ::HIR::TypeRef(::HIR::CoreType { RawType::Function }) ); assert(rv.allocation); - rv.allocation.alloc().relocations.push_back(Relocation { 0, AllocationPtr::new_fcn(fn_path) }); - rv.allocation.alloc().data.at(0) = 0; - rv.allocation.alloc().mask.at(0) = 0xFF; // TODO: Get pointer size and make that much valid instead of 8 bytes + rv.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_fcn(fn_path) }); + rv.allocation->data.at(0) = 0; + rv.allocation->mask.at(0) = 0xFF; // TODO: Get pointer size and make that much valid instead of 8 bytes return rv; } Value Value::new_ffiptr(FFIPointer ffi) { Value rv( ::HIR::TypeRef(::HIR::CoreType { RawType::USize }) ); rv.create_allocation(); - rv.allocation.alloc().relocations.push_back(Relocation { 0, AllocationPtr::new_ffi(ffi) }); - rv.allocation.alloc().data.at(0) = 0; - rv.allocation.alloc().mask.at(0) = 0xFF; // TODO: Get pointer size and make that much valid instead of 8 bytes + rv.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_ffi(ffi) }); + rv.allocation->data.at(0) = 0; + rv.allocation->mask.at(0) = 0xFF; // TODO: Get pointer size and make that much valid instead of 8 bytes return rv; } @@ -595,10 +619,10 @@ void Value::create_allocation() assert(!this->allocation); this->allocation = Allocation::new_alloc(this->direct_data.size); if( this->direct_data.size > 0 ) - this->allocation.alloc().mask[0] = this->direct_data.mask[0]; + this->allocation->mask[0] = this->direct_data.mask[0]; if( this->direct_data.size > 8 ) - this->allocation.alloc().mask[1] = this->direct_data.mask[1]; - ::std::memcpy(this->allocation.alloc().data.data(), this->direct_data.data, this->direct_data.size); + this->allocation->mask[1] = this->direct_data.mask[1]; + ::std::memcpy(this->allocation->data.data(), this->direct_data.data, this->direct_data.size); } void Value::check_bytes_valid(size_t ofs, size_t size) const { @@ -606,7 +630,7 @@ void Value::check_bytes_valid(size_t ofs, size_t size) const return ; if( this->allocation ) { - this->allocation.alloc().check_bytes_valid(ofs, size); + this->allocation->check_bytes_valid(ofs, size); } else { @@ -635,7 +659,7 @@ void Value::mark_bytes_valid(size_t ofs, size_t size) { if( this->allocation ) { - this->allocation.alloc().mark_bytes_valid(ofs, size); + this->allocation->mark_bytes_valid(ofs, size); } else { @@ -652,7 +676,7 @@ Value Value::read_value(size_t ofs, size_t size) const //TRACE_FUNCTION_R(ofs << ", " << size << ") - " << *this, rv); if( this->allocation ) { - rv = this->allocation.alloc().read_value(ofs, size); + rv = this->allocation->read_value(ofs, size); } else { @@ -670,7 +694,7 @@ void Value::read_bytes(size_t ofs, void* dst, size_t count) const return ; if( this->allocation ) { - this->allocation.alloc().read_bytes(ofs, dst, count); + this->allocation->read_bytes(ofs, dst, count); } else { @@ -698,7 +722,7 @@ void Value::write_bytes(size_t ofs, const void* src, size_t count) return ; if( this->allocation ) { - this->allocation.alloc().write_bytes(ofs, src, count); + this->allocation->write_bytes(ofs, src, count); } else { @@ -719,14 +743,14 @@ void Value::write_value(size_t ofs, Value v) { if( this->allocation ) { - this->allocation.alloc().write_value(ofs, ::std::move(v)); + this->allocation->write_value(ofs, ::std::move(v)); } else { - if( v.allocation && !v.allocation.alloc().relocations.empty() ) + if( v.allocation && !v.allocation->relocations.empty() ) { this->create_allocation(); - this->allocation.alloc().write_value(ofs, ::std::move(v)); + this->allocation->write_value(ofs, ::std::move(v)); } else { @@ -749,7 +773,7 @@ void Value::write_value(size_t ofs, Value v) { if( v.allocation ) { - os << v.allocation.alloc(); + os << *v.allocation; } else { @@ -776,13 +800,13 @@ extern ::std::ostream& operator<<(::std::ostream& os, const ValueRef& v) { if( v.m_size == 0 ) return os; - if( v.m_alloc || v.m_value->allocation ) + if( v.m_alloc ) { - const auto& alloc_ptr = v.m_alloc ? v.m_alloc : v.m_value->allocation; + const auto& alloc_ptr = v.m_alloc;; // TODO: What if alloc_ptr isn't a data allocation? switch(alloc_ptr.get_ty()) { - case AllocationPtr::Ty::Allocation: { + case RelocationPtr::Ty::Allocation: { const auto& alloc = alloc_ptr.alloc(); auto flags = os.flags(); @@ -813,10 +837,10 @@ extern ::std::ostream& operator<<(::std::ostream& os, const ValueRef& v) } os << " }"; } break; - case AllocationPtr::Ty::Function: + case RelocationPtr::Ty::Function: LOG_TODO("ValueRef to " << alloc_ptr); break; - case AllocationPtr::Ty::StdString: { + case RelocationPtr::Ty::StdString: { const auto& s = alloc_ptr.str(); assert(v.m_offset < s.size()); assert(v.m_size < s.size()); @@ -829,12 +853,44 @@ extern ::std::ostream& operator<<(::std::ostream& os, const ValueRef& v) } os.setf(flags); } break; - case AllocationPtr::Ty::FfiPointer: + case RelocationPtr::Ty::FfiPointer: LOG_TODO("ValueRef to " << alloc_ptr); break; } } - else + else if( v.m_value && v.m_value->allocation ) + { + const auto& alloc = *v.m_value->allocation; + + auto flags = os.flags(); + os << ::std::hex; + for(size_t i = v.m_offset; i < ::std::min(alloc.size(), v.m_offset + v.m_size); i++) + { + if( i != 0 ) + os << " "; + + if( alloc.mask[i/8] & (1 << i%8) ) + { + os << ::std::setw(2) << ::std::setfill('0') << (int)alloc.data_ptr()[i]; + } + else + { + os << "--"; + } + } + os.setf(flags); + + os << " {"; + for(const auto& r : alloc.relocations) + { + if( v.m_offset <= r.slot_ofs && r.slot_ofs < v.m_offset + v.m_size ) + { + os << " @" << (r.slot_ofs - v.m_offset) << "=" << r.backing_alloc; + } + } + os << " }"; + } + else if( v.m_value ) { const auto& direct = v.m_value->direct_data; @@ -855,6 +911,10 @@ extern ::std::ostream& operator<<(::std::ostream& os, const ValueRef& v) } os.setf(flags); } + else + { + // TODO: no value? + } return os; } @@ -868,9 +928,9 @@ Value ValueRef::read_value(size_t ofs, size_t size) const if( m_alloc ) { switch(m_alloc.get_ty()) { - case AllocationPtr::Ty::Allocation: + case RelocationPtr::Ty::Allocation: return m_alloc.alloc().read_value(m_offset + ofs, size); - case AllocationPtr::Ty::StdString: { + case RelocationPtr::Ty::StdString: { auto rv = Value::with_size(size, false); //ASSERT_BUG(ofs <= m_alloc.str().size(), ""); //ASSERT_BUG(size <= m_alloc.str().size(), ""); @@ -893,9 +953,3 @@ bool ValueRef::compare(const void* other, size_t other_len) const check_bytes_valid(0, other_len); return ::std::memcmp(data_ptr(), other, other_len) == 0; } -uint64_t ValueRef::read_usize(size_t ofs) const -{ - uint64_t v = 0; - this->read_bytes(ofs, &v, POINTER_SIZE); - return v; -} diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index aa41b838..4da2eee6 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -23,12 +23,46 @@ struct FFIPointer void* ptr_value; }; -class AllocationPtr +class AllocationHandle { friend class Allocation; - void* m_ptr; + friend class RelocationPtr; + Allocation* m_ptr; + +private: + AllocationHandle(Allocation* p): + m_ptr(p) + { + } public: + AllocationHandle(): m_ptr(nullptr) {} + AllocationHandle(AllocationHandle&& x): m_ptr(x.m_ptr) { + x.m_ptr = nullptr; + } + AllocationHandle(const AllocationHandle& x); + ~AllocationHandle(); + + AllocationHandle& operator=(const AllocationHandle& x) = delete; + AllocationHandle& operator=(AllocationHandle&& x) { + this->~AllocationHandle(); + this->m_ptr = x.m_ptr; + x.m_ptr = nullptr; + return *this; + } + operator bool() const { return m_ptr != 0; } + const Allocation& operator*() const { assert(m_ptr); return *m_ptr; } + Allocation& operator*() { assert(m_ptr); return *m_ptr; } + const Allocation* operator->() const { assert(m_ptr); return m_ptr; } + Allocation* operator->() { assert(m_ptr); return m_ptr; } +}; + +// TODO: Split into RelocationPtr and AllocationHandle +class RelocationPtr +{ + void* m_ptr; + +public: enum class Ty { Allocation, @@ -37,26 +71,20 @@ public: FfiPointer, }; -private: - AllocationPtr(Allocation* p): - m_ptr(p) - { - } -public: - AllocationPtr(): m_ptr(nullptr) {} - AllocationPtr(AllocationPtr&& x): m_ptr(x.m_ptr) { + RelocationPtr(): m_ptr(nullptr) {} + RelocationPtr(RelocationPtr&& x): m_ptr(x.m_ptr) { x.m_ptr = nullptr; } - AllocationPtr(const AllocationPtr& x); - ~AllocationPtr(); - static AllocationPtr new_fcn(::HIR::Path p); - //static AllocationPtr new_rawdata(const void* buf, size_t len); - static AllocationPtr new_string(const ::std::string* s); // NOTE: The string must have a stable pointer - static AllocationPtr new_ffi(FFIPointer info); - - AllocationPtr& operator=(const AllocationPtr& x) = delete; - AllocationPtr& operator=(AllocationPtr&& x) { - this->~AllocationPtr(); + RelocationPtr(const RelocationPtr& x); + ~RelocationPtr(); + static RelocationPtr new_alloc(AllocationHandle h); + static RelocationPtr new_fcn(::HIR::Path p); + static RelocationPtr new_string(const ::std::string* s); // NOTE: The string must have a stable pointer + static RelocationPtr new_ffi(FFIPointer info); + + RelocationPtr& operator=(const RelocationPtr& x) = delete; + RelocationPtr& operator=(RelocationPtr&& x) { + this->~RelocationPtr(); this->m_ptr = x.m_ptr; x.m_ptr = nullptr; return *this; @@ -98,7 +126,7 @@ public: return static_cast( reinterpret_cast(m_ptr) & 3 ); } - friend ::std::ostream& operator<<(::std::ostream& os, const AllocationPtr& x); + friend ::std::ostream& operator<<(::std::ostream& os, const RelocationPtr& x); private: void* get_ptr() const { return reinterpret_cast( reinterpret_cast(m_ptr) & ~3 ); @@ -109,27 +137,14 @@ struct Relocation // Offset within parent allocation where this relocation is performed. // TODO: Size? size_t slot_ofs; - AllocationPtr backing_alloc; + RelocationPtr backing_alloc; }; -struct ValueCommon +// TODO: Split write and read +struct ValueCommonRead { - virtual AllocationPtr get_relocation(size_t ofs) const = 0; + virtual RelocationPtr get_relocation(size_t ofs) const = 0; virtual void read_bytes(size_t ofs, void* dst, size_t count) const = 0; - virtual void write_bytes(size_t ofs, const void* src, size_t count) = 0; - - void write_u8 (size_t ofs, uint8_t v) { write_bytes(ofs, &v, 1); } - void write_u16(size_t ofs, uint16_t v) { write_bytes(ofs, &v, 2); } - void write_u32(size_t ofs, uint32_t v) { write_bytes(ofs, &v, 4); } - void write_u64(size_t ofs, uint64_t v) { write_bytes(ofs, &v, 8); } - void write_i8 (size_t ofs, int8_t v) { write_u8 (ofs, static_cast(v)); } - void write_i16(size_t ofs, int16_t v) { write_u16(ofs, static_cast(v)); } - void write_i32(size_t ofs, int32_t v) { write_u32(ofs, static_cast(v)); } - void write_i64(size_t ofs, int64_t v) { write_u64(ofs, static_cast(v)); } - void write_f32(size_t ofs, float v) { write_bytes(ofs, &v, 4); } - void write_f64(size_t ofs, double v) { write_bytes(ofs, &v, 8); } - void write_usize(size_t ofs, uint64_t v); - void write_isize(size_t ofs, int64_t v) { write_usize(ofs, static_cast(v)); } uint8_t read_u8(size_t ofs) const { uint8_t rv; read_bytes(ofs, &rv, 1); return rv; } uint16_t read_u16(size_t ofs) const { uint16_t rv; read_bytes(ofs, &rv, 2); return rv; } @@ -164,16 +179,34 @@ struct ValueCommon /// Read a pointer and return a ValueRef to it (mutable data) ValueRef read_pointer_valref_mut(size_t rd_ofs, size_t size); }; +struct ValueCommonWrite: + public ValueCommonRead +{ + virtual void write_bytes(size_t ofs, const void* src, size_t count) = 0; + + void write_u8 (size_t ofs, uint8_t v) { write_bytes(ofs, &v, 1); } + void write_u16(size_t ofs, uint16_t v) { write_bytes(ofs, &v, 2); } + void write_u32(size_t ofs, uint32_t v) { write_bytes(ofs, &v, 4); } + void write_u64(size_t ofs, uint64_t v) { write_bytes(ofs, &v, 8); } + void write_i8 (size_t ofs, int8_t v) { write_u8 (ofs, static_cast(v)); } + void write_i16(size_t ofs, int16_t v) { write_u16(ofs, static_cast(v)); } + void write_i32(size_t ofs, int32_t v) { write_u32(ofs, static_cast(v)); } + void write_i64(size_t ofs, int64_t v) { write_u64(ofs, static_cast(v)); } + void write_f32(size_t ofs, float v) { write_bytes(ofs, &v, 4); } + void write_f64(size_t ofs, double v) { write_bytes(ofs, &v, 8); } + void write_usize(size_t ofs, uint64_t v); + void write_isize(size_t ofs, int64_t v) { write_usize(ofs, static_cast(v)); } +}; class Allocation: - public ValueCommon + public ValueCommonWrite { - friend class AllocationPtr; + friend class AllocationHandle; size_t refcount; // TODO: Read-only flag? bool is_freed = false; public: - static AllocationPtr new_alloc(size_t size); + static AllocationHandle new_alloc(size_t size); const uint8_t* data_ptr() const { return reinterpret_cast(this->data.data()); } uint8_t* data_ptr() { return reinterpret_cast< uint8_t*>(this->data.data()); } @@ -183,12 +216,12 @@ public: ::std::vector mask; ::std::vector relocations; - AllocationPtr get_relocation(size_t ofs) const override { + RelocationPtr get_relocation(size_t ofs) const override { for(const auto& r : relocations) { if(r.slot_ofs == ofs) return r.backing_alloc; } - return AllocationPtr(); + return RelocationPtr(); } void mark_as_freed() { is_freed = true; @@ -211,10 +244,10 @@ public: extern ::std::ostream& operator<<(::std::ostream& os, const Allocation& x); struct Value: - public ValueCommon + public ValueCommonWrite { // If NULL, data is direct - AllocationPtr allocation; + AllocationHandle allocation; struct { uint8_t data[2*sizeof(size_t)-3]; // 16-3 = 13, fits in 16 bits of mask uint8_t mask[2]; @@ -228,15 +261,15 @@ struct Value: static Value new_ffiptr(FFIPointer ffi); void create_allocation(); - size_t size() const { return allocation ? allocation.alloc().size() : direct_data.size; } - const uint8_t* data_ptr() const { return allocation ? allocation.alloc().data_ptr() : direct_data.data; } - uint8_t* data_ptr() { return allocation ? allocation.alloc().data_ptr() : direct_data.data; } + size_t size() const { return allocation ? allocation->size() : direct_data.size; } + const uint8_t* data_ptr() const { return allocation ? allocation->data_ptr() : direct_data.data; } + uint8_t* data_ptr() { return allocation ? allocation->data_ptr() : direct_data.data; } - AllocationPtr get_relocation(size_t ofs) const override { - if( this->allocation && this->allocation.is_alloc() ) - return this->allocation.alloc().get_relocation(ofs); + RelocationPtr get_relocation(size_t ofs) const override { + if( this->allocation && this->allocation ) + return this->allocation->get_relocation(ofs); else - return AllocationPtr(); + return RelocationPtr(); } void check_bytes_valid(size_t ofs, size_t size) const; @@ -251,17 +284,17 @@ struct Value: extern ::std::ostream& operator<<(::std::ostream& os, const Value& v); // A read-only reference to a value (to write, you have to go through it) -struct ValueRef - //:public ValueCommon +struct ValueRef: + public ValueCommonRead { - // Either an AllocationPtr, or a Value pointer - AllocationPtr m_alloc; + // Either an AllocationHandle, or a Value pointer + RelocationPtr m_alloc; Value* m_value; size_t m_offset; // Offset within the value size_t m_size; // Size in bytes of the referenced value ::std::shared_ptr m_metadata; - ValueRef(AllocationPtr ptr, size_t ofs, size_t size): + ValueRef(RelocationPtr ptr, size_t ofs, size_t size): m_alloc(ptr), m_value(nullptr), m_offset(ofs), @@ -271,12 +304,12 @@ struct ValueRef { switch(m_alloc.get_ty()) { - case AllocationPtr::Ty::Allocation: + case RelocationPtr::Ty::Allocation: assert(ofs < m_alloc.alloc().size()); assert(size <= m_alloc.alloc().size()); assert(ofs+size <= m_alloc.alloc().size()); break; - case AllocationPtr::Ty::StdString: + case RelocationPtr::Ty::StdString: assert(ofs < m_alloc.str().size()); assert(size <= m_alloc.str().size()); assert(ofs+size <= m_alloc.str().size()); @@ -297,24 +330,21 @@ struct ValueRef { } - AllocationPtr get_relocation(size_t ofs) const { + RelocationPtr get_relocation(size_t ofs) const override { if(m_alloc) { if( m_alloc.is_alloc() ) return m_alloc.alloc().get_relocation(ofs); else - return AllocationPtr(); + return RelocationPtr(); } - else if( m_value && m_value->allocation ) + else if( m_value ) { - if( m_value->allocation.is_alloc() ) - return m_value->allocation.alloc().get_relocation(ofs); - else - return AllocationPtr(); + return m_value->get_relocation(ofs); } else { - return AllocationPtr(); + return RelocationPtr(); } } Value read_value(size_t ofs, size_t size) const; @@ -322,10 +352,10 @@ struct ValueRef if( m_alloc ) { switch(m_alloc.get_ty()) { - case AllocationPtr::Ty::Allocation: + case RelocationPtr::Ty::Allocation: return m_alloc.alloc().data_ptr() + m_offset; break; - case AllocationPtr::Ty::StdString: + case RelocationPtr::Ty::StdString: return reinterpret_cast(m_alloc.str().data() + m_offset); default: throw "TODO"; @@ -347,10 +377,10 @@ struct ValueRef if( m_alloc ) { switch(m_alloc.get_ty()) { - case AllocationPtr::Ty::Allocation: + case RelocationPtr::Ty::Allocation: m_alloc.alloc().read_bytes(m_offset + ofs, dst, size); break; - case AllocationPtr::Ty::StdString: + case RelocationPtr::Ty::StdString: assert(m_offset+ofs <= m_alloc.str().size() && size <= m_alloc.str().size() && m_offset+ofs+size <= m_alloc.str().size()); ::std::memcpy(dst, m_alloc.str().data() + m_offset + ofs, size); break; @@ -372,10 +402,10 @@ struct ValueRef if( m_alloc ) { switch(m_alloc.get_ty()) { - case AllocationPtr::Ty::Allocation: + case RelocationPtr::Ty::Allocation: m_alloc.alloc().check_bytes_valid(m_offset + ofs, size); break; - case AllocationPtr::Ty::StdString: + case RelocationPtr::Ty::StdString: assert(m_offset+ofs <= m_alloc.str().size() && size <= m_alloc.str().size() && m_offset+ofs+size <= m_alloc.str().size()); break; default: @@ -389,19 +419,5 @@ struct ValueRef } bool compare(const void* other, size_t other_len) const; - - // TODO: Figure out how to make this use `ValueCommon` when it can't write. - uint8_t read_u8(size_t ofs) const { uint8_t rv; read_bytes(ofs, &rv, 1); return rv; } - uint16_t read_u16(size_t ofs) const { uint16_t rv; read_bytes(ofs, &rv, 2); return rv; } - uint32_t read_u32(size_t ofs) const { uint32_t rv; read_bytes(ofs, &rv, 4); return rv; } - uint64_t read_u64(size_t ofs) const { uint64_t rv; read_bytes(ofs, &rv, 8); return rv; } - int8_t read_i8(size_t ofs) const { return static_cast(read_u8(ofs)); } - int16_t read_i16(size_t ofs) const { return static_cast(read_u16(ofs)); } - int32_t read_i32(size_t ofs) const { return static_cast(read_u32(ofs)); } - int64_t read_i64(size_t ofs) const { return static_cast(read_u64(ofs)); } - float read_f32(size_t ofs) const { float rv; read_bytes(ofs, &rv, 4); return rv; } - double read_f64(size_t ofs) const { double rv; read_bytes(ofs, &rv, 8); return rv; } - uint64_t read_usize(size_t ofs) const; - int64_t read_isize(size_t ofs) const { return static_cast(read_usize(ofs)); } }; extern ::std::ostream& operator<<(::std::ostream& os, const ValueRef& v); -- cgit v1.2.3 From c6f9ca14a3295c497b0f5ef6eec3b902fd8af3e7 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Wed, 16 May 2018 21:35:16 +0800 Subject: Standalone MIRI - Split interpreter into its own file --- tools/standalone_miri/Makefile | 2 +- tools/standalone_miri/main.cpp | 2369 +--------------------------------------- tools/standalone_miri/miri.cpp | 2302 ++++++++++++++++++++++++++++++++++++++ tools/standalone_miri/miri.hpp | 79 ++ 4 files changed, 2387 insertions(+), 2365 deletions(-) create mode 100644 tools/standalone_miri/miri.cpp create mode 100644 tools/standalone_miri/miri.hpp (limited to 'tools') diff --git a/tools/standalone_miri/Makefile b/tools/standalone_miri/Makefile index 95e99c75..f4dc0d0d 100644 --- a/tools/standalone_miri/Makefile +++ b/tools/standalone_miri/Makefile @@ -11,7 +11,7 @@ V ?= @ OBJDIR := .obj/ BIN := ../bin/standalone_miri$(EXESUF) -OBJS := main.o debug.o mir.o lex.o value.o module_tree.o hir_sim.o +OBJS := main.o debug.o mir.o lex.o value.o module_tree.o hir_sim.o miri.o LINKFLAGS := -g -lpthread CXXFLAGS := -Wall -std=c++14 -g -O2 diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index cd521501..2011edfa 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -7,93 +7,19 @@ #include #include #include "debug.hpp" -#ifdef _WIN32 -# define NOMINMAX -# include -#endif +#include "miri.hpp" + struct ProgramOptions { ::std::string infile; + //TODO: Architecture file + //TODO: Loadable FFI descriptions + //TODO: Logfile int parse(int argc, const char* argv[]); }; -struct ThreadState -{ - static unsigned s_next_tls_key; - unsigned call_stack_depth; - ::std::vector tls_values; - - ThreadState(): - call_stack_depth(0) - { - } - - struct DecOnDrop { - unsigned* p; - ~DecOnDrop() { (*p) --; } - }; - DecOnDrop enter_function() { - this->call_stack_depth ++; - return DecOnDrop { &this->call_stack_depth }; - } -}; -unsigned ThreadState::s_next_tls_key = 1; - -class InterpreterThread -{ - friend struct MirHelpers; - struct StackFrame - { - ::std::function cb; - const Function& fcn; - Value ret; - ::std::vector args; - ::std::vector locals; - ::std::vector drop_flags; - - unsigned bb_idx; - unsigned stmt_idx; - - StackFrame(const Function& fcn, ::std::vector args); - static StackFrame make_wrapper(::std::function cb) { - static Function f; - StackFrame rv(f, {}); - rv.cb = ::std::move(cb); - return rv; - } - }; - - ModuleTree& m_modtree; - ThreadState m_thread; - ::std::vector m_stack; - -public: - InterpreterThread(ModuleTree& modtree): - m_modtree(modtree) - { - } - ~InterpreterThread(); - - void start(const ::HIR::Path& p, ::std::vector args); - // Returns `true` if the call stack empties - bool step_one(Value& out_thread_result); - -private: - bool pop_stack(Value& out_thread_result); - - // Returns true if the call was resolved instantly - bool call_path(Value& ret_val, const ::HIR::Path& p, ::std::vector args); - // Returns true if the call was resolved instantly - bool call_extern(Value& ret_val, const ::std::string& name, const ::std::string& abi, ::std::vector args); - // Returns true if the call was resolved instantly - bool call_intrinsic(Value& ret_val, const ::std::string& name, const ::HIR::PathParams& pp, ::std::vector args); - - // Returns true if the call was resolved instantly - bool drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_shallow=false); -}; - int main(int argc, const char* argv[]) { ProgramOptions opts; @@ -143,2291 +69,6 @@ int main(int argc, const char* argv[]) return 0; } -class PrimitiveValue -{ -public: - virtual ~PrimitiveValue() {} - - virtual bool add(const PrimitiveValue& v) = 0; - virtual bool subtract(const PrimitiveValue& v) = 0; - virtual bool multiply(const PrimitiveValue& v) = 0; - virtual bool divide(const PrimitiveValue& v) = 0; - virtual bool modulo(const PrimitiveValue& v) = 0; - virtual void write_to_value(ValueCommonWrite& tgt, size_t ofs) const = 0; - - template - const T& check(const char* opname) const - { - const auto* xp = dynamic_cast(this); - LOG_ASSERT(xp, "Attempting to " << opname << " mismatched types, expected " << typeid(T).name() << " got " << typeid(*this).name()); - return *xp; - } -}; -template -struct PrimitiveUInt: - public PrimitiveValue -{ - typedef PrimitiveUInt Self; - T v; - - PrimitiveUInt(T v): v(v) {} - ~PrimitiveUInt() override {} - - bool add(const PrimitiveValue& x) override { - const auto* xp = &x.check("add"); - T newv = this->v + xp->v; - bool did_overflow = newv < this->v; - this->v = newv; - return !did_overflow; - } - bool subtract(const PrimitiveValue& x) override { - const auto* xp = &x.check("subtract"); - T newv = this->v - xp->v; - bool did_overflow = newv > this->v; - this->v = newv; - return !did_overflow; - } - bool multiply(const PrimitiveValue& x) override { - const auto* xp = &x.check("multiply"); - T newv = this->v * xp->v; - bool did_overflow = newv < this->v && newv < xp->v; - this->v = newv; - return !did_overflow; - } - bool divide(const PrimitiveValue& x) override { - const auto* xp = &x.check("divide"); - if(xp->v == 0) return false; - T newv = this->v / xp->v; - this->v = newv; - return true; - } - bool modulo(const PrimitiveValue& x) override { - const auto* xp = &x.check("modulo"); - if(xp->v == 0) return false; - T newv = this->v % xp->v; - this->v = newv; - return true; - } -}; -struct PrimitiveU64: public PrimitiveUInt -{ - PrimitiveU64(uint64_t v): PrimitiveUInt(v) {} - void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { - tgt.write_u64(ofs, this->v); - } -}; -struct PrimitiveU32: public PrimitiveUInt -{ - PrimitiveU32(uint32_t v): PrimitiveUInt(v) {} - void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { - tgt.write_u32(ofs, this->v); - } -}; -template -struct PrimitiveSInt: - public PrimitiveValue -{ - typedef PrimitiveSInt Self; - T v; - - PrimitiveSInt(T v): v(v) {} - ~PrimitiveSInt() override {} - - // TODO: Make this correct. - bool add(const PrimitiveValue& x) override { - const auto* xp = &x.check("add"); - T newv = this->v + xp->v; - bool did_overflow = newv < this->v; - this->v = newv; - return !did_overflow; - } - bool subtract(const PrimitiveValue& x) override { - const auto* xp = &x.check("subtract"); - T newv = this->v - xp->v; - bool did_overflow = newv > this->v; - this->v = newv; - return !did_overflow; - } - bool multiply(const PrimitiveValue& x) override { - const auto* xp = &x.check("multiply"); - T newv = this->v * xp->v; - bool did_overflow = newv < this->v && newv < xp->v; - this->v = newv; - return !did_overflow; - } - bool divide(const PrimitiveValue& x) override { - const auto* xp = &x.check("divide"); - if(xp->v == 0) return false; - T newv = this->v / xp->v; - this->v = newv; - return true; - } - bool modulo(const PrimitiveValue& x) override { - const auto* xp = &x.check("modulo"); - if(xp->v == 0) return false; - T newv = this->v % xp->v; - this->v = newv; - return true; - } -}; -struct PrimitiveI64: public PrimitiveSInt -{ - PrimitiveI64(int64_t v): PrimitiveSInt(v) {} - void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { - tgt.write_i64(ofs, this->v); - } -}; -struct PrimitiveI32: public PrimitiveSInt -{ - PrimitiveI32(int32_t v): PrimitiveSInt(v) {} - void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { - tgt.write_i32(ofs, this->v); - } -}; - -class PrimitiveValueVirt -{ - uint64_t buf[3]; // Allows i128 plus a vtable pointer - PrimitiveValueVirt() {} -public: - // HACK: No copy/move constructors, assumes that contained data is always POD - ~PrimitiveValueVirt() { - reinterpret_cast(&this->buf)->~PrimitiveValue(); - } - PrimitiveValue& get() { return *reinterpret_cast(&this->buf); } - const PrimitiveValue& get() const { return *reinterpret_cast(&this->buf); } - - static PrimitiveValueVirt from_value(const ::HIR::TypeRef& t, const ValueRef& v) { - PrimitiveValueVirt rv; - LOG_ASSERT(t.wrappers.empty(), "PrimitiveValueVirt::from_value: " << t); - switch(t.inner_type) - { - case RawType::U32: - new(&rv.buf) PrimitiveU32(v.read_u32(0)); - break; - case RawType::U64: - new(&rv.buf) PrimitiveU64(v.read_u64(0)); - break; - case RawType::USize: - if( POINTER_SIZE == 8 ) - new(&rv.buf) PrimitiveU64(v.read_u64(0)); - else - new(&rv.buf) PrimitiveU32(v.read_u32(0)); - break; - - case RawType::I32: - new(&rv.buf) PrimitiveI32(v.read_i32(0)); - break; - case RawType::I64: - new(&rv.buf) PrimitiveI64(v.read_i64(0)); - break; - case RawType::ISize: - if( POINTER_SIZE == 8 ) - new(&rv.buf) PrimitiveI64(v.read_i64(0)); - else - new(&rv.buf) PrimitiveI32(v.read_i32(0)); - break; - default: - LOG_TODO("PrimitiveValueVirt::from_value: " << t); - } - return rv; - } -}; - -struct Ops { - template - static int do_compare(T l, T r) { - if( l == r ) { - return 0; - } - else if( !(l != r) ) { - // Special return value for NaN w/ NaN - return 2; - } - else if( l < r ) { - return -1; - } - else { - return 1; - } - } - template - static T do_bitwise(T l, T r, ::MIR::eBinOp op) { - switch(op) - { - case ::MIR::eBinOp::BIT_AND: return l & r; - case ::MIR::eBinOp::BIT_OR: return l | r; - case ::MIR::eBinOp::BIT_XOR: return l ^ r; - case ::MIR::eBinOp::BIT_SHL: return l << r; - case ::MIR::eBinOp::BIT_SHR: return l >> r; - default: - LOG_BUG("Unexpected operation in Ops::do_bitwise"); - } - } -}; - -struct MirHelpers -{ - InterpreterThread& thread; - InterpreterThread::StackFrame& frame; - - MirHelpers(InterpreterThread& thread, InterpreterThread::StackFrame& frame): - thread(thread), - frame(frame) - { - } - - ValueRef get_value_and_type(const ::MIR::LValue& lv, ::HIR::TypeRef& ty) - { - switch(lv.tag()) - { - case ::MIR::LValue::TAGDEAD: throw ""; - // --> Slots - TU_ARM(lv, Return, _e) { - ty = this->frame.fcn.ret_ty; - return ValueRef(this->frame.ret); - } break; - TU_ARM(lv, Local, e) { - ty = this->frame.fcn.m_mir.locals.at(e); - return ValueRef(this->frame.locals.at(e)); - } break; - TU_ARM(lv, Argument, e) { - ty = this->frame.fcn.args.at(e.idx); - return ValueRef(this->frame.args.at(e.idx)); - } break; - TU_ARM(lv, Static, e) { - /*const*/ auto& s = this->thread.m_modtree.get_static(e); - ty = s.ty; - return ValueRef(s.val); - } break; - // --> Modifiers - TU_ARM(lv, Index, e) { - auto idx = get_value_ref(*e.idx).read_usize(0); - ::HIR::TypeRef array_ty; - auto base_val = get_value_and_type(*e.val, array_ty); - if( array_ty.wrappers.empty() ) - LOG_ERROR("Indexing non-array/slice - " << array_ty); - if( array_ty.wrappers.front().type == TypeWrapper::Ty::Array ) - { - ty = array_ty.get_inner(); - base_val.m_offset += ty.get_size() * idx; - return base_val; - } - else if( array_ty.wrappers.front().type == TypeWrapper::Ty::Slice ) - { - LOG_TODO("Slice index"); - } - else - { - LOG_ERROR("Indexing non-array/slice - " << array_ty); - throw "ERROR"; - } - } break; - TU_ARM(lv, Field, e) { - ::HIR::TypeRef composite_ty; - auto base_val = get_value_and_type(*e.val, composite_ty); - // TODO: if there's metadata present in the base, but the inner doesn't have metadata, clear the metadata - size_t inner_ofs; - ty = composite_ty.get_field(e.field_index, inner_ofs); - LOG_DEBUG("Field - " << composite_ty << "#" << e.field_index << " = @" << inner_ofs << " " << ty); - base_val.m_offset += inner_ofs; - if( ty.get_meta_type() == HIR::TypeRef(RawType::Unreachable) ) - { - LOG_ASSERT(base_val.m_size >= ty.get_size(), "Field didn't fit in the value - " << ty.get_size() << " required, but " << base_val.m_size << " avail"); - base_val.m_size = ty.get_size(); - } - return base_val; - } - TU_ARM(lv, Downcast, e) { - ::HIR::TypeRef composite_ty; - auto base_val = get_value_and_type(*e.val, composite_ty); - LOG_DEBUG("Downcast - " << composite_ty); - - size_t inner_ofs; - ty = composite_ty.get_field(e.variant_index, inner_ofs); - base_val.m_offset += inner_ofs; - return base_val; - } - TU_ARM(lv, Deref, e) { - ::HIR::TypeRef ptr_ty; - auto val = get_value_and_type(*e.val, ptr_ty); - ty = ptr_ty.get_inner(); - LOG_DEBUG("val = " << val << ", (inner) ty=" << ty); - - LOG_ASSERT(val.m_size >= POINTER_SIZE, "Deref of a value that doesn't fit a pointer - " << ty); - size_t ofs = val.read_usize(0); - - // There MUST be a relocation at this point with a valid allocation. - auto alloc = val.get_relocation(val.m_offset); - LOG_TRACE("Deref " << alloc << " + " << ofs << " to give value of type " << ty); - // NOTE: No alloc can happen when dereferencing a zero-sized pointer - if( alloc.is_alloc() ) - { - LOG_DEBUG("> " << lv << " alloc=" << alloc.alloc()); - } - size_t size; - - const auto meta_ty = ty.get_meta_type(); - ::std::shared_ptr meta_val; - // If the type has metadata, store it. - if( meta_ty != RawType::Unreachable ) - { - auto meta_size = meta_ty.get_size(); - LOG_ASSERT(val.m_size == POINTER_SIZE + meta_size, "Deref of " << ty << ", but pointer isn't correct size"); - meta_val = ::std::make_shared( val.read_value(POINTER_SIZE, meta_size) ); - - // TODO: Get a more sane size from the metadata - if( alloc ) - { - LOG_DEBUG("> Meta " << *meta_val << ", size = " << alloc.get_size() << " - " << ofs); - size = alloc.get_size() - ofs; - } - else - { - size = 0; - } - } - else - { - LOG_ASSERT(val.m_size == POINTER_SIZE, "Deref of a value that isn't a pointer-sized value (size=" << val.m_size << ") - " << val << ": " << ptr_ty); - size = ty.get_size(); - if( !alloc ) { - LOG_ERROR("Deref of a value with no relocation - " << val); - } - } - - LOG_DEBUG("alloc=" << alloc << ", ofs=" << ofs << ", size=" << size); - auto rv = ValueRef(::std::move(alloc), ofs, size); - rv.m_metadata = ::std::move(meta_val); - return rv; - } break; - } - throw ""; - } - ValueRef get_value_ref(const ::MIR::LValue& lv) - { - ::HIR::TypeRef tmp; - return get_value_and_type(lv, tmp); - } - - ::HIR::TypeRef get_lvalue_ty(const ::MIR::LValue& lv) - { - ::HIR::TypeRef ty; - get_value_and_type(lv, ty); - return ty; - } - - Value read_lvalue_with_ty(const ::MIR::LValue& lv, ::HIR::TypeRef& ty) - { - auto base_value = get_value_and_type(lv, ty); - - return base_value.read_value(0, ty.get_size()); - } - Value read_lvalue(const ::MIR::LValue& lv) - { - ::HIR::TypeRef ty; - return read_lvalue_with_ty(lv, ty); - } - void write_lvalue(const ::MIR::LValue& lv, Value val) - { - //LOG_DEBUG(lv << " = " << val); - ::HIR::TypeRef ty; - auto base_value = get_value_and_type(lv, ty); - - if(base_value.m_alloc) { - base_value.m_alloc.alloc().write_value(base_value.m_offset, ::std::move(val)); - } - else { - base_value.m_value->write_value(base_value.m_offset, ::std::move(val)); - } - } - - Value const_to_value(const ::MIR::Constant& c, ::HIR::TypeRef& ty) - { - switch(c.tag()) - { - case ::MIR::Constant::TAGDEAD: throw ""; - TU_ARM(c, Int, ce) { - ty = ::HIR::TypeRef(ce.t); - Value val = Value(ty); - val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian - // TODO: If the write was clipped, sign-extend - return val; - } break; - TU_ARM(c, Uint, ce) { - ty = ::HIR::TypeRef(ce.t); - Value val = Value(ty); - val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian - return val; - } break; - TU_ARM(c, Bool, ce) { - Value val = Value(::HIR::TypeRef { RawType::Bool }); - val.write_bytes(0, &ce.v, 1); - return val; - } break; - TU_ARM(c, Float, ce) { - ty = ::HIR::TypeRef(ce.t); - Value val = Value(ty); - if( ce.t.raw_type == RawType::F64 ) { - val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian/format? - } - else if( ce.t.raw_type == RawType::F32 ) { - float v = static_cast(ce.v); - val.write_bytes(0, &v, ::std::min(ty.get_size(), sizeof(v))); // TODO: Endian/format? - } - else { - throw ::std::runtime_error("BUG: Invalid type in Constant::Float"); - } - return val; - } break; - TU_ARM(c, Const, ce) { - LOG_BUG("Constant::Const in mmir"); - } break; - TU_ARM(c, Bytes, ce) { - LOG_TODO("Constant::Bytes"); - } break; - TU_ARM(c, StaticString, ce) { - ty = ::HIR::TypeRef(RawType::Str); - ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); - Value val = Value(ty); - val.write_usize(0, 0); - val.write_usize(POINTER_SIZE, ce.size()); - val.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_string(&ce) }); - LOG_DEBUG(c << " = " << val); - //return Value::new_dataptr(ce.data()); - return val; - } break; - // --> Accessor - TU_ARM(c, ItemAddr, ce) { - // Create a value with a special backing allocation of zero size that references the specified item. - if( /*const auto* fn =*/ this->thread.m_modtree.get_function_opt(ce) ) { - ty = ::HIR::TypeRef(RawType::Function); - return Value::new_fnptr(ce); - } - if( const auto* s = this->thread.m_modtree.get_static_opt(ce) ) { - ty = s->ty; - ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); - Value val = Value(ty); - val.write_usize(0, 0); - val.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_alloc(s->val.allocation) }); - return val; - } - LOG_ERROR("Constant::ItemAddr - " << ce << " - not found"); - } break; - } - throw ""; - } - Value const_to_value(const ::MIR::Constant& c) - { - ::HIR::TypeRef ty; - return const_to_value(c, ty); - } - Value param_to_value(const ::MIR::Param& p, ::HIR::TypeRef& ty) - { - switch(p.tag()) - { - case ::MIR::Param::TAGDEAD: throw ""; - TU_ARM(p, Constant, pe) - return const_to_value(pe, ty); - TU_ARM(p, LValue, pe) - return read_lvalue_with_ty(pe, ty); - } - throw ""; - } - Value param_to_value(const ::MIR::Param& p) - { - ::HIR::TypeRef ty; - return param_to_value(p, ty); - } - - ValueRef get_value_ref_param(const ::MIR::Param& p, Value& tmp, ::HIR::TypeRef& ty) - { - switch(p.tag()) - { - case ::MIR::Param::TAGDEAD: throw ""; - TU_ARM(p, Constant, pe) - tmp = const_to_value(pe, ty); - return ValueRef(tmp, 0, ty.get_size()); - TU_ARM(p, LValue, pe) - return get_value_and_type(pe, ty); - } - throw ""; - } -}; - -// ==================================================================== -// -// ==================================================================== -InterpreterThread::~InterpreterThread() -{ - for(size_t i = 0; i < m_stack.size(); i++) - { - const auto& frame = m_stack[m_stack.size() - 1 - i]; - ::std::cout << "#" << i << ": " << frame.fcn.my_path << " BB" << frame.bb_idx << "/"; - if( frame.stmt_idx == frame.fcn.m_mir.blocks.at(frame.bb_idx).statements.size() ) - ::std::cout << "TERM"; - else - ::std::cout << frame.stmt_idx; - ::std::cout << ::std::endl; - } -} -void InterpreterThread::start(const ::HIR::Path& p, ::std::vector args) -{ - assert( this->m_stack.empty() ); - Value v; - if( this->call_path(v, p, ::std::move(args)) ) - { - LOG_TODO("Handle immediate return thread entry"); - } -} -bool InterpreterThread::step_one(Value& out_thread_result) -{ - assert( !this->m_stack.empty() ); - assert( !this->m_stack.back().cb ); - auto& cur_frame = this->m_stack.back(); - TRACE_FUNCTION_R(cur_frame.fcn.my_path, ""); - const auto& bb = cur_frame.fcn.m_mir.blocks.at( cur_frame.bb_idx ); - - MirHelpers state { *this, cur_frame }; - - if( cur_frame.stmt_idx < bb.statements.size() ) - { - const auto& stmt = bb.statements[cur_frame.stmt_idx]; - LOG_DEBUG("=== BB" << cur_frame.bb_idx << "/" << cur_frame.stmt_idx << ": " << stmt); - switch(stmt.tag()) - { - case ::MIR::Statement::TAGDEAD: throw ""; - TU_ARM(stmt, Assign, se) { - Value new_val; - switch(se.src.tag()) - { - case ::MIR::RValue::TAGDEAD: throw ""; - TU_ARM(se.src, Use, re) { - new_val = state.read_lvalue(re); - } break; - TU_ARM(se.src, Constant, re) { - new_val = state.const_to_value(re); - } break; - TU_ARM(se.src, Borrow, re) { - ::HIR::TypeRef src_ty; - ValueRef src_base_value = state.get_value_and_type(re.val, src_ty); - auto alloc = src_base_value.m_alloc; - if( !alloc && src_base_value.m_value ) - { - if( !src_base_value.m_value->allocation ) - { - src_base_value.m_value->create_allocation(); - } - alloc = RelocationPtr::new_alloc( src_base_value.m_value->allocation ); - } - if( alloc.is_alloc() ) - LOG_DEBUG("- alloc=" << alloc << " (" << alloc.alloc() << ")"); - else - LOG_DEBUG("- alloc=" << alloc); - size_t ofs = src_base_value.m_offset; - const auto meta = src_ty.get_meta_type(); - //bool is_slice_like = src_ty.has_slice_meta(); - src_ty.wrappers.insert(src_ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, static_cast(re.type) }); - - new_val = Value(src_ty); - // ^ Pointer value - new_val.write_usize(0, ofs); - if( meta != RawType::Unreachable ) - { - LOG_ASSERT(src_base_value.m_metadata, "Borrow of an unsized value, but no metadata avaliable"); - new_val.write_value(POINTER_SIZE, *src_base_value.m_metadata); - } - // - Add the relocation after writing the value (writing clears the relocations) - new_val.allocation->relocations.push_back(Relocation { 0, ::std::move(alloc) }); - } break; - TU_ARM(se.src, Cast, re) { - // Determine the type of cast, is it a reinterpret or is it a value transform? - // - Float <-> integer is a transform, anything else should be a reinterpret. - ::HIR::TypeRef src_ty; - auto src_value = state.get_value_and_type(re.val, src_ty); - - new_val = Value(re.type); - if( re.type == src_ty ) - { - // No-op cast - new_val = src_value.read_value(0, re.type.get_size()); - } - else if( !re.type.wrappers.empty() ) - { - // Destination can only be a raw pointer - if( re.type.wrappers.at(0).type != TypeWrapper::Ty::Pointer ) { - throw "ERROR"; - } - if( !src_ty.wrappers.empty() ) - { - // Source can be either - if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer - && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { - throw "ERROR"; - } - - if( src_ty.get_size() > re.type.get_size() ) { - // TODO: How to casting fat to thin? - //LOG_TODO("Handle casting fat to thin, " << src_ty << " -> " << re.type); - new_val = src_value.read_value(0, re.type.get_size()); - } - else - { - new_val = src_value.read_value(0, re.type.get_size()); - } - } - else - { - if( src_ty == RawType::Function ) - { - } - else if( src_ty == RawType::USize ) - { - } - else - { - ::std::cerr << "ERROR: Trying to pointer (" << re.type <<" ) from invalid type (" << src_ty << ")\n"; - throw "ERROR"; - } - new_val = src_value.read_value(0, re.type.get_size()); - } - } - else if( !src_ty.wrappers.empty() ) - { - // TODO: top wrapper MUST be a pointer - if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer - && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { - throw "ERROR"; - } - // TODO: MUST be a thin pointer? - - // TODO: MUST be an integer (usize only?) - if( re.type != RawType::USize && re.type != RawType::ISize ) { - LOG_ERROR("Casting from a pointer to non-usize - " << re.type << " to " << src_ty); - throw "ERROR"; - } - new_val = src_value.read_value(0, re.type.get_size()); - } - else - { - // TODO: What happens if there'a cast of something with a relocation? - switch(re.type.inner_type) - { - case RawType::Unreachable: throw "BUG"; - case RawType::Composite: - case RawType::TraitObject: - case RawType::Function: - case RawType::Str: - case RawType::Unit: - LOG_ERROR("Casting to " << re.type << " is invalid"); - throw "ERROR"; - case RawType::F32: { - float dst_val = 0.0; - // Can be an integer, or F64 (pointer is impossible atm) - switch(src_ty.inner_type) - { - case RawType::Unreachable: throw "BUG"; - case RawType::Composite: throw "ERROR"; - case RawType::TraitObject: throw "ERROR"; - case RawType::Function: throw "ERROR"; - case RawType::Char: throw "ERROR"; - case RawType::Str: throw "ERROR"; - case RawType::Unit: throw "ERROR"; - case RawType::Bool: throw "ERROR"; - case RawType::F32: throw "BUG"; - case RawType::F64: dst_val = static_cast( src_value.read_f64(0) ); break; - case RawType::USize: throw "TODO";// /*dst_val = src_value.read_usize();*/ break; - case RawType::ISize: throw "TODO";// /*dst_val = src_value.read_isize();*/ break; - case RawType::U8: dst_val = static_cast( src_value.read_u8 (0) ); break; - case RawType::I8: dst_val = static_cast( src_value.read_i8 (0) ); break; - case RawType::U16: dst_val = static_cast( src_value.read_u16(0) ); break; - case RawType::I16: dst_val = static_cast( src_value.read_i16(0) ); break; - case RawType::U32: dst_val = static_cast( src_value.read_u32(0) ); break; - case RawType::I32: dst_val = static_cast( src_value.read_i32(0) ); break; - case RawType::U64: dst_val = static_cast( src_value.read_u64(0) ); break; - case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); break; - case RawType::U128: throw "TODO";// /*dst_val = src_value.read_u128();*/ break; - case RawType::I128: throw "TODO";// /*dst_val = src_value.read_i128();*/ break; - } - new_val.write_f32(0, dst_val); - } break; - case RawType::F64: { - double dst_val = 0.0; - // Can be an integer, or F32 (pointer is impossible atm) - switch(src_ty.inner_type) - { - case RawType::Unreachable: throw "BUG"; - case RawType::Composite: throw "ERROR"; - case RawType::TraitObject: throw "ERROR"; - case RawType::Function: throw "ERROR"; - case RawType::Char: throw "ERROR"; - case RawType::Str: throw "ERROR"; - case RawType::Unit: throw "ERROR"; - case RawType::Bool: throw "ERROR"; - case RawType::F64: throw "BUG"; - case RawType::F32: dst_val = static_cast( src_value.read_f32(0) ); break; - case RawType::USize: dst_val = static_cast( src_value.read_usize(0) ); break; - case RawType::ISize: dst_val = static_cast( src_value.read_isize(0) ); break; - case RawType::U8: dst_val = static_cast( src_value.read_u8 (0) ); break; - case RawType::I8: dst_val = static_cast( src_value.read_i8 (0) ); break; - case RawType::U16: dst_val = static_cast( src_value.read_u16(0) ); break; - case RawType::I16: dst_val = static_cast( src_value.read_i16(0) ); break; - case RawType::U32: dst_val = static_cast( src_value.read_u32(0) ); break; - case RawType::I32: dst_val = static_cast( src_value.read_i32(0) ); break; - case RawType::U64: dst_val = static_cast( src_value.read_u64(0) ); break; - case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); break; - case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break; - case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break; - } - new_val.write_f64(0, dst_val); - } break; - case RawType::Bool: - LOG_TODO("Cast to " << re.type); - case RawType::Char: - LOG_TODO("Cast to " << re.type); - case RawType::USize: - case RawType::U8: - case RawType::U16: - case RawType::U32: - case RawType::U64: - case RawType::ISize: - case RawType::I8: - case RawType::I16: - case RawType::I32: - case RawType::I64: - { - uint64_t dst_val = 0; - // Can be an integer, or F32 (pointer is impossible atm) - switch(src_ty.inner_type) - { - case RawType::Unreachable: - LOG_BUG("Casting unreachable"); - case RawType::TraitObject: - case RawType::Str: - LOG_FATAL("Cast of unsized type - " << src_ty); - case RawType::Function: - LOG_ASSERT(re.type.inner_type == RawType::USize, "Function pointers can only be casted to usize, instead " << re.type); - new_val = src_value.read_value(0, re.type.get_size()); - break; - case RawType::Char: - LOG_ASSERT(re.type.inner_type == RawType::U32, "Char can only be casted to u32, instead " << re.type); - new_val = src_value.read_value(0, 4); - break; - case RawType::Unit: - LOG_FATAL("Cast of unit"); - case RawType::Composite: { - const auto& dt = *src_ty.composite_type; - if( dt.variants.size() == 0 ) { - LOG_FATAL("Cast of composite - " << src_ty); - } - // TODO: Check that all variants have the same tag offset - LOG_ASSERT(dt.fields.size() == 1, ""); - LOG_ASSERT(dt.fields[0].first == 0, ""); - for(size_t i = 0; i < dt.variants.size(); i ++ ) { - LOG_ASSERT(dt.variants[i].base_field == 0, ""); - LOG_ASSERT(dt.variants[i].field_path.empty(), ""); - } - ::HIR::TypeRef tag_ty = dt.fields[0].second; - LOG_ASSERT(tag_ty.wrappers.empty(), ""); - switch(tag_ty.inner_type) - { - case RawType::USize: - dst_val = static_cast( src_value.read_usize(0) ); - if(0) - case RawType::ISize: - dst_val = static_cast( src_value.read_isize(0) ); - if(0) - case RawType::U8: - dst_val = static_cast( src_value.read_u8 (0) ); - if(0) - case RawType::I8: - dst_val = static_cast( src_value.read_i8 (0) ); - if(0) - case RawType::U16: - dst_val = static_cast( src_value.read_u16(0) ); - if(0) - case RawType::I16: - dst_val = static_cast( src_value.read_i16(0) ); - if(0) - case RawType::U32: - dst_val = static_cast( src_value.read_u32(0) ); - if(0) - case RawType::I32: - dst_val = static_cast( src_value.read_i32(0) ); - if(0) - case RawType::U64: - dst_val = static_cast( src_value.read_u64(0) ); - if(0) - case RawType::I64: - dst_val = static_cast( src_value.read_i64(0) ); - break; - default: - LOG_FATAL("Bad tag type in cast - " << tag_ty); - } - } if(0) - case RawType::Bool: - dst_val = static_cast( src_value.read_u8 (0) ); - if(0) - case RawType::F64: - dst_val = static_cast( src_value.read_f64(0) ); - if(0) - case RawType::F32: - dst_val = static_cast( src_value.read_f32(0) ); - if(0) - case RawType::USize: - dst_val = static_cast( src_value.read_usize(0) ); - if(0) - case RawType::ISize: - dst_val = static_cast( src_value.read_isize(0) ); - if(0) - case RawType::U8: - dst_val = static_cast( src_value.read_u8 (0) ); - if(0) - case RawType::I8: - dst_val = static_cast( src_value.read_i8 (0) ); - if(0) - case RawType::U16: - dst_val = static_cast( src_value.read_u16(0) ); - if(0) - case RawType::I16: - dst_val = static_cast( src_value.read_i16(0) ); - if(0) - case RawType::U32: - dst_val = static_cast( src_value.read_u32(0) ); - if(0) - case RawType::I32: - dst_val = static_cast( src_value.read_i32(0) ); - if(0) - case RawType::U64: - dst_val = static_cast( src_value.read_u64(0) ); - if(0) - case RawType::I64: - dst_val = static_cast( src_value.read_i64(0) ); - - switch(re.type.inner_type) - { - case RawType::USize: - new_val.write_usize(0, dst_val); - break; - case RawType::U8: - new_val.write_u8(0, static_cast(dst_val)); - break; - case RawType::U16: - new_val.write_u16(0, static_cast(dst_val)); - break; - case RawType::U32: - new_val.write_u32(0, static_cast(dst_val)); - break; - case RawType::U64: - new_val.write_u64(0, dst_val); - break; - case RawType::ISize: - new_val.write_usize(0, static_cast(dst_val)); - break; - case RawType::I8: - new_val.write_i8(0, static_cast(dst_val)); - break; - case RawType::I16: - new_val.write_i16(0, static_cast(dst_val)); - break; - case RawType::I32: - new_val.write_i32(0, static_cast(dst_val)); - break; - case RawType::I64: - new_val.write_i64(0, static_cast(dst_val)); - break; - default: - throw ""; - } - break; - case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break; - case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break; - } - } break; - case RawType::U128: - case RawType::I128: - LOG_TODO("Cast to " << re.type); - } - } - } break; - TU_ARM(se.src, BinOp, re) { - ::HIR::TypeRef ty_l, ty_r; - Value tmp_l, tmp_r; - auto v_l = state.get_value_ref_param(re.val_l, tmp_l, ty_l); - auto v_r = state.get_value_ref_param(re.val_r, tmp_r, ty_r); - LOG_DEBUG(v_l << " (" << ty_l <<") ? " << v_r << " (" << ty_r <<")"); - - switch(re.op) - { - case ::MIR::eBinOp::EQ: - case ::MIR::eBinOp::NE: - case ::MIR::eBinOp::GT: - case ::MIR::eBinOp::GE: - case ::MIR::eBinOp::LT: - case ::MIR::eBinOp::LE: { - LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); - int res = 0; - // TODO: Handle comparison of the relocations too - - const auto& alloc_l = v_l.m_value ? v_l.m_value->allocation : v_l.m_alloc; - const auto& alloc_r = v_r.m_value ? v_r.m_value->allocation : v_r.m_alloc; - auto reloc_l = alloc_l ? v_l.get_relocation(v_l.m_offset) : RelocationPtr(); - auto reloc_r = alloc_r ? v_r.get_relocation(v_r.m_offset) : RelocationPtr(); - - if( reloc_l != reloc_r ) - { - res = (reloc_l < reloc_r ? -1 : 1); - } - LOG_DEBUG("res=" << res << ", " << reloc_l << " ? " << reloc_r); - - if( ty_l.wrappers.empty() ) - { - switch(ty_l.inner_type) - { - case RawType::U64: res = res != 0 ? res : Ops::do_compare(v_l.read_u64(0), v_r.read_u64(0)); break; - case RawType::U32: res = res != 0 ? res : Ops::do_compare(v_l.read_u32(0), v_r.read_u32(0)); break; - case RawType::U16: res = res != 0 ? res : Ops::do_compare(v_l.read_u16(0), v_r.read_u16(0)); break; - case RawType::U8 : res = res != 0 ? res : Ops::do_compare(v_l.read_u8 (0), v_r.read_u8 (0)); break; - case RawType::I64: res = res != 0 ? res : Ops::do_compare(v_l.read_i64(0), v_r.read_i64(0)); break; - case RawType::I32: res = res != 0 ? res : Ops::do_compare(v_l.read_i32(0), v_r.read_i32(0)); break; - case RawType::I16: res = res != 0 ? res : Ops::do_compare(v_l.read_i16(0), v_r.read_i16(0)); break; - case RawType::I8 : res = res != 0 ? res : Ops::do_compare(v_l.read_i8 (0), v_r.read_i8 (0)); break; - case RawType::USize: res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); break; - case RawType::ISize: res = res != 0 ? res : Ops::do_compare(v_l.read_isize(0), v_r.read_isize(0)); break; - default: - LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); - } - } - else if( ty_l.wrappers.front().type == TypeWrapper::Ty::Pointer ) - { - // TODO: Technically only EQ/NE are valid. - - res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); - - // Compare fat metadata. - if( res == 0 && v_l.m_size > POINTER_SIZE ) - { - reloc_l = v_l.get_relocation(POINTER_SIZE); - reloc_r = v_r.get_relocation(POINTER_SIZE); - - if( res == 0 && reloc_l != reloc_r ) - { - res = (reloc_l < reloc_r ? -1 : 1); - } - res = res != 0 ? res : Ops::do_compare(v_l.read_usize(POINTER_SIZE), v_r.read_usize(POINTER_SIZE)); - } - } - else - { - LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); - } - bool res_bool; - switch(re.op) - { - case ::MIR::eBinOp::EQ: res_bool = (res == 0); break; - case ::MIR::eBinOp::NE: res_bool = (res != 0); break; - case ::MIR::eBinOp::GT: res_bool = (res == 1); break; - case ::MIR::eBinOp::GE: res_bool = (res == 1 || res == 0); break; - case ::MIR::eBinOp::LT: res_bool = (res == -1); break; - case ::MIR::eBinOp::LE: res_bool = (res == -1 || res == 0); break; - break; - default: - LOG_BUG("Unknown comparison"); - } - new_val = Value(::HIR::TypeRef(RawType::Bool)); - new_val.write_u8(0, res_bool ? 1 : 0); - } break; - case ::MIR::eBinOp::BIT_SHL: - case ::MIR::eBinOp::BIT_SHR: { - LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); - LOG_ASSERT(ty_r.wrappers.empty(), "Bitwise operator with non-primitive - " << ty_r); - size_t max_bits = ty_r.get_size() * 8; - uint8_t shift; - auto check_cast = [&](auto v){ LOG_ASSERT(0 <= v && v <= max_bits, "Shift out of range - " << v); return static_cast(v); }; - switch(ty_r.inner_type) - { - case RawType::U64: shift = check_cast(v_r.read_u64(0)); break; - case RawType::U32: shift = check_cast(v_r.read_u32(0)); break; - case RawType::U16: shift = check_cast(v_r.read_u16(0)); break; - case RawType::U8 : shift = check_cast(v_r.read_u8 (0)); break; - case RawType::I64: shift = check_cast(v_r.read_i64(0)); break; - case RawType::I32: shift = check_cast(v_r.read_i32(0)); break; - case RawType::I16: shift = check_cast(v_r.read_i16(0)); break; - case RawType::I8 : shift = check_cast(v_r.read_i8 (0)); break; - case RawType::USize: shift = check_cast(v_r.read_usize(0)); break; - case RawType::ISize: shift = check_cast(v_r.read_isize(0)); break; - default: - LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); - } - new_val = Value(ty_l); - switch(ty_l.inner_type) - { - // TODO: U128 - case RawType::U64: new_val.write_u64(0, Ops::do_bitwise(v_l.read_u64(0), static_cast(shift), re.op)); break; - case RawType::U32: new_val.write_u32(0, Ops::do_bitwise(v_l.read_u32(0), static_cast(shift), re.op)); break; - case RawType::U16: new_val.write_u16(0, Ops::do_bitwise(v_l.read_u16(0), static_cast(shift), re.op)); break; - case RawType::U8 : new_val.write_u8 (0, Ops::do_bitwise(v_l.read_u8 (0), static_cast(shift), re.op)); break; - case RawType::USize: new_val.write_usize(0, Ops::do_bitwise(v_l.read_usize(0), static_cast(shift), re.op)); break; - // TODO: Is signed allowed? - default: - LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); - } - } break; - case ::MIR::eBinOp::BIT_AND: - case ::MIR::eBinOp::BIT_OR: - case ::MIR::eBinOp::BIT_XOR: - LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); - LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); - new_val = Value(ty_l); - switch(ty_l.inner_type) - { - // TODO: U128/I128 - case RawType::U64: - case RawType::I64: - new_val.write_u64( 0, Ops::do_bitwise(v_l.read_u64(0), v_r.read_u64(0), re.op) ); - break; - case RawType::U32: - case RawType::I32: - new_val.write_u32( 0, static_cast(Ops::do_bitwise(v_l.read_u32(0), v_r.read_u32(0), re.op)) ); - break; - case RawType::U16: - case RawType::I16: - new_val.write_u16( 0, static_cast(Ops::do_bitwise(v_l.read_u16(0), v_r.read_u16(0), re.op)) ); - break; - case RawType::U8: - case RawType::I8: - new_val.write_u8 ( 0, static_cast(Ops::do_bitwise(v_l.read_u8 (0), v_r.read_u8 (0), re.op)) ); - break; - case RawType::USize: - case RawType::ISize: - new_val.write_usize( 0, Ops::do_bitwise(v_l.read_usize(0), v_r.read_usize(0), re.op) ); - break; - default: - LOG_TODO("BinOp bitwise - " << se.src << " w/ " << ty_l); - } - - break; - default: - LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); - auto val_l = PrimitiveValueVirt::from_value(ty_l, v_l); - auto val_r = PrimitiveValueVirt::from_value(ty_r, v_r); - switch(re.op) - { - case ::MIR::eBinOp::ADD: val_l.get().add( val_r.get() ); break; - case ::MIR::eBinOp::SUB: val_l.get().subtract( val_r.get() ); break; - case ::MIR::eBinOp::MUL: val_l.get().multiply( val_r.get() ); break; - case ::MIR::eBinOp::DIV: val_l.get().divide( val_r.get() ); break; - case ::MIR::eBinOp::MOD: val_l.get().modulo( val_r.get() ); break; - - default: - LOG_TODO("Unsupported binary operator?"); - } - new_val = Value(ty_l); - val_l.get().write_to_value(new_val, 0); - break; - } - } break; - TU_ARM(se.src, UniOp, re) { - ::HIR::TypeRef ty; - auto v = state.get_value_and_type(re.val, ty); - LOG_ASSERT(ty.wrappers.empty(), "UniOp on wrapped type - " << ty); - new_val = Value(ty); - switch(re.op) - { - case ::MIR::eUniOp::INV: - switch(ty.inner_type) - { - case RawType::U128: - case RawType::I128: - LOG_TODO("UniOp::INV U128"); - case RawType::U64: - case RawType::I64: - new_val.write_u64( 0, ~v.read_u64(0) ); - break; - case RawType::U32: - case RawType::I32: - new_val.write_u32( 0, ~v.read_u32(0) ); - break; - case RawType::U16: - case RawType::I16: - new_val.write_u16( 0, ~v.read_u16(0) ); - break; - case RawType::U8: - case RawType::I8: - new_val.write_u8 ( 0, ~v.read_u8 (0) ); - break; - case RawType::USize: - case RawType::ISize: - new_val.write_usize( 0, ~v.read_usize(0) ); - break; - case RawType::Bool: - new_val.write_u8 ( 0, v.read_u8 (0) == 0 ); - break; - default: - LOG_TODO("UniOp::INV - w/ type " << ty); - } - break; - case ::MIR::eUniOp::NEG: - switch(ty.inner_type) - { - case RawType::I128: - LOG_TODO("UniOp::NEG I128"); - case RawType::I64: - new_val.write_i64( 0, -v.read_i64(0) ); - break; - case RawType::I32: - new_val.write_i32( 0, -v.read_i32(0) ); - break; - case RawType::I16: - new_val.write_i16( 0, -v.read_i16(0) ); - break; - case RawType::I8: - new_val.write_i8 ( 0, -v.read_i8 (0) ); - break; - case RawType::ISize: - new_val.write_isize( 0, -v.read_isize(0) ); - break; - default: - LOG_ERROR("UniOp::INV not valid on type " << ty); - } - break; - } - } break; - TU_ARM(se.src, DstMeta, re) { - auto ptr = state.get_value_ref(re.val); - - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = ptr.read_value(POINTER_SIZE, dst_ty.get_size()); - } break; - TU_ARM(se.src, DstPtr, re) { - auto ptr = state.get_value_ref(re.val); - - new_val = ptr.read_value(0, POINTER_SIZE); - } break; - TU_ARM(se.src, MakeDst, re) { - // - Get target type, just for some assertions - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - - auto ptr = state.param_to_value(re.ptr_val ); - auto meta = state.param_to_value(re.meta_val); - LOG_DEBUG("ty=" << dst_ty << ", ptr=" << ptr << ", meta=" << meta); - - new_val.write_value(0, ::std::move(ptr)); - new_val.write_value(POINTER_SIZE, ::std::move(meta)); - } break; - TU_ARM(se.src, Tuple, re) { - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - - for(size_t i = 0; i < re.vals.size(); i++) - { - auto fld_ofs = dst_ty.composite_type->fields.at(i).first; - new_val.write_value(fld_ofs, state.param_to_value(re.vals[i])); - } - } break; - TU_ARM(se.src, Array, re) { - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - // TODO: Assert that type is an array - auto inner_ty = dst_ty.get_inner(); - size_t stride = inner_ty.get_size(); - - size_t ofs = 0; - for(const auto& v : re.vals) - { - new_val.write_value(ofs, state.param_to_value(v)); - ofs += stride; - } - } break; - TU_ARM(se.src, SizedArray, re) { - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - // TODO: Assert that type is an array - auto inner_ty = dst_ty.get_inner(); - size_t stride = inner_ty.get_size(); - - size_t ofs = 0; - for(size_t i = 0; i < re.count; i++) - { - new_val.write_value(ofs, state.param_to_value(re.val)); - ofs += stride; - } - } break; - TU_ARM(se.src, Variant, re) { - // 1. Get the composite by path. - const auto& data_ty = this->m_modtree.get_composite(re.path); - auto dst_ty = ::HIR::TypeRef(&data_ty); - new_val = Value(dst_ty); - LOG_DEBUG("Variant " << new_val); - // Three cases: - // - Unions (no tag) - // - Data enums (tag and data) - // - Value enums (no data) - const auto& var = data_ty.variants.at(re.index); - if( var.data_field != SIZE_MAX ) - { - const auto& fld = data_ty.fields.at(re.index); - - new_val.write_value(fld.first, state.param_to_value(re.val)); - } - LOG_DEBUG("Variant " << new_val); - if( var.base_field != SIZE_MAX ) - { - ::HIR::TypeRef tag_ty; - size_t tag_ofs = dst_ty.get_field_ofs(var.base_field, var.field_path, tag_ty); - LOG_ASSERT(tag_ty.get_size() == var.tag_data.size(), ""); - new_val.write_bytes(tag_ofs, var.tag_data.data(), var.tag_data.size()); - } - else - { - // Union, no tag - } - LOG_DEBUG("Variant " << new_val); - } break; - TU_ARM(se.src, Struct, re) { - const auto& data_ty = m_modtree.get_composite(re.path); - - ::HIR::TypeRef dst_ty; - state.get_value_and_type(se.dst, dst_ty); - new_val = Value(dst_ty); - LOG_ASSERT(dst_ty.composite_type == &data_ty, "Destination type of RValue::Struct isn't the same as the input"); - - for(size_t i = 0; i < re.vals.size(); i++) - { - auto fld_ofs = data_ty.fields.at(i).first; - new_val.write_value(fld_ofs, state.param_to_value(re.vals[i])); - } - } break; - } - LOG_DEBUG("- " << new_val); - state.write_lvalue(se.dst, ::std::move(new_val)); - } break; - case ::MIR::Statement::TAG_Asm: - LOG_TODO(stmt); - break; - TU_ARM(stmt, Drop, se) { - if( se.flag_idx == ~0u || cur_frame.drop_flags.at(se.flag_idx) ) - { - ::HIR::TypeRef ty; - auto v = state.get_value_and_type(se.slot, ty); - - // - Take a pointer to the inner - auto alloc = v.m_alloc; - if( !alloc ) - { - if( !v.m_value->allocation ) - { - v.m_value->create_allocation(); - } - alloc = RelocationPtr::new_alloc( v.m_value->allocation ); - } - size_t ofs = v.m_offset; - assert(ty.get_meta_type() == RawType::Unreachable); - - auto ptr_ty = ty.wrap(TypeWrapper::Ty::Borrow, 2); - - auto ptr_val = Value(ptr_ty); - ptr_val.write_usize(0, ofs); - ptr_val.allocation->relocations.push_back(Relocation { 0, ::std::move(alloc) }); - - if( !drop_value(ptr_val, ty, /*shallow=*/se.kind == ::MIR::eDropKind::SHALLOW) ) - { - return false; - } - } - } break; - TU_ARM(stmt, SetDropFlag, se) { - bool val = (se.other == ~0u ? false : cur_frame.drop_flags.at(se.other)) != se.new_val; - LOG_DEBUG("- " << val); - cur_frame.drop_flags.at(se.idx) = val; - } break; - case ::MIR::Statement::TAG_ScopeEnd: - LOG_TODO(stmt); - break; - } - - cur_frame.stmt_idx += 1; - } - else - { - LOG_DEBUG("=== BB" << cur_frame.bb_idx << "/TERM: " << bb.terminator); - switch(bb.terminator.tag()) - { - case ::MIR::Terminator::TAGDEAD: throw ""; - TU_ARM(bb.terminator, Incomplete, _te) - LOG_TODO("Terminator::Incomplete hit"); - TU_ARM(bb.terminator, Diverge, _te) - LOG_TODO("Terminator::Diverge hit"); - TU_ARM(bb.terminator, Panic, _te) - LOG_TODO("Terminator::Panic"); - TU_ARM(bb.terminator, Goto, te) - cur_frame.bb_idx = te; - break; - TU_ARM(bb.terminator, Return, _te) - LOG_DEBUG("RETURN " << cur_frame.ret); - return this->pop_stack(out_thread_result); - TU_ARM(bb.terminator, If, te) { - uint8_t v = state.get_value_ref(te.cond).read_u8(0); - LOG_ASSERT(v == 0 || v == 1, ""); - cur_frame.bb_idx = v ? te.bb0 : te.bb1; - } break; - TU_ARM(bb.terminator, Switch, te) { - ::HIR::TypeRef ty; - auto v = state.get_value_and_type(te.val, ty); - LOG_ASSERT(ty.wrappers.size() == 0, "" << ty); - LOG_ASSERT(ty.inner_type == RawType::Composite, "" << ty); - - // TODO: Convert the variant list into something that makes it easier to switch on. - size_t found_target = SIZE_MAX; - size_t default_target = SIZE_MAX; - for(size_t i = 0; i < ty.composite_type->variants.size(); i ++) - { - const auto& var = ty.composite_type->variants[i]; - if( var.tag_data.size() == 0 ) - { - // Save as the default, error for multiple defaults - if( default_target != SIZE_MAX ) - { - LOG_FATAL("Two variants with no tag in Switch - " << ty); - } - default_target = i; - } - else - { - // Get offset, read the value. - ::HIR::TypeRef tag_ty; - size_t tag_ofs = ty.get_field_ofs(var.base_field, var.field_path, tag_ty); - // Read the value bytes - ::std::vector tmp( var.tag_data.size() ); - v.read_bytes(tag_ofs, const_cast(tmp.data()), tmp.size()); - if( v.get_relocation(tag_ofs) ) - continue ; - if( ::std::memcmp(tmp.data(), var.tag_data.data(), tmp.size()) == 0 ) - { - found_target = i; - break ; - } - } - } - - if( found_target == SIZE_MAX ) - { - found_target = default_target; - } - if( found_target == SIZE_MAX ) - { - LOG_FATAL("Terminator::Switch on " << ty << " didn't find a variant"); - } - cur_frame.bb_idx = te.targets.at(found_target); - } break; - TU_ARM(bb.terminator, SwitchValue, _te) - LOG_TODO("Terminator::SwitchValue"); - TU_ARM(bb.terminator, Call, te) { - ::std::vector sub_args; sub_args.reserve(te.args.size()); - for(const auto& a : te.args) - { - sub_args.push_back( state.param_to_value(a) ); - LOG_DEBUG("#" << (sub_args.size() - 1) << " " << sub_args.back()); - } - Value rv; - if( te.fcn.is_Intrinsic() ) - { - const auto& fe = te.fcn.as_Intrinsic(); - if( !this->call_intrinsic(rv, fe.name, fe.params, ::std::move(sub_args)) ) - { - // Early return, don't want to update stmt_idx yet - return false; - } - } - else - { - RelocationPtr fcn_alloc_ptr; - const ::HIR::Path* fcn_p; - if( te.fcn.is_Path() ) { - fcn_p = &te.fcn.as_Path(); - } - else { - ::HIR::TypeRef ty; - auto v = state.get_value_and_type(te.fcn.as_Value(), ty); - LOG_DEBUG("> Indirect call " << v); - // TODO: Assert type - // TODO: Assert offset/content. - assert(v.read_usize(0) == 0); - fcn_alloc_ptr = v.get_relocation(v.m_offset); - if( !fcn_alloc_ptr ) - LOG_FATAL("Calling value with no relocation - " << v); - LOG_ASSERT(fcn_alloc_ptr.get_ty() == RelocationPtr::Ty::Function, "Calling value that isn't a function pointer"); - fcn_p = &fcn_alloc_ptr.fcn(); - } - - LOG_DEBUG("Call " << *fcn_p); - if( !this->call_path(rv, *fcn_p, ::std::move(sub_args)) ) - { - // Early return, don't want to update stmt_idx yet - return false; - } - } - LOG_DEBUG(te.ret_val << " = " << rv << " (resume " << cur_frame.fcn.my_path << ")"); - state.write_lvalue(te.ret_val, rv); - cur_frame.bb_idx = te.ret_block; - } break; - } - cur_frame.stmt_idx = 0; - } - - return false; -} -bool InterpreterThread::pop_stack(Value& out_thread_result) -{ - assert( !this->m_stack.empty() ); - - auto res_v = ::std::move(this->m_stack.back().ret); - this->m_stack.pop_back(); - - if( this->m_stack.empty() ) - { - LOG_DEBUG("Thread complete, result " << res_v); - out_thread_result = ::std::move(res_v); - return true; - } - else - { - // Handle callback wrappers (e.g. for __rust_maybe_catch_panic) - if( this->m_stack.back().cb ) - { - if( !this->m_stack.back().cb(res_v, ::std::move(res_v)) ) - { - return false; - } - this->m_stack.pop_back(); - assert( !this->m_stack.empty() ); - assert( !this->m_stack.back().cb ); - } - - auto& cur_frame = this->m_stack.back(); - MirHelpers state { *this, cur_frame }; - - const auto& blk = cur_frame.fcn.m_mir.blocks.at( cur_frame.bb_idx ); - if( cur_frame.stmt_idx < blk.statements.size() ) - { - assert( blk.statements[cur_frame.stmt_idx].is_Drop() ); - cur_frame.stmt_idx ++; - LOG_DEBUG("DROP complete (resume " << cur_frame.fcn.my_path << ")"); - } - else - { - assert( blk.terminator.is_Call() ); - const auto& te = blk.terminator.as_Call(); - - LOG_DEBUG(te.ret_val << " = " << res_v << " (resume " << cur_frame.fcn.my_path << ")"); - - state.write_lvalue(te.ret_val, res_v); - cur_frame.stmt_idx = 0; - cur_frame.bb_idx = te.ret_block; - } - - return false; - } -} - -InterpreterThread::StackFrame::StackFrame(const Function& fcn, ::std::vector args): - fcn(fcn), - ret( fcn.ret_ty ), - args( ::std::move(args) ), - locals( ), - drop_flags( fcn.m_mir.drop_flags ), - bb_idx(0), - stmt_idx(0) -{ - this->locals.reserve( fcn.m_mir.locals.size() ); - for(const auto& ty : fcn.m_mir.locals) - { - if( ty == RawType::Unreachable ) { - // HACK: Locals can be !, but they can NEVER be accessed - this->locals.push_back( Value() ); - } - else { - this->locals.push_back( Value(ty) ); - } - } -} -bool InterpreterThread::call_path(Value& ret, const ::HIR::Path& path, ::std::vector args) -{ - // TODO: Support overriding certain functions - { - if( path == ::HIR::SimplePath { "std", { "sys", "imp", "c", "SetThreadStackGuarantee" } } ) - { - ret = Value(::HIR::TypeRef{RawType::I32}); - ret.write_i32(0, 120); // ERROR_CALL_NOT_IMPLEMENTED - return true; - } - - // - No guard page needed - if( path == ::HIR::SimplePath { "std", {"sys", "imp", "thread", "guard", "init" } } ) - { - ret = Value::with_size(16, false); - ret.write_u64(0, 0); - ret.write_u64(8, 0); - return true; - } - - // - No stack overflow handling needed - if( path == ::HIR::SimplePath { "std", { "sys", "imp", "stack_overflow", "imp", "init" } } ) - { - return true; - } - } - - const auto& fcn = m_modtree.get_function(path); - - if( fcn.external.link_name != "" ) - { - // External function! - return this->call_extern(ret, fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); - } - - this->m_stack.push_back(StackFrame(fcn, ::std::move(args))); - return false; -} - -extern "C" { - long sysconf(int); - ssize_t write(int, const void*, size_t); -} -bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, const ::std::string& abi, ::std::vector args) -{ - if( link_name == "__rust_allocate" ) - { - auto size = args.at(0).read_usize(0); - auto align = args.at(1).read_usize(0); - LOG_DEBUG("__rust_allocate(size=" << size << ", align=" << align << ")"); - ::HIR::TypeRef rty { RawType::Unit }; - rty.wrappers.push_back({ TypeWrapper::Ty::Pointer, 0 }); - - rv = Value(rty); - rv.write_usize(0, 0); - // TODO: Use the alignment when making an allocation? - rv.allocation->relocations.push_back({ 0, RelocationPtr::new_alloc(Allocation::new_alloc(size)) }); - } - else if( link_name == "__rust_reallocate" ) - { - LOG_ASSERT(args.at(0).allocation, "__rust_reallocate first argument doesn't have an allocation"); - auto alloc_ptr = args.at(0).get_relocation(0); - auto ptr_ofs = args.at(0).read_usize(0); - LOG_ASSERT(ptr_ofs == 0, "__rust_reallocate with offset pointer"); - auto oldsize = args.at(1).read_usize(0); - auto newsize = args.at(2).read_usize(0); - auto align = args.at(3).read_usize(0); - LOG_DEBUG("__rust_reallocate(ptr=" << alloc_ptr << ", oldsize=" << oldsize << ", newsize=" << newsize << ", align=" << align << ")"); - - LOG_ASSERT(alloc_ptr, "__rust_reallocate with no backing allocation attached to pointer"); - LOG_ASSERT(alloc_ptr.is_alloc(), "__rust_reallocate with no backing allocation attached to pointer"); - auto& alloc = alloc_ptr.alloc(); - // TODO: Check old size and alignment against allocation. - alloc.data.resize( (newsize + 8-1) / 8 ); - alloc.mask.resize( (newsize + 8-1) / 8 ); - // TODO: Should this instead make a new allocation to catch use-after-free? - rv = ::std::move(args.at(0)); - } - else if( link_name == "__rust_deallocate" ) - { - LOG_ASSERT(args.at(0).allocation, "__rust_deallocate first argument doesn't have an allocation"); - auto alloc_ptr = args.at(0).get_relocation(0); - auto ptr_ofs = args.at(0).read_usize(0); - LOG_ASSERT(ptr_ofs == 0, "__rust_deallocate with offset pointer"); - LOG_DEBUG("__rust_deallocate(ptr=" << alloc_ptr << ")"); - - LOG_ASSERT(alloc_ptr, "__rust_deallocate with no backing allocation attached to pointer"); - LOG_ASSERT(alloc_ptr.is_alloc(), "__rust_deallocate with no backing allocation attached to pointer"); - auto& alloc = alloc_ptr.alloc(); - alloc.mark_as_freed(); - // Just let it drop. - rv = Value(); - } - else if( link_name == "__rust_maybe_catch_panic" ) - { - auto fcn_path = args.at(0).get_relocation(0).fcn(); - auto arg = args.at(1); - auto data_ptr = args.at(2).read_pointer_valref_mut(0, POINTER_SIZE); - auto vtable_ptr = args.at(3).read_pointer_valref_mut(0, POINTER_SIZE); - - ::std::vector sub_args; - sub_args.push_back( ::std::move(arg) ); - - this->m_stack.push_back(StackFrame::make_wrapper([=](Value& out_rv, Value /*rv*/)->bool{ - out_rv = Value(::HIR::TypeRef(RawType::U32)); - out_rv.write_u32(0, 0); - return true; - })); - - // TODO: Catch the panic out of this. - if( this->call_path(rv, fcn_path, ::std::move(sub_args)) ) - { - bool v = this->pop_stack(rv); - assert( v == false ); - return true; - } - else - { - return false; - } - } - else if( link_name == "__rust_start_panic" ) - { - LOG_TODO("__rust_start_panic"); - } - else if( link_name == "rust_begin_unwind" ) - { - LOG_TODO("rust_begin_unwind"); - } -#ifdef _WIN32 - // WinAPI functions used by libstd - else if( link_name == "AddVectoredExceptionHandler" ) - { - LOG_DEBUG("Call `AddVectoredExceptionHandler` - Ignoring and returning non-null"); - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.write_usize(0, 1); - } - else if( link_name == "GetModuleHandleW" ) - { - LOG_ASSERT(args.at(0).allocation.is_alloc(), ""); - const auto& tgt_alloc = args.at(0).allocation.alloc().get_relocation(0); - const void* arg0 = (tgt_alloc ? tgt_alloc.alloc().data_ptr() : nullptr); - //extern void* GetModuleHandleW(const void* s); - if(arg0) { - LOG_DEBUG("GetModuleHandleW(" << tgt_alloc.alloc() << ")"); - } - else { - LOG_DEBUG("GetModuleHandleW(NULL)"); - } - - auto ret = GetModuleHandleW(static_cast(arg0)); - if(ret) - { - rv = Value::new_ffiptr(FFIPointer { "GetModuleHandleW", ret }); - } - else - { - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.create_allocation(); - rv.write_usize(0,0); - } - } - else if( link_name == "GetProcAddress" ) - { - LOG_ASSERT(args.at(0).allocation.is_alloc(), ""); - const auto& handle_alloc = args.at(0).allocation.alloc().get_relocation(0); - LOG_ASSERT(args.at(1).allocation.is_alloc(), ""); - const auto& sym_alloc = args.at(1).allocation.alloc().get_relocation(0); - - // TODO: Ensure that first arg is a FFI pointer with offset+size of zero - void* handle = handle_alloc.ffi().ptr_value; - // TODO: Get either a FFI data pointer, or a inner data pointer - const void* symname = sym_alloc.alloc().data_ptr(); - // TODO: Sanity check that it's a valid c string within its allocation - LOG_DEBUG("FFI GetProcAddress(" << handle << ", \"" << static_cast(symname) << "\")"); - - auto ret = GetProcAddress(static_cast(handle), static_cast(symname)); - - if( ret ) - { - rv = Value::new_ffiptr(FFIPointer { "GetProcAddress", ret }); - } - else - { - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.create_allocation(); - rv.write_usize(0,0); - } - } -#else - // POSIX - else if( link_name == "write" ) - { - auto fd = args.at(0).read_i32(0); - auto count = args.at(2).read_isize(0); - const auto* buf = args.at(1).read_pointer_const(0, count); - - ssize_t val = write(fd, buf, count); - - rv = Value(::HIR::TypeRef(RawType::ISize)); - rv.write_isize(0, val); - } - else if( link_name == "sysconf" ) - { - auto name = args.at(0).read_i32(0); - LOG_DEBUG("FFI sysconf(" << name << ")"); - - long val = sysconf(name); - - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.write_usize(0, val); - } - else if( link_name == "pthread_mutex_init" || link_name == "pthread_mutex_lock" || link_name == "pthread_mutex_unlock" || link_name == "pthread_mutex_destroy" ) - { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); - } - else if( link_name == "pthread_rwlock_rdlock" ) - { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); - } - else if( link_name == "pthread_mutexattr_init" || link_name == "pthread_mutexattr_settype" || link_name == "pthread_mutexattr_destroy" ) - { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); - } - else if( link_name == "pthread_condattr_init" || link_name == "pthread_condattr_destroy" || link_name == "pthread_condattr_setclock" ) - { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); - } - else if( link_name == "pthread_cond_init" || link_name == "pthread_cond_destroy" ) - { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); - } - else if( link_name == "pthread_key_create" ) - { - auto key_ref = args.at(0).read_pointer_valref_mut(0, 4); - - auto key = ThreadState::s_next_tls_key ++; - key_ref.m_alloc.alloc().write_u32( key_ref.m_offset, key ); - - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); - } - else if( link_name == "pthread_getspecific" ) - { - auto key = args.at(0).read_u32(0); - - // Get a pointer-sized value from storage - uint64_t v = key < m_thread.tls_values.size() ? m_thread.tls_values[key] : 0; - - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.write_usize(0, v); - } - else if( link_name == "pthread_setspecific" ) - { - auto key = args.at(0).read_u32(0); - auto v = args.at(1).read_u64(0); - - // Get a pointer-sized value from storage - if( key >= m_thread.tls_values.size() ) { - m_thread.tls_values.resize(key+1); - } - m_thread.tls_values[key] = v; - - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); - } - else if( link_name == "pthread_key_delete" ) - { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); - } -#endif - // std C - else if( link_name == "signal" ) - { - LOG_DEBUG("Call `signal` - Ignoring and returning SIG_IGN"); - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.write_usize(0, 1); - } - // - `void *memchr(const void *s, int c, size_t n);` - else if( link_name == "memchr" ) - { - auto ptr_alloc = args.at(0).get_relocation(0); - auto c = args.at(1).read_i32(0); - auto n = args.at(2).read_usize(0); - const void* ptr = args.at(0).read_pointer_const(0, n); - - const void* ret = memchr(ptr, c, n); - - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.create_allocation(); - if( ret ) - { - rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast(ret) - static_cast(ptr) )); - rv.allocation->relocations.push_back({ 0, ptr_alloc }); - } - else - { - rv.write_usize(0, 0); - } - } - else if( link_name == "memrchr" ) - { - auto ptr_alloc = args.at(0).get_relocation(0); - auto c = args.at(1).read_i32(0); - auto n = args.at(2).read_usize(0); - const void* ptr = args.at(0).read_pointer_const(0, n); - - const void* ret = memrchr(ptr, c, n); - - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.create_allocation(); - if( ret ) - { - rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast(ret) - static_cast(ptr) )); - rv.allocation->relocations.push_back({ 0, ptr_alloc }); - } - else - { - rv.write_usize(0, 0); - } - } - // Allocators! - else - { - LOG_TODO("Call external function " << link_name); - } - return true; -} - -bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args) -{ - TRACE_FUNCTION_R(name, rv); - for(const auto& a : args) - LOG_DEBUG("#" << (&a - args.data()) << ": " << a); - if( name == "type_id" ) - { - const auto& ty_T = ty_params.tys.at(0); - static ::std::vector type_ids; - auto it = ::std::find(type_ids.begin(), type_ids.end(), ty_T); - if( it == type_ids.end() ) - { - it = type_ids.insert(it, ty_T); - } - - rv = Value::with_size(POINTER_SIZE, false); - rv.write_usize(0, it - type_ids.begin()); - } - else if( name == "atomic_fence" || name == "atomic_fence_acq" ) - { - rv = Value(); - } - else if( name == "atomic_store" ) - { - auto& ptr_val = args.at(0); - auto& data_val = args.at(1); - - LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_store of a value that isn't a pointer-sized value"); - - // There MUST be a relocation at this point with a valid allocation. - auto alloc = ptr_val.get_relocation(0); - LOG_ASSERT(alloc, "Deref of a value with no relocation"); - - // TODO: Atomic side of this? - size_t ofs = ptr_val.read_usize(0); - alloc.alloc().write_value(ofs, ::std::move(data_val)); - } - else if( name == "atomic_load" || name == "atomic_load_relaxed" ) - { - auto& ptr_val = args.at(0); - LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_store of a value that isn't a pointer-sized value"); - - // There MUST be a relocation at this point with a valid allocation. - auto alloc = ptr_val.get_relocation(0); - LOG_ASSERT(alloc, "Deref of a value with no relocation"); - // TODO: Atomic lock the allocation. - - size_t ofs = ptr_val.read_usize(0); - const auto& ty = ty_params.tys.at(0); - - rv = alloc.alloc().read_value(ofs, ty.get_size()); - } - else if( name == "atomic_xadd" || name == "atomic_xadd_relaxed" ) - { - const auto& ty_T = ty_params.tys.at(0); - auto ptr_ofs = args.at(0).read_usize(0); - auto ptr_alloc = args.at(0).get_relocation(0); - auto v = args.at(1).read_value(0, ty_T.get_size()); - - // TODO: Atomic lock the allocation. - if( !ptr_alloc || !ptr_alloc.is_alloc() ) { - LOG_ERROR("atomic pointer has no allocation"); - } - - // - Result is the original value - rv = ptr_alloc.alloc().read_value(ptr_ofs, ty_T.get_size()); - - auto val_l = PrimitiveValueVirt::from_value(ty_T, rv); - const auto val_r = PrimitiveValueVirt::from_value(ty_T, v); - val_l.get().add( val_r.get() ); - - val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs ); - } - else if( name == "atomic_xsub" || name == "atomic_xsub_relaxed" || name == "atomic_xsub_rel" ) - { - const auto& ty_T = ty_params.tys.at(0); - auto ptr_ofs = args.at(0).read_usize(0); - auto ptr_alloc = args.at(0).get_relocation(0); - auto v = args.at(1).read_value(0, ty_T.get_size()); - - // TODO: Atomic lock the allocation. - if( !ptr_alloc || !ptr_alloc.is_alloc() ) { - LOG_ERROR("atomic pointer has no allocation"); - } - - // - Result is the original value - rv = ptr_alloc.alloc().read_value(ptr_ofs, ty_T.get_size()); - - auto val_l = PrimitiveValueVirt::from_value(ty_T, rv); - const auto val_r = PrimitiveValueVirt::from_value(ty_T, v); - val_l.get().subtract( val_r.get() ); - - val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs ); - } - else if( name == "atomic_xchg" ) - { - const auto& ty_T = ty_params.tys.at(0); - auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size()); - const auto& new_v = args.at(1); - - rv = data_ref.read_value(0, new_v.size()); - data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v ); - } - else if( name == "atomic_cxchg" ) - { - const auto& ty_T = ty_params.tys.at(0); - // TODO: Get a ValueRef to the target location - auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size()); - const auto& old_v = args.at(1); - const auto& new_v = args.at(2); - rv = Value::with_size( ty_T.get_size() + 1, false ); - rv.write_value(0, data_ref.read_value(0, old_v.size())); - LOG_DEBUG("> *ptr = " << data_ref); - if( data_ref.compare(old_v.data_ptr(), old_v.size()) == true ) { - data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v ); - rv.write_u8( old_v.size(), 1 ); - } - else { - rv.write_u8( old_v.size(), 0 ); - } - } - else if( name == "transmute" ) - { - // Transmute requires the same size, so just copying the value works - rv = ::std::move(args.at(0)); - } - else if( name == "assume" ) - { - // Assume is a no-op which returns unit - } - else if( name == "offset" ) - { - auto ptr_alloc = args.at(0).get_relocation(0); - auto ptr_ofs = args.at(0).read_usize(0); - auto& ofs_val = args.at(1); - - auto delta_counts = ofs_val.read_usize(0); - auto new_ofs = ptr_ofs + delta_counts * ty_params.tys.at(0).get_size(); - if(POINTER_SIZE != 8) { - new_ofs &= 0xFFFFFFFF; - } - - rv = ::std::move(args.at(0)); - rv.write_usize(0, new_ofs); - if( ptr_alloc ) { - rv.allocation->relocations.push_back({ 0, ptr_alloc }); - } - } - // effectively ptr::write - else if( name == "move_val_init" ) - { - auto& ptr_val = args.at(0); - auto& data_val = args.at(1); - - LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "move_val_init of an address that isn't a pointer-sized value"); - - // There MUST be a relocation at this point with a valid allocation. - LOG_ASSERT(ptr_val.allocation, "Deref of a value with no allocation (hence no relocations)"); - LOG_TRACE("Deref " << ptr_val << " and store " << data_val); - - auto ptr_alloc = ptr_val.get_relocation(0); - LOG_ASSERT(ptr_alloc, "Deref of a value with no relocation"); - - size_t ofs = ptr_val.read_usize(0); - ptr_alloc.alloc().write_value(ofs, ::std::move(data_val)); - LOG_DEBUG(ptr_alloc.alloc()); - } - else if( name == "uninit" ) - { - rv = Value(ty_params.tys.at(0)); - } - else if( name == "init" ) - { - rv = Value(ty_params.tys.at(0)); - rv.mark_bytes_valid(0, rv.size()); - } - // - Unsized stuff - else if( name == "size_of_val" ) - { - auto& val = args.at(0); - const auto& ty = ty_params.tys.at(0); - rv = Value(::HIR::TypeRef(RawType::USize)); - // Get unsized type somehow. - // - _HAS_ to be the last type, so that makes it easier - size_t fixed_size = 0; - if( const auto* ity = ty.get_usized_type(fixed_size) ) - { - const auto meta_ty = ty.get_meta_type(); - LOG_DEBUG("size_of_val - " << ty << " ity=" << *ity << " meta_ty=" << meta_ty << " fixed_size=" << fixed_size); - size_t flex_size = 0; - if( !ity->wrappers.empty() ) - { - LOG_ASSERT(ity->wrappers[0].type == TypeWrapper::Ty::Slice, ""); - size_t item_size = ity->get_inner().get_size(); - size_t item_count = val.read_usize(POINTER_SIZE); - flex_size = item_count * item_size; - LOG_DEBUG("> item_size=" << item_size << " item_count=" << item_count << " flex_size=" << flex_size); - } - else if( ity->inner_type == RawType::Str ) - { - flex_size = val.read_usize(POINTER_SIZE); - } - else if( ity->inner_type == RawType::TraitObject ) - { - LOG_TODO("size_of_val - Trait Object - " << ty); - } - else - { - LOG_BUG("Inner unsized type unknown - " << *ity); - } - - rv.write_usize(0, fixed_size + flex_size); - } - else - { - rv.write_usize(0, ty.get_size()); - } - } - else if( name == "drop_in_place" ) - { - auto& val = args.at(0); - const auto& ty = ty_params.tys.at(0); - if( !ty.wrappers.empty() ) - { - size_t item_count = 0; - switch(ty.wrappers[0].type) - { - case TypeWrapper::Ty::Slice: - case TypeWrapper::Ty::Array: - item_count = (ty.wrappers[0].type == TypeWrapper::Ty::Slice ? val.read_usize(POINTER_SIZE) : ty.wrappers[0].size); - break; - case TypeWrapper::Ty::Pointer: - break; - case TypeWrapper::Ty::Borrow: - // TODO: Only &move has a destructor - break; - } - LOG_ASSERT(ty.wrappers[0].type == TypeWrapper::Ty::Slice, "drop_in_place should only exist for slices - " << ty); - const auto& ity = ty.get_inner(); - size_t item_size = ity.get_size(); - - auto ptr = val.read_value(0, POINTER_SIZE); - for(size_t i = 0; i < item_count; i ++) - { - // TODO: Nested calls? - if( !drop_value(ptr, ity) ) - { - LOG_DEBUG("Handle multiple queued calls"); - } - ptr.write_usize(0, ptr.read_usize(0) + item_size); - } - } - else - { - return drop_value(val, ty); - } - } - // ---------------------------------------------------------------- - // Checked arithmatic - else if( name == "add_with_overflow" ) - { - const auto& ty = ty_params.tys.at(0); - - auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0)); - auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1)); - bool didnt_overflow = lhs.get().add( rhs.get() ); - - // Get return type - a tuple of `(T, bool,)` - ::HIR::GenericPath gp; - gp.m_params.tys.push_back(ty); - gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); - const auto& dty = m_modtree.get_composite(gp); - - rv = Value(::HIR::TypeRef(&dty)); - lhs.get().write_to_value(rv, dty.fields[0].first); - rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened - } - else if( name == "sub_with_overflow" ) - { - const auto& ty = ty_params.tys.at(0); - - auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0)); - auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1)); - bool didnt_overflow = lhs.get().subtract( rhs.get() ); - - // Get return type - a tuple of `(T, bool,)` - ::HIR::GenericPath gp; - gp.m_params.tys.push_back(ty); - gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); - const auto& dty = m_modtree.get_composite(gp); - - rv = Value(::HIR::TypeRef(&dty)); - lhs.get().write_to_value(rv, dty.fields[0].first); - rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened - } - else if( name == "mul_with_overflow" ) - { - const auto& ty = ty_params.tys.at(0); - - auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0)); - auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1)); - bool didnt_overflow = lhs.get().multiply( rhs.get() ); - - // Get return type - a tuple of `(T, bool,)` - ::HIR::GenericPath gp; - gp.m_params.tys.push_back(ty); - gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); - const auto& dty = m_modtree.get_composite(gp); - - rv = Value(::HIR::TypeRef(&dty)); - lhs.get().write_to_value(rv, dty.fields[0].first); - rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened - } - // Overflowing artithmatic - else if( name == "overflowing_sub" ) - { - const auto& ty = ty_params.tys.at(0); - - auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0)); - auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1)); - lhs.get().subtract( rhs.get() ); - - rv = Value(ty); - lhs.get().write_to_value(rv, 0); - } - // ---------------------------------------------------------------- - // memcpy - else if( name == "copy_nonoverlapping" ) - { - auto src_ofs = args.at(0).read_usize(0); - auto src_alloc = args.at(0).get_relocation(0); - auto dst_ofs = args.at(1).read_usize(0); - auto dst_alloc = args.at(1).get_relocation(0); - size_t ent_count = args.at(2).read_usize(0); - size_t ent_size = ty_params.tys.at(0).get_size(); - auto byte_count = ent_count * ent_size; - - LOG_ASSERT(src_alloc, "Source of copy* must have an allocation"); - LOG_ASSERT(dst_alloc, "Destination of copy* must be a memory allocation"); - LOG_ASSERT(dst_alloc.is_alloc(), "Destination of copy* must be a memory allocation"); - - switch(src_alloc.get_ty()) - { - case RelocationPtr::Ty::Allocation: { - auto v = src_alloc.alloc().read_value(src_ofs, byte_count); - LOG_DEBUG("v = " << v); - dst_alloc.alloc().write_value(dst_ofs, ::std::move(v)); - } break; - case RelocationPtr::Ty::StdString: - LOG_ASSERT(src_ofs <= src_alloc.str().size(), ""); - LOG_ASSERT(byte_count <= src_alloc.str().size(), ""); - LOG_ASSERT(src_ofs + byte_count <= src_alloc.str().size(), ""); - dst_alloc.alloc().write_bytes(dst_ofs, src_alloc.str().data() + src_ofs, byte_count); - break; - case RelocationPtr::Ty::Function: - LOG_FATAL("Attempt to copy* a function"); - break; - case RelocationPtr::Ty::FfiPointer: - LOG_BUG("Trying to copy from a FFI pointer"); - break; - } - } - else - { - LOG_TODO("Call intrinsic \"" << name << "\""); - } - return true; -} - -bool InterpreterThread::drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_shallow/*=false*/) -{ - if( is_shallow ) - { - // HACK: Only works for Box where the first pointer is the data pointer - auto box_ptr_vr = ptr.read_pointer_valref_mut(0, POINTER_SIZE); - auto ofs = box_ptr_vr.read_usize(0); - auto alloc = box_ptr_vr.get_relocation(0); - if( ofs != 0 || !alloc || !alloc.is_alloc() ) { - LOG_ERROR("Attempting to shallow drop with invalid pointer (no relocation or non-zero offset) - " << box_ptr_vr); - } - - LOG_DEBUG("drop_value SHALLOW deallocate " << alloc); - alloc.alloc().mark_as_freed(); - return true; - } - if( ty.wrappers.empty() ) - { - if( ty.inner_type == RawType::Composite ) - { - if( ty.composite_type->drop_glue != ::HIR::Path() ) - { - LOG_DEBUG("Drop - " << ty); - - Value tmp; - return this->call_path(tmp, ty.composite_type->drop_glue, { ptr }); - } - else - { - // No drop glue - } - } - else if( ty.inner_type == RawType::TraitObject ) - { - LOG_TODO("Drop - " << ty << " - trait object"); - } - else - { - // No destructor - } - } - else - { - switch( ty.wrappers[0].type ) - { - case TypeWrapper::Ty::Borrow: - if( ty.wrappers[0].size == static_cast(::HIR::BorrowType::Move) ) - { - LOG_TODO("Drop - " << ty << " - dereference and go to inner"); - // TODO: Clear validity on the entire inner value. - } - else - { - // No destructor - } - break; - case TypeWrapper::Ty::Pointer: - // No destructor - break; - // TODO: Arrays - default: - LOG_TODO("Drop - " << ty << " - array?"); - break; - } - } - return true; -} int ProgramOptions::parse(int argc, const char* argv[]) { diff --git a/tools/standalone_miri/miri.cpp b/tools/standalone_miri/miri.cpp new file mode 100644 index 00000000..a4390e66 --- /dev/null +++ b/tools/standalone_miri/miri.cpp @@ -0,0 +1,2302 @@ +// +// +// +#include +#include "module_tree.hpp" +#include "value.hpp" +#include +#include +#include "debug.hpp" +#include "miri.hpp" +#ifdef _WIN32 +# define NOMINMAX +# include +#endif + +unsigned ThreadState::s_next_tls_key = 1; + +class PrimitiveValue +{ +public: + virtual ~PrimitiveValue() {} + + virtual bool add(const PrimitiveValue& v) = 0; + virtual bool subtract(const PrimitiveValue& v) = 0; + virtual bool multiply(const PrimitiveValue& v) = 0; + virtual bool divide(const PrimitiveValue& v) = 0; + virtual bool modulo(const PrimitiveValue& v) = 0; + virtual void write_to_value(ValueCommonWrite& tgt, size_t ofs) const = 0; + + template + const T& check(const char* opname) const + { + const auto* xp = dynamic_cast(this); + LOG_ASSERT(xp, "Attempting to " << opname << " mismatched types, expected " << typeid(T).name() << " got " << typeid(*this).name()); + return *xp; + } +}; +template +struct PrimitiveUInt: + public PrimitiveValue +{ + typedef PrimitiveUInt Self; + T v; + + PrimitiveUInt(T v): v(v) {} + ~PrimitiveUInt() override {} + + bool add(const PrimitiveValue& x) override { + const auto* xp = &x.check("add"); + T newv = this->v + xp->v; + bool did_overflow = newv < this->v; + this->v = newv; + return !did_overflow; + } + bool subtract(const PrimitiveValue& x) override { + const auto* xp = &x.check("subtract"); + T newv = this->v - xp->v; + bool did_overflow = newv > this->v; + this->v = newv; + return !did_overflow; + } + bool multiply(const PrimitiveValue& x) override { + const auto* xp = &x.check("multiply"); + T newv = this->v * xp->v; + bool did_overflow = newv < this->v && newv < xp->v; + this->v = newv; + return !did_overflow; + } + bool divide(const PrimitiveValue& x) override { + const auto* xp = &x.check("divide"); + if(xp->v == 0) return false; + T newv = this->v / xp->v; + this->v = newv; + return true; + } + bool modulo(const PrimitiveValue& x) override { + const auto* xp = &x.check("modulo"); + if(xp->v == 0) return false; + T newv = this->v % xp->v; + this->v = newv; + return true; + } +}; +struct PrimitiveU64: public PrimitiveUInt +{ + PrimitiveU64(uint64_t v): PrimitiveUInt(v) {} + void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { + tgt.write_u64(ofs, this->v); + } +}; +struct PrimitiveU32: public PrimitiveUInt +{ + PrimitiveU32(uint32_t v): PrimitiveUInt(v) {} + void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { + tgt.write_u32(ofs, this->v); + } +}; +template +struct PrimitiveSInt: + public PrimitiveValue +{ + typedef PrimitiveSInt Self; + T v; + + PrimitiveSInt(T v): v(v) {} + ~PrimitiveSInt() override {} + + // TODO: Make this correct. + bool add(const PrimitiveValue& x) override { + const auto* xp = &x.check("add"); + T newv = this->v + xp->v; + bool did_overflow = newv < this->v; + this->v = newv; + return !did_overflow; + } + bool subtract(const PrimitiveValue& x) override { + const auto* xp = &x.check("subtract"); + T newv = this->v - xp->v; + bool did_overflow = newv > this->v; + this->v = newv; + return !did_overflow; + } + bool multiply(const PrimitiveValue& x) override { + const auto* xp = &x.check("multiply"); + T newv = this->v * xp->v; + bool did_overflow = newv < this->v && newv < xp->v; + this->v = newv; + return !did_overflow; + } + bool divide(const PrimitiveValue& x) override { + const auto* xp = &x.check("divide"); + if(xp->v == 0) return false; + T newv = this->v / xp->v; + this->v = newv; + return true; + } + bool modulo(const PrimitiveValue& x) override { + const auto* xp = &x.check("modulo"); + if(xp->v == 0) return false; + T newv = this->v % xp->v; + this->v = newv; + return true; + } +}; +struct PrimitiveI64: public PrimitiveSInt +{ + PrimitiveI64(int64_t v): PrimitiveSInt(v) {} + void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { + tgt.write_i64(ofs, this->v); + } +}; +struct PrimitiveI32: public PrimitiveSInt +{ + PrimitiveI32(int32_t v): PrimitiveSInt(v) {} + void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override { + tgt.write_i32(ofs, this->v); + } +}; + +class PrimitiveValueVirt +{ + uint64_t buf[3]; // Allows i128 plus a vtable pointer + PrimitiveValueVirt() {} +public: + // HACK: No copy/move constructors, assumes that contained data is always POD + ~PrimitiveValueVirt() { + reinterpret_cast(&this->buf)->~PrimitiveValue(); + } + PrimitiveValue& get() { return *reinterpret_cast(&this->buf); } + const PrimitiveValue& get() const { return *reinterpret_cast(&this->buf); } + + static PrimitiveValueVirt from_value(const ::HIR::TypeRef& t, const ValueRef& v) { + PrimitiveValueVirt rv; + LOG_ASSERT(t.wrappers.empty(), "PrimitiveValueVirt::from_value: " << t); + switch(t.inner_type) + { + case RawType::U32: + new(&rv.buf) PrimitiveU32(v.read_u32(0)); + break; + case RawType::U64: + new(&rv.buf) PrimitiveU64(v.read_u64(0)); + break; + case RawType::USize: + if( POINTER_SIZE == 8 ) + new(&rv.buf) PrimitiveU64(v.read_u64(0)); + else + new(&rv.buf) PrimitiveU32(v.read_u32(0)); + break; + + case RawType::I32: + new(&rv.buf) PrimitiveI32(v.read_i32(0)); + break; + case RawType::I64: + new(&rv.buf) PrimitiveI64(v.read_i64(0)); + break; + case RawType::ISize: + if( POINTER_SIZE == 8 ) + new(&rv.buf) PrimitiveI64(v.read_i64(0)); + else + new(&rv.buf) PrimitiveI32(v.read_i32(0)); + break; + default: + LOG_TODO("PrimitiveValueVirt::from_value: " << t); + } + return rv; + } +}; + +struct Ops { + template + static int do_compare(T l, T r) { + if( l == r ) { + return 0; + } + else if( !(l != r) ) { + // Special return value for NaN w/ NaN + return 2; + } + else if( l < r ) { + return -1; + } + else { + return 1; + } + } + template + static T do_bitwise(T l, T r, ::MIR::eBinOp op) { + switch(op) + { + case ::MIR::eBinOp::BIT_AND: return l & r; + case ::MIR::eBinOp::BIT_OR: return l | r; + case ::MIR::eBinOp::BIT_XOR: return l ^ r; + case ::MIR::eBinOp::BIT_SHL: return l << r; + case ::MIR::eBinOp::BIT_SHR: return l >> r; + default: + LOG_BUG("Unexpected operation in Ops::do_bitwise"); + } + } +}; + +struct MirHelpers +{ + InterpreterThread& thread; + InterpreterThread::StackFrame& frame; + + MirHelpers(InterpreterThread& thread, InterpreterThread::StackFrame& frame): + thread(thread), + frame(frame) + { + } + + ValueRef get_value_and_type(const ::MIR::LValue& lv, ::HIR::TypeRef& ty) + { + switch(lv.tag()) + { + case ::MIR::LValue::TAGDEAD: throw ""; + // --> Slots + TU_ARM(lv, Return, _e) { + ty = this->frame.fcn.ret_ty; + return ValueRef(this->frame.ret); + } break; + TU_ARM(lv, Local, e) { + ty = this->frame.fcn.m_mir.locals.at(e); + return ValueRef(this->frame.locals.at(e)); + } break; + TU_ARM(lv, Argument, e) { + ty = this->frame.fcn.args.at(e.idx); + return ValueRef(this->frame.args.at(e.idx)); + } break; + TU_ARM(lv, Static, e) { + /*const*/ auto& s = this->thread.m_modtree.get_static(e); + ty = s.ty; + return ValueRef(s.val); + } break; + // --> Modifiers + TU_ARM(lv, Index, e) { + auto idx = get_value_ref(*e.idx).read_usize(0); + ::HIR::TypeRef array_ty; + auto base_val = get_value_and_type(*e.val, array_ty); + if( array_ty.wrappers.empty() ) + LOG_ERROR("Indexing non-array/slice - " << array_ty); + if( array_ty.wrappers.front().type == TypeWrapper::Ty::Array ) + { + ty = array_ty.get_inner(); + base_val.m_offset += ty.get_size() * idx; + return base_val; + } + else if( array_ty.wrappers.front().type == TypeWrapper::Ty::Slice ) + { + LOG_TODO("Slice index"); + } + else + { + LOG_ERROR("Indexing non-array/slice - " << array_ty); + throw "ERROR"; + } + } break; + TU_ARM(lv, Field, e) { + ::HIR::TypeRef composite_ty; + auto base_val = get_value_and_type(*e.val, composite_ty); + // TODO: if there's metadata present in the base, but the inner doesn't have metadata, clear the metadata + size_t inner_ofs; + ty = composite_ty.get_field(e.field_index, inner_ofs); + LOG_DEBUG("Field - " << composite_ty << "#" << e.field_index << " = @" << inner_ofs << " " << ty); + base_val.m_offset += inner_ofs; + if( ty.get_meta_type() == HIR::TypeRef(RawType::Unreachable) ) + { + LOG_ASSERT(base_val.m_size >= ty.get_size(), "Field didn't fit in the value - " << ty.get_size() << " required, but " << base_val.m_size << " avail"); + base_val.m_size = ty.get_size(); + } + return base_val; + } + TU_ARM(lv, Downcast, e) { + ::HIR::TypeRef composite_ty; + auto base_val = get_value_and_type(*e.val, composite_ty); + LOG_DEBUG("Downcast - " << composite_ty); + + size_t inner_ofs; + ty = composite_ty.get_field(e.variant_index, inner_ofs); + base_val.m_offset += inner_ofs; + return base_val; + } + TU_ARM(lv, Deref, e) { + ::HIR::TypeRef ptr_ty; + auto val = get_value_and_type(*e.val, ptr_ty); + ty = ptr_ty.get_inner(); + LOG_DEBUG("val = " << val << ", (inner) ty=" << ty); + + LOG_ASSERT(val.m_size >= POINTER_SIZE, "Deref of a value that doesn't fit a pointer - " << ty); + size_t ofs = val.read_usize(0); + + // There MUST be a relocation at this point with a valid allocation. + auto alloc = val.get_relocation(val.m_offset); + LOG_TRACE("Deref " << alloc << " + " << ofs << " to give value of type " << ty); + // NOTE: No alloc can happen when dereferencing a zero-sized pointer + if( alloc.is_alloc() ) + { + LOG_DEBUG("> " << lv << " alloc=" << alloc.alloc()); + } + size_t size; + + const auto meta_ty = ty.get_meta_type(); + ::std::shared_ptr meta_val; + // If the type has metadata, store it. + if( meta_ty != RawType::Unreachable ) + { + auto meta_size = meta_ty.get_size(); + LOG_ASSERT(val.m_size == POINTER_SIZE + meta_size, "Deref of " << ty << ", but pointer isn't correct size"); + meta_val = ::std::make_shared( val.read_value(POINTER_SIZE, meta_size) ); + + // TODO: Get a more sane size from the metadata + if( alloc ) + { + LOG_DEBUG("> Meta " << *meta_val << ", size = " << alloc.get_size() << " - " << ofs); + size = alloc.get_size() - ofs; + } + else + { + size = 0; + } + } + else + { + LOG_ASSERT(val.m_size == POINTER_SIZE, "Deref of a value that isn't a pointer-sized value (size=" << val.m_size << ") - " << val << ": " << ptr_ty); + size = ty.get_size(); + if( !alloc ) { + LOG_ERROR("Deref of a value with no relocation - " << val); + } + } + + LOG_DEBUG("alloc=" << alloc << ", ofs=" << ofs << ", size=" << size); + auto rv = ValueRef(::std::move(alloc), ofs, size); + rv.m_metadata = ::std::move(meta_val); + return rv; + } break; + } + throw ""; + } + ValueRef get_value_ref(const ::MIR::LValue& lv) + { + ::HIR::TypeRef tmp; + return get_value_and_type(lv, tmp); + } + + ::HIR::TypeRef get_lvalue_ty(const ::MIR::LValue& lv) + { + ::HIR::TypeRef ty; + get_value_and_type(lv, ty); + return ty; + } + + Value read_lvalue_with_ty(const ::MIR::LValue& lv, ::HIR::TypeRef& ty) + { + auto base_value = get_value_and_type(lv, ty); + + return base_value.read_value(0, ty.get_size()); + } + Value read_lvalue(const ::MIR::LValue& lv) + { + ::HIR::TypeRef ty; + return read_lvalue_with_ty(lv, ty); + } + void write_lvalue(const ::MIR::LValue& lv, Value val) + { + //LOG_DEBUG(lv << " = " << val); + ::HIR::TypeRef ty; + auto base_value = get_value_and_type(lv, ty); + + if(base_value.m_alloc) { + base_value.m_alloc.alloc().write_value(base_value.m_offset, ::std::move(val)); + } + else { + base_value.m_value->write_value(base_value.m_offset, ::std::move(val)); + } + } + + Value const_to_value(const ::MIR::Constant& c, ::HIR::TypeRef& ty) + { + switch(c.tag()) + { + case ::MIR::Constant::TAGDEAD: throw ""; + TU_ARM(c, Int, ce) { + ty = ::HIR::TypeRef(ce.t); + Value val = Value(ty); + val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian + // TODO: If the write was clipped, sign-extend + return val; + } break; + TU_ARM(c, Uint, ce) { + ty = ::HIR::TypeRef(ce.t); + Value val = Value(ty); + val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian + return val; + } break; + TU_ARM(c, Bool, ce) { + Value val = Value(::HIR::TypeRef { RawType::Bool }); + val.write_bytes(0, &ce.v, 1); + return val; + } break; + TU_ARM(c, Float, ce) { + ty = ::HIR::TypeRef(ce.t); + Value val = Value(ty); + if( ce.t.raw_type == RawType::F64 ) { + val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian/format? + } + else if( ce.t.raw_type == RawType::F32 ) { + float v = static_cast(ce.v); + val.write_bytes(0, &v, ::std::min(ty.get_size(), sizeof(v))); // TODO: Endian/format? + } + else { + throw ::std::runtime_error("BUG: Invalid type in Constant::Float"); + } + return val; + } break; + TU_ARM(c, Const, ce) { + LOG_BUG("Constant::Const in mmir"); + } break; + TU_ARM(c, Bytes, ce) { + LOG_TODO("Constant::Bytes"); + } break; + TU_ARM(c, StaticString, ce) { + ty = ::HIR::TypeRef(RawType::Str); + ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); + Value val = Value(ty); + val.write_usize(0, 0); + val.write_usize(POINTER_SIZE, ce.size()); + val.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_string(&ce) }); + LOG_DEBUG(c << " = " << val); + //return Value::new_dataptr(ce.data()); + return val; + } break; + // --> Accessor + TU_ARM(c, ItemAddr, ce) { + // Create a value with a special backing allocation of zero size that references the specified item. + if( /*const auto* fn =*/ this->thread.m_modtree.get_function_opt(ce) ) { + ty = ::HIR::TypeRef(RawType::Function); + return Value::new_fnptr(ce); + } + if( const auto* s = this->thread.m_modtree.get_static_opt(ce) ) { + ty = s->ty; + ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); + Value val = Value(ty); + val.write_usize(0, 0); + val.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_alloc(s->val.allocation) }); + return val; + } + LOG_ERROR("Constant::ItemAddr - " << ce << " - not found"); + } break; + } + throw ""; + } + Value const_to_value(const ::MIR::Constant& c) + { + ::HIR::TypeRef ty; + return const_to_value(c, ty); + } + Value param_to_value(const ::MIR::Param& p, ::HIR::TypeRef& ty) + { + switch(p.tag()) + { + case ::MIR::Param::TAGDEAD: throw ""; + TU_ARM(p, Constant, pe) + return const_to_value(pe, ty); + TU_ARM(p, LValue, pe) + return read_lvalue_with_ty(pe, ty); + } + throw ""; + } + Value param_to_value(const ::MIR::Param& p) + { + ::HIR::TypeRef ty; + return param_to_value(p, ty); + } + + ValueRef get_value_ref_param(const ::MIR::Param& p, Value& tmp, ::HIR::TypeRef& ty) + { + switch(p.tag()) + { + case ::MIR::Param::TAGDEAD: throw ""; + TU_ARM(p, Constant, pe) + tmp = const_to_value(pe, ty); + return ValueRef(tmp, 0, ty.get_size()); + TU_ARM(p, LValue, pe) + return get_value_and_type(pe, ty); + } + throw ""; + } +}; + +// ==================================================================== +// +// ==================================================================== +InterpreterThread::~InterpreterThread() +{ + for(size_t i = 0; i < m_stack.size(); i++) + { + const auto& frame = m_stack[m_stack.size() - 1 - i]; + ::std::cout << "#" << i << ": " << frame.fcn.my_path << " BB" << frame.bb_idx << "/"; + if( frame.stmt_idx == frame.fcn.m_mir.blocks.at(frame.bb_idx).statements.size() ) + ::std::cout << "TERM"; + else + ::std::cout << frame.stmt_idx; + ::std::cout << ::std::endl; + } +} +void InterpreterThread::start(const ::HIR::Path& p, ::std::vector args) +{ + assert( this->m_stack.empty() ); + Value v; + if( this->call_path(v, p, ::std::move(args)) ) + { + LOG_TODO("Handle immediate return thread entry"); + } +} +bool InterpreterThread::step_one(Value& out_thread_result) +{ + assert( !this->m_stack.empty() ); + assert( !this->m_stack.back().cb ); + auto& cur_frame = this->m_stack.back(); + TRACE_FUNCTION_R(cur_frame.fcn.my_path, ""); + const auto& bb = cur_frame.fcn.m_mir.blocks.at( cur_frame.bb_idx ); + + MirHelpers state { *this, cur_frame }; + + if( cur_frame.stmt_idx < bb.statements.size() ) + { + const auto& stmt = bb.statements[cur_frame.stmt_idx]; + LOG_DEBUG("=== BB" << cur_frame.bb_idx << "/" << cur_frame.stmt_idx << ": " << stmt); + switch(stmt.tag()) + { + case ::MIR::Statement::TAGDEAD: throw ""; + TU_ARM(stmt, Assign, se) { + Value new_val; + switch(se.src.tag()) + { + case ::MIR::RValue::TAGDEAD: throw ""; + TU_ARM(se.src, Use, re) { + new_val = state.read_lvalue(re); + } break; + TU_ARM(se.src, Constant, re) { + new_val = state.const_to_value(re); + } break; + TU_ARM(se.src, Borrow, re) { + ::HIR::TypeRef src_ty; + ValueRef src_base_value = state.get_value_and_type(re.val, src_ty); + auto alloc = src_base_value.m_alloc; + if( !alloc && src_base_value.m_value ) + { + if( !src_base_value.m_value->allocation ) + { + src_base_value.m_value->create_allocation(); + } + alloc = RelocationPtr::new_alloc( src_base_value.m_value->allocation ); + } + if( alloc.is_alloc() ) + LOG_DEBUG("- alloc=" << alloc << " (" << alloc.alloc() << ")"); + else + LOG_DEBUG("- alloc=" << alloc); + size_t ofs = src_base_value.m_offset; + const auto meta = src_ty.get_meta_type(); + //bool is_slice_like = src_ty.has_slice_meta(); + src_ty.wrappers.insert(src_ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, static_cast(re.type) }); + + new_val = Value(src_ty); + // ^ Pointer value + new_val.write_usize(0, ofs); + if( meta != RawType::Unreachable ) + { + LOG_ASSERT(src_base_value.m_metadata, "Borrow of an unsized value, but no metadata avaliable"); + new_val.write_value(POINTER_SIZE, *src_base_value.m_metadata); + } + // - Add the relocation after writing the value (writing clears the relocations) + new_val.allocation->relocations.push_back(Relocation { 0, ::std::move(alloc) }); + } break; + TU_ARM(se.src, Cast, re) { + // Determine the type of cast, is it a reinterpret or is it a value transform? + // - Float <-> integer is a transform, anything else should be a reinterpret. + ::HIR::TypeRef src_ty; + auto src_value = state.get_value_and_type(re.val, src_ty); + + new_val = Value(re.type); + if( re.type == src_ty ) + { + // No-op cast + new_val = src_value.read_value(0, re.type.get_size()); + } + else if( !re.type.wrappers.empty() ) + { + // Destination can only be a raw pointer + if( re.type.wrappers.at(0).type != TypeWrapper::Ty::Pointer ) { + throw "ERROR"; + } + if( !src_ty.wrappers.empty() ) + { + // Source can be either + if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer + && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { + throw "ERROR"; + } + + if( src_ty.get_size() > re.type.get_size() ) { + // TODO: How to casting fat to thin? + //LOG_TODO("Handle casting fat to thin, " << src_ty << " -> " << re.type); + new_val = src_value.read_value(0, re.type.get_size()); + } + else + { + new_val = src_value.read_value(0, re.type.get_size()); + } + } + else + { + if( src_ty == RawType::Function ) + { + } + else if( src_ty == RawType::USize ) + { + } + else + { + ::std::cerr << "ERROR: Trying to pointer (" << re.type <<" ) from invalid type (" << src_ty << ")\n"; + throw "ERROR"; + } + new_val = src_value.read_value(0, re.type.get_size()); + } + } + else if( !src_ty.wrappers.empty() ) + { + // TODO: top wrapper MUST be a pointer + if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer + && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { + throw "ERROR"; + } + // TODO: MUST be a thin pointer? + + // TODO: MUST be an integer (usize only?) + if( re.type != RawType::USize && re.type != RawType::ISize ) { + LOG_ERROR("Casting from a pointer to non-usize - " << re.type << " to " << src_ty); + throw "ERROR"; + } + new_val = src_value.read_value(0, re.type.get_size()); + } + else + { + // TODO: What happens if there'a cast of something with a relocation? + switch(re.type.inner_type) + { + case RawType::Unreachable: throw "BUG"; + case RawType::Composite: + case RawType::TraitObject: + case RawType::Function: + case RawType::Str: + case RawType::Unit: + LOG_ERROR("Casting to " << re.type << " is invalid"); + throw "ERROR"; + case RawType::F32: { + float dst_val = 0.0; + // Can be an integer, or F64 (pointer is impossible atm) + switch(src_ty.inner_type) + { + case RawType::Unreachable: throw "BUG"; + case RawType::Composite: throw "ERROR"; + case RawType::TraitObject: throw "ERROR"; + case RawType::Function: throw "ERROR"; + case RawType::Char: throw "ERROR"; + case RawType::Str: throw "ERROR"; + case RawType::Unit: throw "ERROR"; + case RawType::Bool: throw "ERROR"; + case RawType::F32: throw "BUG"; + case RawType::F64: dst_val = static_cast( src_value.read_f64(0) ); break; + case RawType::USize: throw "TODO";// /*dst_val = src_value.read_usize();*/ break; + case RawType::ISize: throw "TODO";// /*dst_val = src_value.read_isize();*/ break; + case RawType::U8: dst_val = static_cast( src_value.read_u8 (0) ); break; + case RawType::I8: dst_val = static_cast( src_value.read_i8 (0) ); break; + case RawType::U16: dst_val = static_cast( src_value.read_u16(0) ); break; + case RawType::I16: dst_val = static_cast( src_value.read_i16(0) ); break; + case RawType::U32: dst_val = static_cast( src_value.read_u32(0) ); break; + case RawType::I32: dst_val = static_cast( src_value.read_i32(0) ); break; + case RawType::U64: dst_val = static_cast( src_value.read_u64(0) ); break; + case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); break; + case RawType::U128: throw "TODO";// /*dst_val = src_value.read_u128();*/ break; + case RawType::I128: throw "TODO";// /*dst_val = src_value.read_i128();*/ break; + } + new_val.write_f32(0, dst_val); + } break; + case RawType::F64: { + double dst_val = 0.0; + // Can be an integer, or F32 (pointer is impossible atm) + switch(src_ty.inner_type) + { + case RawType::Unreachable: throw "BUG"; + case RawType::Composite: throw "ERROR"; + case RawType::TraitObject: throw "ERROR"; + case RawType::Function: throw "ERROR"; + case RawType::Char: throw "ERROR"; + case RawType::Str: throw "ERROR"; + case RawType::Unit: throw "ERROR"; + case RawType::Bool: throw "ERROR"; + case RawType::F64: throw "BUG"; + case RawType::F32: dst_val = static_cast( src_value.read_f32(0) ); break; + case RawType::USize: dst_val = static_cast( src_value.read_usize(0) ); break; + case RawType::ISize: dst_val = static_cast( src_value.read_isize(0) ); break; + case RawType::U8: dst_val = static_cast( src_value.read_u8 (0) ); break; + case RawType::I8: dst_val = static_cast( src_value.read_i8 (0) ); break; + case RawType::U16: dst_val = static_cast( src_value.read_u16(0) ); break; + case RawType::I16: dst_val = static_cast( src_value.read_i16(0) ); break; + case RawType::U32: dst_val = static_cast( src_value.read_u32(0) ); break; + case RawType::I32: dst_val = static_cast( src_value.read_i32(0) ); break; + case RawType::U64: dst_val = static_cast( src_value.read_u64(0) ); break; + case RawType::I64: dst_val = static_cast( src_value.read_i64(0) ); break; + case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break; + case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break; + } + new_val.write_f64(0, dst_val); + } break; + case RawType::Bool: + LOG_TODO("Cast to " << re.type); + case RawType::Char: + LOG_TODO("Cast to " << re.type); + case RawType::USize: + case RawType::U8: + case RawType::U16: + case RawType::U32: + case RawType::U64: + case RawType::ISize: + case RawType::I8: + case RawType::I16: + case RawType::I32: + case RawType::I64: + { + uint64_t dst_val = 0; + // Can be an integer, or F32 (pointer is impossible atm) + switch(src_ty.inner_type) + { + case RawType::Unreachable: + LOG_BUG("Casting unreachable"); + case RawType::TraitObject: + case RawType::Str: + LOG_FATAL("Cast of unsized type - " << src_ty); + case RawType::Function: + LOG_ASSERT(re.type.inner_type == RawType::USize, "Function pointers can only be casted to usize, instead " << re.type); + new_val = src_value.read_value(0, re.type.get_size()); + break; + case RawType::Char: + LOG_ASSERT(re.type.inner_type == RawType::U32, "Char can only be casted to u32, instead " << re.type); + new_val = src_value.read_value(0, 4); + break; + case RawType::Unit: + LOG_FATAL("Cast of unit"); + case RawType::Composite: { + const auto& dt = *src_ty.composite_type; + if( dt.variants.size() == 0 ) { + LOG_FATAL("Cast of composite - " << src_ty); + } + // TODO: Check that all variants have the same tag offset + LOG_ASSERT(dt.fields.size() == 1, ""); + LOG_ASSERT(dt.fields[0].first == 0, ""); + for(size_t i = 0; i < dt.variants.size(); i ++ ) { + LOG_ASSERT(dt.variants[i].base_field == 0, ""); + LOG_ASSERT(dt.variants[i].field_path.empty(), ""); + } + ::HIR::TypeRef tag_ty = dt.fields[0].second; + LOG_ASSERT(tag_ty.wrappers.empty(), ""); + switch(tag_ty.inner_type) + { + case RawType::USize: + dst_val = static_cast( src_value.read_usize(0) ); + if(0) + case RawType::ISize: + dst_val = static_cast( src_value.read_isize(0) ); + if(0) + case RawType::U8: + dst_val = static_cast( src_value.read_u8 (0) ); + if(0) + case RawType::I8: + dst_val = static_cast( src_value.read_i8 (0) ); + if(0) + case RawType::U16: + dst_val = static_cast( src_value.read_u16(0) ); + if(0) + case RawType::I16: + dst_val = static_cast( src_value.read_i16(0) ); + if(0) + case RawType::U32: + dst_val = static_cast( src_value.read_u32(0) ); + if(0) + case RawType::I32: + dst_val = static_cast( src_value.read_i32(0) ); + if(0) + case RawType::U64: + dst_val = static_cast( src_value.read_u64(0) ); + if(0) + case RawType::I64: + dst_val = static_cast( src_value.read_i64(0) ); + break; + default: + LOG_FATAL("Bad tag type in cast - " << tag_ty); + } + } if(0) + case RawType::Bool: + dst_val = static_cast( src_value.read_u8 (0) ); + if(0) + case RawType::F64: + dst_val = static_cast( src_value.read_f64(0) ); + if(0) + case RawType::F32: + dst_val = static_cast( src_value.read_f32(0) ); + if(0) + case RawType::USize: + dst_val = static_cast( src_value.read_usize(0) ); + if(0) + case RawType::ISize: + dst_val = static_cast( src_value.read_isize(0) ); + if(0) + case RawType::U8: + dst_val = static_cast( src_value.read_u8 (0) ); + if(0) + case RawType::I8: + dst_val = static_cast( src_value.read_i8 (0) ); + if(0) + case RawType::U16: + dst_val = static_cast( src_value.read_u16(0) ); + if(0) + case RawType::I16: + dst_val = static_cast( src_value.read_i16(0) ); + if(0) + case RawType::U32: + dst_val = static_cast( src_value.read_u32(0) ); + if(0) + case RawType::I32: + dst_val = static_cast( src_value.read_i32(0) ); + if(0) + case RawType::U64: + dst_val = static_cast( src_value.read_u64(0) ); + if(0) + case RawType::I64: + dst_val = static_cast( src_value.read_i64(0) ); + + switch(re.type.inner_type) + { + case RawType::USize: + new_val.write_usize(0, dst_val); + break; + case RawType::U8: + new_val.write_u8(0, static_cast(dst_val)); + break; + case RawType::U16: + new_val.write_u16(0, static_cast(dst_val)); + break; + case RawType::U32: + new_val.write_u32(0, static_cast(dst_val)); + break; + case RawType::U64: + new_val.write_u64(0, dst_val); + break; + case RawType::ISize: + new_val.write_usize(0, static_cast(dst_val)); + break; + case RawType::I8: + new_val.write_i8(0, static_cast(dst_val)); + break; + case RawType::I16: + new_val.write_i16(0, static_cast(dst_val)); + break; + case RawType::I32: + new_val.write_i32(0, static_cast(dst_val)); + break; + case RawType::I64: + new_val.write_i64(0, static_cast(dst_val)); + break; + default: + throw ""; + } + break; + case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break; + case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break; + } + } break; + case RawType::U128: + case RawType::I128: + LOG_TODO("Cast to " << re.type); + } + } + } break; + TU_ARM(se.src, BinOp, re) { + ::HIR::TypeRef ty_l, ty_r; + Value tmp_l, tmp_r; + auto v_l = state.get_value_ref_param(re.val_l, tmp_l, ty_l); + auto v_r = state.get_value_ref_param(re.val_r, tmp_r, ty_r); + LOG_DEBUG(v_l << " (" << ty_l <<") ? " << v_r << " (" << ty_r <<")"); + + switch(re.op) + { + case ::MIR::eBinOp::EQ: + case ::MIR::eBinOp::NE: + case ::MIR::eBinOp::GT: + case ::MIR::eBinOp::GE: + case ::MIR::eBinOp::LT: + case ::MIR::eBinOp::LE: { + LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); + int res = 0; + // TODO: Handle comparison of the relocations too + + const auto& alloc_l = v_l.m_value ? v_l.m_value->allocation : v_l.m_alloc; + const auto& alloc_r = v_r.m_value ? v_r.m_value->allocation : v_r.m_alloc; + auto reloc_l = alloc_l ? v_l.get_relocation(v_l.m_offset) : RelocationPtr(); + auto reloc_r = alloc_r ? v_r.get_relocation(v_r.m_offset) : RelocationPtr(); + + if( reloc_l != reloc_r ) + { + res = (reloc_l < reloc_r ? -1 : 1); + } + LOG_DEBUG("res=" << res << ", " << reloc_l << " ? " << reloc_r); + + if( ty_l.wrappers.empty() ) + { + switch(ty_l.inner_type) + { + case RawType::U64: res = res != 0 ? res : Ops::do_compare(v_l.read_u64(0), v_r.read_u64(0)); break; + case RawType::U32: res = res != 0 ? res : Ops::do_compare(v_l.read_u32(0), v_r.read_u32(0)); break; + case RawType::U16: res = res != 0 ? res : Ops::do_compare(v_l.read_u16(0), v_r.read_u16(0)); break; + case RawType::U8 : res = res != 0 ? res : Ops::do_compare(v_l.read_u8 (0), v_r.read_u8 (0)); break; + case RawType::I64: res = res != 0 ? res : Ops::do_compare(v_l.read_i64(0), v_r.read_i64(0)); break; + case RawType::I32: res = res != 0 ? res : Ops::do_compare(v_l.read_i32(0), v_r.read_i32(0)); break; + case RawType::I16: res = res != 0 ? res : Ops::do_compare(v_l.read_i16(0), v_r.read_i16(0)); break; + case RawType::I8 : res = res != 0 ? res : Ops::do_compare(v_l.read_i8 (0), v_r.read_i8 (0)); break; + case RawType::USize: res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); break; + case RawType::ISize: res = res != 0 ? res : Ops::do_compare(v_l.read_isize(0), v_r.read_isize(0)); break; + default: + LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); + } + } + else if( ty_l.wrappers.front().type == TypeWrapper::Ty::Pointer ) + { + // TODO: Technically only EQ/NE are valid. + + res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); + + // Compare fat metadata. + if( res == 0 && v_l.m_size > POINTER_SIZE ) + { + reloc_l = v_l.get_relocation(POINTER_SIZE); + reloc_r = v_r.get_relocation(POINTER_SIZE); + + if( res == 0 && reloc_l != reloc_r ) + { + res = (reloc_l < reloc_r ? -1 : 1); + } + res = res != 0 ? res : Ops::do_compare(v_l.read_usize(POINTER_SIZE), v_r.read_usize(POINTER_SIZE)); + } + } + else + { + LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); + } + bool res_bool; + switch(re.op) + { + case ::MIR::eBinOp::EQ: res_bool = (res == 0); break; + case ::MIR::eBinOp::NE: res_bool = (res != 0); break; + case ::MIR::eBinOp::GT: res_bool = (res == 1); break; + case ::MIR::eBinOp::GE: res_bool = (res == 1 || res == 0); break; + case ::MIR::eBinOp::LT: res_bool = (res == -1); break; + case ::MIR::eBinOp::LE: res_bool = (res == -1 || res == 0); break; + break; + default: + LOG_BUG("Unknown comparison"); + } + new_val = Value(::HIR::TypeRef(RawType::Bool)); + new_val.write_u8(0, res_bool ? 1 : 0); + } break; + case ::MIR::eBinOp::BIT_SHL: + case ::MIR::eBinOp::BIT_SHR: { + LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); + LOG_ASSERT(ty_r.wrappers.empty(), "Bitwise operator with non-primitive - " << ty_r); + size_t max_bits = ty_r.get_size() * 8; + uint8_t shift; + auto check_cast = [&](auto v){ LOG_ASSERT(0 <= v && v <= max_bits, "Shift out of range - " << v); return static_cast(v); }; + switch(ty_r.inner_type) + { + case RawType::U64: shift = check_cast(v_r.read_u64(0)); break; + case RawType::U32: shift = check_cast(v_r.read_u32(0)); break; + case RawType::U16: shift = check_cast(v_r.read_u16(0)); break; + case RawType::U8 : shift = check_cast(v_r.read_u8 (0)); break; + case RawType::I64: shift = check_cast(v_r.read_i64(0)); break; + case RawType::I32: shift = check_cast(v_r.read_i32(0)); break; + case RawType::I16: shift = check_cast(v_r.read_i16(0)); break; + case RawType::I8 : shift = check_cast(v_r.read_i8 (0)); break; + case RawType::USize: shift = check_cast(v_r.read_usize(0)); break; + case RawType::ISize: shift = check_cast(v_r.read_isize(0)); break; + default: + LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); + } + new_val = Value(ty_l); + switch(ty_l.inner_type) + { + // TODO: U128 + case RawType::U64: new_val.write_u64(0, Ops::do_bitwise(v_l.read_u64(0), static_cast(shift), re.op)); break; + case RawType::U32: new_val.write_u32(0, Ops::do_bitwise(v_l.read_u32(0), static_cast(shift), re.op)); break; + case RawType::U16: new_val.write_u16(0, Ops::do_bitwise(v_l.read_u16(0), static_cast(shift), re.op)); break; + case RawType::U8 : new_val.write_u8 (0, Ops::do_bitwise(v_l.read_u8 (0), static_cast(shift), re.op)); break; + case RawType::USize: new_val.write_usize(0, Ops::do_bitwise(v_l.read_usize(0), static_cast(shift), re.op)); break; + // TODO: Is signed allowed? + default: + LOG_TODO("BinOp shift rhs unknown type - " << se.src << " w/ " << ty_r); + } + } break; + case ::MIR::eBinOp::BIT_AND: + case ::MIR::eBinOp::BIT_OR: + case ::MIR::eBinOp::BIT_XOR: + LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); + LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); + new_val = Value(ty_l); + switch(ty_l.inner_type) + { + // TODO: U128/I128 + case RawType::U64: + case RawType::I64: + new_val.write_u64( 0, Ops::do_bitwise(v_l.read_u64(0), v_r.read_u64(0), re.op) ); + break; + case RawType::U32: + case RawType::I32: + new_val.write_u32( 0, static_cast(Ops::do_bitwise(v_l.read_u32(0), v_r.read_u32(0), re.op)) ); + break; + case RawType::U16: + case RawType::I16: + new_val.write_u16( 0, static_cast(Ops::do_bitwise(v_l.read_u16(0), v_r.read_u16(0), re.op)) ); + break; + case RawType::U8: + case RawType::I8: + new_val.write_u8 ( 0, static_cast(Ops::do_bitwise(v_l.read_u8 (0), v_r.read_u8 (0), re.op)) ); + break; + case RawType::USize: + case RawType::ISize: + new_val.write_usize( 0, Ops::do_bitwise(v_l.read_usize(0), v_r.read_usize(0), re.op) ); + break; + default: + LOG_TODO("BinOp bitwise - " << se.src << " w/ " << ty_l); + } + + break; + default: + LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); + auto val_l = PrimitiveValueVirt::from_value(ty_l, v_l); + auto val_r = PrimitiveValueVirt::from_value(ty_r, v_r); + switch(re.op) + { + case ::MIR::eBinOp::ADD: val_l.get().add( val_r.get() ); break; + case ::MIR::eBinOp::SUB: val_l.get().subtract( val_r.get() ); break; + case ::MIR::eBinOp::MUL: val_l.get().multiply( val_r.get() ); break; + case ::MIR::eBinOp::DIV: val_l.get().divide( val_r.get() ); break; + case ::MIR::eBinOp::MOD: val_l.get().modulo( val_r.get() ); break; + + default: + LOG_TODO("Unsupported binary operator?"); + } + new_val = Value(ty_l); + val_l.get().write_to_value(new_val, 0); + break; + } + } break; + TU_ARM(se.src, UniOp, re) { + ::HIR::TypeRef ty; + auto v = state.get_value_and_type(re.val, ty); + LOG_ASSERT(ty.wrappers.empty(), "UniOp on wrapped type - " << ty); + new_val = Value(ty); + switch(re.op) + { + case ::MIR::eUniOp::INV: + switch(ty.inner_type) + { + case RawType::U128: + case RawType::I128: + LOG_TODO("UniOp::INV U128"); + case RawType::U64: + case RawType::I64: + new_val.write_u64( 0, ~v.read_u64(0) ); + break; + case RawType::U32: + case RawType::I32: + new_val.write_u32( 0, ~v.read_u32(0) ); + break; + case RawType::U16: + case RawType::I16: + new_val.write_u16( 0, ~v.read_u16(0) ); + break; + case RawType::U8: + case RawType::I8: + new_val.write_u8 ( 0, ~v.read_u8 (0) ); + break; + case RawType::USize: + case RawType::ISize: + new_val.write_usize( 0, ~v.read_usize(0) ); + break; + case RawType::Bool: + new_val.write_u8 ( 0, v.read_u8 (0) == 0 ); + break; + default: + LOG_TODO("UniOp::INV - w/ type " << ty); + } + break; + case ::MIR::eUniOp::NEG: + switch(ty.inner_type) + { + case RawType::I128: + LOG_TODO("UniOp::NEG I128"); + case RawType::I64: + new_val.write_i64( 0, -v.read_i64(0) ); + break; + case RawType::I32: + new_val.write_i32( 0, -v.read_i32(0) ); + break; + case RawType::I16: + new_val.write_i16( 0, -v.read_i16(0) ); + break; + case RawType::I8: + new_val.write_i8 ( 0, -v.read_i8 (0) ); + break; + case RawType::ISize: + new_val.write_isize( 0, -v.read_isize(0) ); + break; + default: + LOG_ERROR("UniOp::INV not valid on type " << ty); + } + break; + } + } break; + TU_ARM(se.src, DstMeta, re) { + auto ptr = state.get_value_ref(re.val); + + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = ptr.read_value(POINTER_SIZE, dst_ty.get_size()); + } break; + TU_ARM(se.src, DstPtr, re) { + auto ptr = state.get_value_ref(re.val); + + new_val = ptr.read_value(0, POINTER_SIZE); + } break; + TU_ARM(se.src, MakeDst, re) { + // - Get target type, just for some assertions + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + + auto ptr = state.param_to_value(re.ptr_val ); + auto meta = state.param_to_value(re.meta_val); + LOG_DEBUG("ty=" << dst_ty << ", ptr=" << ptr << ", meta=" << meta); + + new_val.write_value(0, ::std::move(ptr)); + new_val.write_value(POINTER_SIZE, ::std::move(meta)); + } break; + TU_ARM(se.src, Tuple, re) { + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + + for(size_t i = 0; i < re.vals.size(); i++) + { + auto fld_ofs = dst_ty.composite_type->fields.at(i).first; + new_val.write_value(fld_ofs, state.param_to_value(re.vals[i])); + } + } break; + TU_ARM(se.src, Array, re) { + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + // TODO: Assert that type is an array + auto inner_ty = dst_ty.get_inner(); + size_t stride = inner_ty.get_size(); + + size_t ofs = 0; + for(const auto& v : re.vals) + { + new_val.write_value(ofs, state.param_to_value(v)); + ofs += stride; + } + } break; + TU_ARM(se.src, SizedArray, re) { + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + // TODO: Assert that type is an array + auto inner_ty = dst_ty.get_inner(); + size_t stride = inner_ty.get_size(); + + size_t ofs = 0; + for(size_t i = 0; i < re.count; i++) + { + new_val.write_value(ofs, state.param_to_value(re.val)); + ofs += stride; + } + } break; + TU_ARM(se.src, Variant, re) { + // 1. Get the composite by path. + const auto& data_ty = this->m_modtree.get_composite(re.path); + auto dst_ty = ::HIR::TypeRef(&data_ty); + new_val = Value(dst_ty); + LOG_DEBUG("Variant " << new_val); + // Three cases: + // - Unions (no tag) + // - Data enums (tag and data) + // - Value enums (no data) + const auto& var = data_ty.variants.at(re.index); + if( var.data_field != SIZE_MAX ) + { + const auto& fld = data_ty.fields.at(re.index); + + new_val.write_value(fld.first, state.param_to_value(re.val)); + } + LOG_DEBUG("Variant " << new_val); + if( var.base_field != SIZE_MAX ) + { + ::HIR::TypeRef tag_ty; + size_t tag_ofs = dst_ty.get_field_ofs(var.base_field, var.field_path, tag_ty); + LOG_ASSERT(tag_ty.get_size() == var.tag_data.size(), ""); + new_val.write_bytes(tag_ofs, var.tag_data.data(), var.tag_data.size()); + } + else + { + // Union, no tag + } + LOG_DEBUG("Variant " << new_val); + } break; + TU_ARM(se.src, Struct, re) { + const auto& data_ty = m_modtree.get_composite(re.path); + + ::HIR::TypeRef dst_ty; + state.get_value_and_type(se.dst, dst_ty); + new_val = Value(dst_ty); + LOG_ASSERT(dst_ty.composite_type == &data_ty, "Destination type of RValue::Struct isn't the same as the input"); + + for(size_t i = 0; i < re.vals.size(); i++) + { + auto fld_ofs = data_ty.fields.at(i).first; + new_val.write_value(fld_ofs, state.param_to_value(re.vals[i])); + } + } break; + } + LOG_DEBUG("- " << new_val); + state.write_lvalue(se.dst, ::std::move(new_val)); + } break; + case ::MIR::Statement::TAG_Asm: + LOG_TODO(stmt); + break; + TU_ARM(stmt, Drop, se) { + if( se.flag_idx == ~0u || cur_frame.drop_flags.at(se.flag_idx) ) + { + ::HIR::TypeRef ty; + auto v = state.get_value_and_type(se.slot, ty); + + // - Take a pointer to the inner + auto alloc = v.m_alloc; + if( !alloc ) + { + if( !v.m_value->allocation ) + { + v.m_value->create_allocation(); + } + alloc = RelocationPtr::new_alloc( v.m_value->allocation ); + } + size_t ofs = v.m_offset; + assert(ty.get_meta_type() == RawType::Unreachable); + + auto ptr_ty = ty.wrap(TypeWrapper::Ty::Borrow, 2); + + auto ptr_val = Value(ptr_ty); + ptr_val.write_usize(0, ofs); + ptr_val.allocation->relocations.push_back(Relocation { 0, ::std::move(alloc) }); + + if( !drop_value(ptr_val, ty, /*shallow=*/se.kind == ::MIR::eDropKind::SHALLOW) ) + { + return false; + } + } + } break; + TU_ARM(stmt, SetDropFlag, se) { + bool val = (se.other == ~0u ? false : cur_frame.drop_flags.at(se.other)) != se.new_val; + LOG_DEBUG("- " << val); + cur_frame.drop_flags.at(se.idx) = val; + } break; + case ::MIR::Statement::TAG_ScopeEnd: + LOG_TODO(stmt); + break; + } + + cur_frame.stmt_idx += 1; + } + else + { + LOG_DEBUG("=== BB" << cur_frame.bb_idx << "/TERM: " << bb.terminator); + switch(bb.terminator.tag()) + { + case ::MIR::Terminator::TAGDEAD: throw ""; + TU_ARM(bb.terminator, Incomplete, _te) + LOG_TODO("Terminator::Incomplete hit"); + TU_ARM(bb.terminator, Diverge, _te) + LOG_TODO("Terminator::Diverge hit"); + TU_ARM(bb.terminator, Panic, _te) + LOG_TODO("Terminator::Panic"); + TU_ARM(bb.terminator, Goto, te) + cur_frame.bb_idx = te; + break; + TU_ARM(bb.terminator, Return, _te) + LOG_DEBUG("RETURN " << cur_frame.ret); + return this->pop_stack(out_thread_result); + TU_ARM(bb.terminator, If, te) { + uint8_t v = state.get_value_ref(te.cond).read_u8(0); + LOG_ASSERT(v == 0 || v == 1, ""); + cur_frame.bb_idx = v ? te.bb0 : te.bb1; + } break; + TU_ARM(bb.terminator, Switch, te) { + ::HIR::TypeRef ty; + auto v = state.get_value_and_type(te.val, ty); + LOG_ASSERT(ty.wrappers.size() == 0, "" << ty); + LOG_ASSERT(ty.inner_type == RawType::Composite, "" << ty); + + // TODO: Convert the variant list into something that makes it easier to switch on. + size_t found_target = SIZE_MAX; + size_t default_target = SIZE_MAX; + for(size_t i = 0; i < ty.composite_type->variants.size(); i ++) + { + const auto& var = ty.composite_type->variants[i]; + if( var.tag_data.size() == 0 ) + { + // Save as the default, error for multiple defaults + if( default_target != SIZE_MAX ) + { + LOG_FATAL("Two variants with no tag in Switch - " << ty); + } + default_target = i; + } + else + { + // Get offset, read the value. + ::HIR::TypeRef tag_ty; + size_t tag_ofs = ty.get_field_ofs(var.base_field, var.field_path, tag_ty); + // Read the value bytes + ::std::vector tmp( var.tag_data.size() ); + v.read_bytes(tag_ofs, const_cast(tmp.data()), tmp.size()); + if( v.get_relocation(tag_ofs) ) + continue ; + if( ::std::memcmp(tmp.data(), var.tag_data.data(), tmp.size()) == 0 ) + { + found_target = i; + break ; + } + } + } + + if( found_target == SIZE_MAX ) + { + found_target = default_target; + } + if( found_target == SIZE_MAX ) + { + LOG_FATAL("Terminator::Switch on " << ty << " didn't find a variant"); + } + cur_frame.bb_idx = te.targets.at(found_target); + } break; + TU_ARM(bb.terminator, SwitchValue, _te) + LOG_TODO("Terminator::SwitchValue"); + TU_ARM(bb.terminator, Call, te) { + ::std::vector sub_args; sub_args.reserve(te.args.size()); + for(const auto& a : te.args) + { + sub_args.push_back( state.param_to_value(a) ); + LOG_DEBUG("#" << (sub_args.size() - 1) << " " << sub_args.back()); + } + Value rv; + if( te.fcn.is_Intrinsic() ) + { + const auto& fe = te.fcn.as_Intrinsic(); + if( !this->call_intrinsic(rv, fe.name, fe.params, ::std::move(sub_args)) ) + { + // Early return, don't want to update stmt_idx yet + return false; + } + } + else + { + RelocationPtr fcn_alloc_ptr; + const ::HIR::Path* fcn_p; + if( te.fcn.is_Path() ) { + fcn_p = &te.fcn.as_Path(); + } + else { + ::HIR::TypeRef ty; + auto v = state.get_value_and_type(te.fcn.as_Value(), ty); + LOG_DEBUG("> Indirect call " << v); + // TODO: Assert type + // TODO: Assert offset/content. + assert(v.read_usize(0) == 0); + fcn_alloc_ptr = v.get_relocation(v.m_offset); + if( !fcn_alloc_ptr ) + LOG_FATAL("Calling value with no relocation - " << v); + LOG_ASSERT(fcn_alloc_ptr.get_ty() == RelocationPtr::Ty::Function, "Calling value that isn't a function pointer"); + fcn_p = &fcn_alloc_ptr.fcn(); + } + + LOG_DEBUG("Call " << *fcn_p); + if( !this->call_path(rv, *fcn_p, ::std::move(sub_args)) ) + { + // Early return, don't want to update stmt_idx yet + return false; + } + } + LOG_DEBUG(te.ret_val << " = " << rv << " (resume " << cur_frame.fcn.my_path << ")"); + state.write_lvalue(te.ret_val, rv); + cur_frame.bb_idx = te.ret_block; + } break; + } + cur_frame.stmt_idx = 0; + } + + return false; +} +bool InterpreterThread::pop_stack(Value& out_thread_result) +{ + assert( !this->m_stack.empty() ); + + auto res_v = ::std::move(this->m_stack.back().ret); + this->m_stack.pop_back(); + + if( this->m_stack.empty() ) + { + LOG_DEBUG("Thread complete, result " << res_v); + out_thread_result = ::std::move(res_v); + return true; + } + else + { + // Handle callback wrappers (e.g. for __rust_maybe_catch_panic) + if( this->m_stack.back().cb ) + { + if( !this->m_stack.back().cb(res_v, ::std::move(res_v)) ) + { + return false; + } + this->m_stack.pop_back(); + assert( !this->m_stack.empty() ); + assert( !this->m_stack.back().cb ); + } + + auto& cur_frame = this->m_stack.back(); + MirHelpers state { *this, cur_frame }; + + const auto& blk = cur_frame.fcn.m_mir.blocks.at( cur_frame.bb_idx ); + if( cur_frame.stmt_idx < blk.statements.size() ) + { + assert( blk.statements[cur_frame.stmt_idx].is_Drop() ); + cur_frame.stmt_idx ++; + LOG_DEBUG("DROP complete (resume " << cur_frame.fcn.my_path << ")"); + } + else + { + assert( blk.terminator.is_Call() ); + const auto& te = blk.terminator.as_Call(); + + LOG_DEBUG(te.ret_val << " = " << res_v << " (resume " << cur_frame.fcn.my_path << ")"); + + state.write_lvalue(te.ret_val, res_v); + cur_frame.stmt_idx = 0; + cur_frame.bb_idx = te.ret_block; + } + + return false; + } +} + +InterpreterThread::StackFrame::StackFrame(const Function& fcn, ::std::vector args): + fcn(fcn), + ret( fcn.ret_ty ), + args( ::std::move(args) ), + locals( ), + drop_flags( fcn.m_mir.drop_flags ), + bb_idx(0), + stmt_idx(0) +{ + this->locals.reserve( fcn.m_mir.locals.size() ); + for(const auto& ty : fcn.m_mir.locals) + { + if( ty == RawType::Unreachable ) { + // HACK: Locals can be !, but they can NEVER be accessed + this->locals.push_back( Value() ); + } + else { + this->locals.push_back( Value(ty) ); + } + } +} +bool InterpreterThread::call_path(Value& ret, const ::HIR::Path& path, ::std::vector args) +{ + // TODO: Support overriding certain functions + { + if( path == ::HIR::SimplePath { "std", { "sys", "imp", "c", "SetThreadStackGuarantee" } } ) + { + ret = Value(::HIR::TypeRef{RawType::I32}); + ret.write_i32(0, 120); // ERROR_CALL_NOT_IMPLEMENTED + return true; + } + + // - No guard page needed + if( path == ::HIR::SimplePath { "std", {"sys", "imp", "thread", "guard", "init" } } ) + { + ret = Value::with_size(16, false); + ret.write_u64(0, 0); + ret.write_u64(8, 0); + return true; + } + + // - No stack overflow handling needed + if( path == ::HIR::SimplePath { "std", { "sys", "imp", "stack_overflow", "imp", "init" } } ) + { + return true; + } + } + + const auto& fcn = m_modtree.get_function(path); + + if( fcn.external.link_name != "" ) + { + // External function! + return this->call_extern(ret, fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); + } + + this->m_stack.push_back(StackFrame(fcn, ::std::move(args))); + return false; +} + +extern "C" { + long sysconf(int); + ssize_t write(int, const void*, size_t); +} +bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, const ::std::string& abi, ::std::vector args) +{ + if( link_name == "__rust_allocate" ) + { + auto size = args.at(0).read_usize(0); + auto align = args.at(1).read_usize(0); + LOG_DEBUG("__rust_allocate(size=" << size << ", align=" << align << ")"); + ::HIR::TypeRef rty { RawType::Unit }; + rty.wrappers.push_back({ TypeWrapper::Ty::Pointer, 0 }); + + rv = Value(rty); + rv.write_usize(0, 0); + // TODO: Use the alignment when making an allocation? + rv.allocation->relocations.push_back({ 0, RelocationPtr::new_alloc(Allocation::new_alloc(size)) }); + } + else if( link_name == "__rust_reallocate" ) + { + LOG_ASSERT(args.at(0).allocation, "__rust_reallocate first argument doesn't have an allocation"); + auto alloc_ptr = args.at(0).get_relocation(0); + auto ptr_ofs = args.at(0).read_usize(0); + LOG_ASSERT(ptr_ofs == 0, "__rust_reallocate with offset pointer"); + auto oldsize = args.at(1).read_usize(0); + auto newsize = args.at(2).read_usize(0); + auto align = args.at(3).read_usize(0); + LOG_DEBUG("__rust_reallocate(ptr=" << alloc_ptr << ", oldsize=" << oldsize << ", newsize=" << newsize << ", align=" << align << ")"); + + LOG_ASSERT(alloc_ptr, "__rust_reallocate with no backing allocation attached to pointer"); + LOG_ASSERT(alloc_ptr.is_alloc(), "__rust_reallocate with no backing allocation attached to pointer"); + auto& alloc = alloc_ptr.alloc(); + // TODO: Check old size and alignment against allocation. + alloc.data.resize( (newsize + 8-1) / 8 ); + alloc.mask.resize( (newsize + 8-1) / 8 ); + // TODO: Should this instead make a new allocation to catch use-after-free? + rv = ::std::move(args.at(0)); + } + else if( link_name == "__rust_deallocate" ) + { + LOG_ASSERT(args.at(0).allocation, "__rust_deallocate first argument doesn't have an allocation"); + auto alloc_ptr = args.at(0).get_relocation(0); + auto ptr_ofs = args.at(0).read_usize(0); + LOG_ASSERT(ptr_ofs == 0, "__rust_deallocate with offset pointer"); + LOG_DEBUG("__rust_deallocate(ptr=" << alloc_ptr << ")"); + + LOG_ASSERT(alloc_ptr, "__rust_deallocate with no backing allocation attached to pointer"); + LOG_ASSERT(alloc_ptr.is_alloc(), "__rust_deallocate with no backing allocation attached to pointer"); + auto& alloc = alloc_ptr.alloc(); + alloc.mark_as_freed(); + // Just let it drop. + rv = Value(); + } + else if( link_name == "__rust_maybe_catch_panic" ) + { + auto fcn_path = args.at(0).get_relocation(0).fcn(); + auto arg = args.at(1); + auto data_ptr = args.at(2).read_pointer_valref_mut(0, POINTER_SIZE); + auto vtable_ptr = args.at(3).read_pointer_valref_mut(0, POINTER_SIZE); + + ::std::vector sub_args; + sub_args.push_back( ::std::move(arg) ); + + this->m_stack.push_back(StackFrame::make_wrapper([=](Value& out_rv, Value /*rv*/)->bool{ + out_rv = Value(::HIR::TypeRef(RawType::U32)); + out_rv.write_u32(0, 0); + return true; + })); + + // TODO: Catch the panic out of this. + if( this->call_path(rv, fcn_path, ::std::move(sub_args)) ) + { + bool v = this->pop_stack(rv); + assert( v == false ); + return true; + } + else + { + return false; + } + } + else if( link_name == "__rust_start_panic" ) + { + LOG_TODO("__rust_start_panic"); + } + else if( link_name == "rust_begin_unwind" ) + { + LOG_TODO("rust_begin_unwind"); + } +#ifdef _WIN32 + // WinAPI functions used by libstd + else if( link_name == "AddVectoredExceptionHandler" ) + { + LOG_DEBUG("Call `AddVectoredExceptionHandler` - Ignoring and returning non-null"); + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, 1); + } + else if( link_name == "GetModuleHandleW" ) + { + LOG_ASSERT(args.at(0).allocation.is_alloc(), ""); + const auto& tgt_alloc = args.at(0).allocation.alloc().get_relocation(0); + const void* arg0 = (tgt_alloc ? tgt_alloc.alloc().data_ptr() : nullptr); + //extern void* GetModuleHandleW(const void* s); + if(arg0) { + LOG_DEBUG("GetModuleHandleW(" << tgt_alloc.alloc() << ")"); + } + else { + LOG_DEBUG("GetModuleHandleW(NULL)"); + } + + auto ret = GetModuleHandleW(static_cast(arg0)); + if(ret) + { + rv = Value::new_ffiptr(FFIPointer { "GetModuleHandleW", ret }); + } + else + { + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.create_allocation(); + rv.write_usize(0,0); + } + } + else if( link_name == "GetProcAddress" ) + { + LOG_ASSERT(args.at(0).allocation.is_alloc(), ""); + const auto& handle_alloc = args.at(0).allocation.alloc().get_relocation(0); + LOG_ASSERT(args.at(1).allocation.is_alloc(), ""); + const auto& sym_alloc = args.at(1).allocation.alloc().get_relocation(0); + + // TODO: Ensure that first arg is a FFI pointer with offset+size of zero + void* handle = handle_alloc.ffi().ptr_value; + // TODO: Get either a FFI data pointer, or a inner data pointer + const void* symname = sym_alloc.alloc().data_ptr(); + // TODO: Sanity check that it's a valid c string within its allocation + LOG_DEBUG("FFI GetProcAddress(" << handle << ", \"" << static_cast(symname) << "\")"); + + auto ret = GetProcAddress(static_cast(handle), static_cast(symname)); + + if( ret ) + { + rv = Value::new_ffiptr(FFIPointer { "GetProcAddress", ret }); + } + else + { + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.create_allocation(); + rv.write_usize(0,0); + } + } +#else + // POSIX + else if( link_name == "write" ) + { + auto fd = args.at(0).read_i32(0); + auto count = args.at(2).read_isize(0); + const auto* buf = args.at(1).read_pointer_const(0, count); + + ssize_t val = write(fd, buf, count); + + rv = Value(::HIR::TypeRef(RawType::ISize)); + rv.write_isize(0, val); + } + else if( link_name == "sysconf" ) + { + auto name = args.at(0).read_i32(0); + LOG_DEBUG("FFI sysconf(" << name << ")"); + + long val = sysconf(name); + + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, val); + } + else if( link_name == "pthread_mutex_init" || link_name == "pthread_mutex_lock" || link_name == "pthread_mutex_unlock" || link_name == "pthread_mutex_destroy" ) + { + rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + } + else if( link_name == "pthread_rwlock_rdlock" ) + { + rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + } + else if( link_name == "pthread_mutexattr_init" || link_name == "pthread_mutexattr_settype" || link_name == "pthread_mutexattr_destroy" ) + { + rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + } + else if( link_name == "pthread_condattr_init" || link_name == "pthread_condattr_destroy" || link_name == "pthread_condattr_setclock" ) + { + rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + } + else if( link_name == "pthread_cond_init" || link_name == "pthread_cond_destroy" ) + { + rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + } + else if( link_name == "pthread_key_create" ) + { + auto key_ref = args.at(0).read_pointer_valref_mut(0, 4); + + auto key = ThreadState::s_next_tls_key ++; + key_ref.m_alloc.alloc().write_u32( key_ref.m_offset, key ); + + rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + } + else if( link_name == "pthread_getspecific" ) + { + auto key = args.at(0).read_u32(0); + + // Get a pointer-sized value from storage + uint64_t v = key < m_thread.tls_values.size() ? m_thread.tls_values[key] : 0; + + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, v); + } + else if( link_name == "pthread_setspecific" ) + { + auto key = args.at(0).read_u32(0); + auto v = args.at(1).read_u64(0); + + // Get a pointer-sized value from storage + if( key >= m_thread.tls_values.size() ) { + m_thread.tls_values.resize(key+1); + } + m_thread.tls_values[key] = v; + + rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + } + else if( link_name == "pthread_key_delete" ) + { + rv = Value(::HIR::TypeRef(RawType::I32)); + rv.write_i32(0, 0); + } +#endif + // std C + else if( link_name == "signal" ) + { + LOG_DEBUG("Call `signal` - Ignoring and returning SIG_IGN"); + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, 1); + } + // - `void *memchr(const void *s, int c, size_t n);` + else if( link_name == "memchr" ) + { + auto ptr_alloc = args.at(0).get_relocation(0); + auto c = args.at(1).read_i32(0); + auto n = args.at(2).read_usize(0); + const void* ptr = args.at(0).read_pointer_const(0, n); + + const void* ret = memchr(ptr, c, n); + + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.create_allocation(); + if( ret ) + { + rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast(ret) - static_cast(ptr) )); + rv.allocation->relocations.push_back({ 0, ptr_alloc }); + } + else + { + rv.write_usize(0, 0); + } + } + else if( link_name == "memrchr" ) + { + auto ptr_alloc = args.at(0).get_relocation(0); + auto c = args.at(1).read_i32(0); + auto n = args.at(2).read_usize(0); + const void* ptr = args.at(0).read_pointer_const(0, n); + + const void* ret = memrchr(ptr, c, n); + + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.create_allocation(); + if( ret ) + { + rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast(ret) - static_cast(ptr) )); + rv.allocation->relocations.push_back({ 0, ptr_alloc }); + } + else + { + rv.write_usize(0, 0); + } + } + // Allocators! + else + { + LOG_TODO("Call external function " << link_name); + } + return true; +} + +bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, const ::HIR::PathParams& ty_params, ::std::vector args) +{ + TRACE_FUNCTION_R(name, rv); + for(const auto& a : args) + LOG_DEBUG("#" << (&a - args.data()) << ": " << a); + if( name == "type_id" ) + { + const auto& ty_T = ty_params.tys.at(0); + static ::std::vector type_ids; + auto it = ::std::find(type_ids.begin(), type_ids.end(), ty_T); + if( it == type_ids.end() ) + { + it = type_ids.insert(it, ty_T); + } + + rv = Value::with_size(POINTER_SIZE, false); + rv.write_usize(0, it - type_ids.begin()); + } + else if( name == "atomic_fence" || name == "atomic_fence_acq" ) + { + rv = Value(); + } + else if( name == "atomic_store" ) + { + auto& ptr_val = args.at(0); + auto& data_val = args.at(1); + + LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_store of a value that isn't a pointer-sized value"); + + // There MUST be a relocation at this point with a valid allocation. + auto alloc = ptr_val.get_relocation(0); + LOG_ASSERT(alloc, "Deref of a value with no relocation"); + + // TODO: Atomic side of this? + size_t ofs = ptr_val.read_usize(0); + alloc.alloc().write_value(ofs, ::std::move(data_val)); + } + else if( name == "atomic_load" || name == "atomic_load_relaxed" ) + { + auto& ptr_val = args.at(0); + LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_store of a value that isn't a pointer-sized value"); + + // There MUST be a relocation at this point with a valid allocation. + auto alloc = ptr_val.get_relocation(0); + LOG_ASSERT(alloc, "Deref of a value with no relocation"); + // TODO: Atomic lock the allocation. + + size_t ofs = ptr_val.read_usize(0); + const auto& ty = ty_params.tys.at(0); + + rv = alloc.alloc().read_value(ofs, ty.get_size()); + } + else if( name == "atomic_xadd" || name == "atomic_xadd_relaxed" ) + { + const auto& ty_T = ty_params.tys.at(0); + auto ptr_ofs = args.at(0).read_usize(0); + auto ptr_alloc = args.at(0).get_relocation(0); + auto v = args.at(1).read_value(0, ty_T.get_size()); + + // TODO: Atomic lock the allocation. + if( !ptr_alloc || !ptr_alloc.is_alloc() ) { + LOG_ERROR("atomic pointer has no allocation"); + } + + // - Result is the original value + rv = ptr_alloc.alloc().read_value(ptr_ofs, ty_T.get_size()); + + auto val_l = PrimitiveValueVirt::from_value(ty_T, rv); + const auto val_r = PrimitiveValueVirt::from_value(ty_T, v); + val_l.get().add( val_r.get() ); + + val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs ); + } + else if( name == "atomic_xsub" || name == "atomic_xsub_relaxed" || name == "atomic_xsub_rel" ) + { + const auto& ty_T = ty_params.tys.at(0); + auto ptr_ofs = args.at(0).read_usize(0); + auto ptr_alloc = args.at(0).get_relocation(0); + auto v = args.at(1).read_value(0, ty_T.get_size()); + + // TODO: Atomic lock the allocation. + if( !ptr_alloc || !ptr_alloc.is_alloc() ) { + LOG_ERROR("atomic pointer has no allocation"); + } + + // - Result is the original value + rv = ptr_alloc.alloc().read_value(ptr_ofs, ty_T.get_size()); + + auto val_l = PrimitiveValueVirt::from_value(ty_T, rv); + const auto val_r = PrimitiveValueVirt::from_value(ty_T, v); + val_l.get().subtract( val_r.get() ); + + val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs ); + } + else if( name == "atomic_xchg" ) + { + const auto& ty_T = ty_params.tys.at(0); + auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size()); + const auto& new_v = args.at(1); + + rv = data_ref.read_value(0, new_v.size()); + data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v ); + } + else if( name == "atomic_cxchg" ) + { + const auto& ty_T = ty_params.tys.at(0); + // TODO: Get a ValueRef to the target location + auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size()); + const auto& old_v = args.at(1); + const auto& new_v = args.at(2); + rv = Value::with_size( ty_T.get_size() + 1, false ); + rv.write_value(0, data_ref.read_value(0, old_v.size())); + LOG_DEBUG("> *ptr = " << data_ref); + if( data_ref.compare(old_v.data_ptr(), old_v.size()) == true ) { + data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v ); + rv.write_u8( old_v.size(), 1 ); + } + else { + rv.write_u8( old_v.size(), 0 ); + } + } + else if( name == "transmute" ) + { + // Transmute requires the same size, so just copying the value works + rv = ::std::move(args.at(0)); + } + else if( name == "assume" ) + { + // Assume is a no-op which returns unit + } + else if( name == "offset" ) + { + auto ptr_alloc = args.at(0).get_relocation(0); + auto ptr_ofs = args.at(0).read_usize(0); + auto& ofs_val = args.at(1); + + auto delta_counts = ofs_val.read_usize(0); + auto new_ofs = ptr_ofs + delta_counts * ty_params.tys.at(0).get_size(); + if(POINTER_SIZE != 8) { + new_ofs &= 0xFFFFFFFF; + } + + rv = ::std::move(args.at(0)); + rv.write_usize(0, new_ofs); + if( ptr_alloc ) { + rv.allocation->relocations.push_back({ 0, ptr_alloc }); + } + } + // effectively ptr::write + else if( name == "move_val_init" ) + { + auto& ptr_val = args.at(0); + auto& data_val = args.at(1); + + LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "move_val_init of an address that isn't a pointer-sized value"); + + // There MUST be a relocation at this point with a valid allocation. + LOG_ASSERT(ptr_val.allocation, "Deref of a value with no allocation (hence no relocations)"); + LOG_TRACE("Deref " << ptr_val << " and store " << data_val); + + auto ptr_alloc = ptr_val.get_relocation(0); + LOG_ASSERT(ptr_alloc, "Deref of a value with no relocation"); + + size_t ofs = ptr_val.read_usize(0); + ptr_alloc.alloc().write_value(ofs, ::std::move(data_val)); + LOG_DEBUG(ptr_alloc.alloc()); + } + else if( name == "uninit" ) + { + rv = Value(ty_params.tys.at(0)); + } + else if( name == "init" ) + { + rv = Value(ty_params.tys.at(0)); + rv.mark_bytes_valid(0, rv.size()); + } + // - Unsized stuff + else if( name == "size_of_val" ) + { + auto& val = args.at(0); + const auto& ty = ty_params.tys.at(0); + rv = Value(::HIR::TypeRef(RawType::USize)); + // Get unsized type somehow. + // - _HAS_ to be the last type, so that makes it easier + size_t fixed_size = 0; + if( const auto* ity = ty.get_usized_type(fixed_size) ) + { + const auto meta_ty = ty.get_meta_type(); + LOG_DEBUG("size_of_val - " << ty << " ity=" << *ity << " meta_ty=" << meta_ty << " fixed_size=" << fixed_size); + size_t flex_size = 0; + if( !ity->wrappers.empty() ) + { + LOG_ASSERT(ity->wrappers[0].type == TypeWrapper::Ty::Slice, ""); + size_t item_size = ity->get_inner().get_size(); + size_t item_count = val.read_usize(POINTER_SIZE); + flex_size = item_count * item_size; + LOG_DEBUG("> item_size=" << item_size << " item_count=" << item_count << " flex_size=" << flex_size); + } + else if( ity->inner_type == RawType::Str ) + { + flex_size = val.read_usize(POINTER_SIZE); + } + else if( ity->inner_type == RawType::TraitObject ) + { + LOG_TODO("size_of_val - Trait Object - " << ty); + } + else + { + LOG_BUG("Inner unsized type unknown - " << *ity); + } + + rv.write_usize(0, fixed_size + flex_size); + } + else + { + rv.write_usize(0, ty.get_size()); + } + } + else if( name == "drop_in_place" ) + { + auto& val = args.at(0); + const auto& ty = ty_params.tys.at(0); + if( !ty.wrappers.empty() ) + { + size_t item_count = 0; + switch(ty.wrappers[0].type) + { + case TypeWrapper::Ty::Slice: + case TypeWrapper::Ty::Array: + item_count = (ty.wrappers[0].type == TypeWrapper::Ty::Slice ? val.read_usize(POINTER_SIZE) : ty.wrappers[0].size); + break; + case TypeWrapper::Ty::Pointer: + break; + case TypeWrapper::Ty::Borrow: + // TODO: Only &move has a destructor + break; + } + LOG_ASSERT(ty.wrappers[0].type == TypeWrapper::Ty::Slice, "drop_in_place should only exist for slices - " << ty); + const auto& ity = ty.get_inner(); + size_t item_size = ity.get_size(); + + auto ptr = val.read_value(0, POINTER_SIZE); + for(size_t i = 0; i < item_count; i ++) + { + // TODO: Nested calls? + if( !drop_value(ptr, ity) ) + { + LOG_DEBUG("Handle multiple queued calls"); + } + ptr.write_usize(0, ptr.read_usize(0) + item_size); + } + } + else + { + return drop_value(val, ty); + } + } + // ---------------------------------------------------------------- + // Checked arithmatic + else if( name == "add_with_overflow" ) + { + const auto& ty = ty_params.tys.at(0); + + auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0)); + auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1)); + bool didnt_overflow = lhs.get().add( rhs.get() ); + + // Get return type - a tuple of `(T, bool,)` + ::HIR::GenericPath gp; + gp.m_params.tys.push_back(ty); + gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); + const auto& dty = m_modtree.get_composite(gp); + + rv = Value(::HIR::TypeRef(&dty)); + lhs.get().write_to_value(rv, dty.fields[0].first); + rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened + } + else if( name == "sub_with_overflow" ) + { + const auto& ty = ty_params.tys.at(0); + + auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0)); + auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1)); + bool didnt_overflow = lhs.get().subtract( rhs.get() ); + + // Get return type - a tuple of `(T, bool,)` + ::HIR::GenericPath gp; + gp.m_params.tys.push_back(ty); + gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); + const auto& dty = m_modtree.get_composite(gp); + + rv = Value(::HIR::TypeRef(&dty)); + lhs.get().write_to_value(rv, dty.fields[0].first); + rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened + } + else if( name == "mul_with_overflow" ) + { + const auto& ty = ty_params.tys.at(0); + + auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0)); + auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1)); + bool didnt_overflow = lhs.get().multiply( rhs.get() ); + + // Get return type - a tuple of `(T, bool,)` + ::HIR::GenericPath gp; + gp.m_params.tys.push_back(ty); + gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool }); + const auto& dty = m_modtree.get_composite(gp); + + rv = Value(::HIR::TypeRef(&dty)); + lhs.get().write_to_value(rv, dty.fields[0].first); + rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened + } + // Overflowing artithmatic + else if( name == "overflowing_sub" ) + { + const auto& ty = ty_params.tys.at(0); + + auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0)); + auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1)); + lhs.get().subtract( rhs.get() ); + + rv = Value(ty); + lhs.get().write_to_value(rv, 0); + } + // ---------------------------------------------------------------- + // memcpy + else if( name == "copy_nonoverlapping" ) + { + auto src_ofs = args.at(0).read_usize(0); + auto src_alloc = args.at(0).get_relocation(0); + auto dst_ofs = args.at(1).read_usize(0); + auto dst_alloc = args.at(1).get_relocation(0); + size_t ent_count = args.at(2).read_usize(0); + size_t ent_size = ty_params.tys.at(0).get_size(); + auto byte_count = ent_count * ent_size; + + LOG_ASSERT(src_alloc, "Source of copy* must have an allocation"); + LOG_ASSERT(dst_alloc, "Destination of copy* must be a memory allocation"); + LOG_ASSERT(dst_alloc.is_alloc(), "Destination of copy* must be a memory allocation"); + + switch(src_alloc.get_ty()) + { + case RelocationPtr::Ty::Allocation: { + auto v = src_alloc.alloc().read_value(src_ofs, byte_count); + LOG_DEBUG("v = " << v); + dst_alloc.alloc().write_value(dst_ofs, ::std::move(v)); + } break; + case RelocationPtr::Ty::StdString: + LOG_ASSERT(src_ofs <= src_alloc.str().size(), ""); + LOG_ASSERT(byte_count <= src_alloc.str().size(), ""); + LOG_ASSERT(src_ofs + byte_count <= src_alloc.str().size(), ""); + dst_alloc.alloc().write_bytes(dst_ofs, src_alloc.str().data() + src_ofs, byte_count); + break; + case RelocationPtr::Ty::Function: + LOG_FATAL("Attempt to copy* a function"); + break; + case RelocationPtr::Ty::FfiPointer: + LOG_BUG("Trying to copy from a FFI pointer"); + break; + } + } + else + { + LOG_TODO("Call intrinsic \"" << name << "\""); + } + return true; +} + +bool InterpreterThread::drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_shallow/*=false*/) +{ + if( is_shallow ) + { + // HACK: Only works for Box where the first pointer is the data pointer + auto box_ptr_vr = ptr.read_pointer_valref_mut(0, POINTER_SIZE); + auto ofs = box_ptr_vr.read_usize(0); + auto alloc = box_ptr_vr.get_relocation(0); + if( ofs != 0 || !alloc || !alloc.is_alloc() ) { + LOG_ERROR("Attempting to shallow drop with invalid pointer (no relocation or non-zero offset) - " << box_ptr_vr); + } + + LOG_DEBUG("drop_value SHALLOW deallocate " << alloc); + alloc.alloc().mark_as_freed(); + return true; + } + if( ty.wrappers.empty() ) + { + if( ty.inner_type == RawType::Composite ) + { + if( ty.composite_type->drop_glue != ::HIR::Path() ) + { + LOG_DEBUG("Drop - " << ty); + + Value tmp; + return this->call_path(tmp, ty.composite_type->drop_glue, { ptr }); + } + else + { + // No drop glue + } + } + else if( ty.inner_type == RawType::TraitObject ) + { + LOG_TODO("Drop - " << ty << " - trait object"); + } + else + { + // No destructor + } + } + else + { + switch( ty.wrappers[0].type ) + { + case TypeWrapper::Ty::Borrow: + if( ty.wrappers[0].size == static_cast(::HIR::BorrowType::Move) ) + { + LOG_TODO("Drop - " << ty << " - dereference and go to inner"); + // TODO: Clear validity on the entire inner value. + } + else + { + // No destructor + } + break; + case TypeWrapper::Ty::Pointer: + // No destructor + break; + // TODO: Arrays + default: + LOG_TODO("Drop - " << ty << " - array?"); + break; + } + } + return true; +} diff --git a/tools/standalone_miri/miri.hpp b/tools/standalone_miri/miri.hpp new file mode 100644 index 00000000..09d92a9b --- /dev/null +++ b/tools/standalone_miri/miri.hpp @@ -0,0 +1,79 @@ + +#pragma once +#include "module_tree.hpp" +#include "value.hpp" + +struct ThreadState +{ + static unsigned s_next_tls_key; + unsigned call_stack_depth; + ::std::vector tls_values; + + ThreadState(): + call_stack_depth(0) + { + } + + struct DecOnDrop { + unsigned* p; + ~DecOnDrop() { (*p) --; } + }; + DecOnDrop enter_function() { + this->call_stack_depth ++; + return DecOnDrop { &this->call_stack_depth }; + } +}; + +class InterpreterThread +{ + friend struct MirHelpers; + struct StackFrame + { + ::std::function cb; + const Function& fcn; + Value ret; + ::std::vector args; + ::std::vector locals; + ::std::vector drop_flags; + + unsigned bb_idx; + unsigned stmt_idx; + + StackFrame(const Function& fcn, ::std::vector args); + static StackFrame make_wrapper(::std::function cb) { + static Function f; + StackFrame rv(f, {}); + rv.cb = ::std::move(cb); + return rv; + } + }; + + ModuleTree& m_modtree; + ThreadState m_thread; + ::std::vector m_stack; + +public: + InterpreterThread(ModuleTree& modtree): + m_modtree(modtree) + { + } + ~InterpreterThread(); + + void start(const ::HIR::Path& p, ::std::vector args); + // Returns `true` if the call stack empties + bool step_one(Value& out_thread_result); + +private: + bool pop_stack(Value& out_thread_result); + + // Returns true if the call was resolved instantly + bool call_path(Value& ret_val, const ::HIR::Path& p, ::std::vector args); + // Returns true if the call was resolved instantly + bool call_extern(Value& ret_val, const ::std::string& name, const ::std::string& abi, ::std::vector args); + // Returns true if the call was resolved instantly + bool call_intrinsic(Value& ret_val, const ::std::string& name, const ::HIR::PathParams& pp, ::std::vector args); + + // Returns true if the call was resolved instantly + bool drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_shallow=false); +}; + -- cgit v1.2.3 From 1320ff65f1fcce3cbd492eaf6f300ac81e2f8ae3 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Fri, 18 May 2018 19:37:01 +0800 Subject: Standalone MIRI - Range limit on FFI pointers --- tools/standalone_miri/miri.cpp | 4 ++-- tools/standalone_miri/value.hpp | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/miri.cpp b/tools/standalone_miri/miri.cpp index a4390e66..f7e47a6b 100644 --- a/tools/standalone_miri/miri.cpp +++ b/tools/standalone_miri/miri.cpp @@ -1682,7 +1682,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c auto ret = GetModuleHandleW(static_cast(arg0)); if(ret) { - rv = Value::new_ffiptr(FFIPointer { "GetModuleHandleW", ret }); + rv = Value::new_ffiptr(FFIPointer { "GetModuleHandleW", ret, 0 }); } else { @@ -1709,7 +1709,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c if( ret ) { - rv = Value::new_ffiptr(FFIPointer { "GetProcAddress", ret }); + rv = Value::new_ffiptr(FFIPointer { "GetProcAddress", ret, 0 }); } else { diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index 4da2eee6..7219f1f7 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -21,6 +21,7 @@ struct FFIPointer { const char* source_function; void* ptr_value; + size_t size; }; class AllocationHandle -- cgit v1.2.3 From aada4f2fe9be2f9bfadb4ef6ba057f36b9860aa8 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 19 May 2018 08:09:14 +0800 Subject: Standalone MIRI - Pass argv to the target --- tools/standalone_miri/main.cpp | 46 +++++++++++++++++++++++++++++++++++++++-- tools/standalone_miri/miri.cpp | 23 ++++++++++++++++++++- tools/standalone_miri/value.cpp | 13 +++++++----- tools/standalone_miri/value.hpp | 5 +++++ 4 files changed, 79 insertions(+), 8 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 2011edfa..1755a9d7 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -14,10 +14,15 @@ struct ProgramOptions { ::std::string infile; //TODO: Architecture file + //::std::string archname; //TODO: Loadable FFI descriptions + //::std::vector ffi_api_files; //TODO: Logfile + //::std::string logfile; + ::std::vector args; int parse(int argc, const char* argv[]); + void show_help(const char* prog) const; }; int main(int argc, const char* argv[]) @@ -38,8 +43,19 @@ int main(int argc, const char* argv[]) argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); auto val_argv = Value(argv_ty); - val_argc.write_isize(0, 0); + + // Create argc/argv based on input arguments + val_argc.write_isize(0, 1 + opts.args.size()); + auto argv_alloc = Allocation::new_alloc((1 + opts.args.size()) * POINTER_SIZE); + argv_alloc->write_usize(0 * POINTER_SIZE, 0); + argv_alloc->relocations.push_back({ 0 * POINTER_SIZE, RelocationPtr::new_ffi(FFIPointer { "", (void*)(opts.infile.c_str()), opts.infile.size() + 1 }) }); + for(size_t i = 0; i < opts.args.size(); i ++) + { + argv_alloc->write_usize((1 + i) * POINTER_SIZE, 0); + argv_alloc->relocations.push_back({ (1 + i) * POINTER_SIZE, RelocationPtr::new_ffi({ "", (void*)(opts.args[0]), ::std::strlen(opts.args[0]) + 1 }) }); + } val_argv.write_usize(0, 0); + val_argv.allocation->relocations.push_back({ 0 * POINTER_SIZE, RelocationPtr::new_alloc(argv_alloc) }); try { @@ -85,16 +101,37 @@ int ProgramOptions::parse(int argc, const char* argv[]) } else { - // TODO: Too many free arguments + this->args.push_back(arg); } } else if( arg[1] != '-' ) { // Short + if( arg[2] != '\0' ) { + // Error? + } + switch(arg[1]) + { + case 'h': + this->show_help(argv[0]); + exit(0); + default: + // TODO: Error + break; + } } else if( arg[2] != '\0' ) { // Long + if( ::std::strcmp(arg, "--help") == 0 ) { + this->show_help(argv[0]); + exit(0); + } + //else if( ::std::strcmp(arg, "--api") == 0 ) { + //} + else { + // TODO: Error + } } else { @@ -103,3 +140,8 @@ int ProgramOptions::parse(int argc, const char* argv[]) } return 0; } + +void ProgramOptions::show_help(const char* prog) const +{ + ::std::cout << "USAGE: " << prog << " <... args>" << ::std::endl; +} diff --git a/tools/standalone_miri/miri.cpp b/tools/standalone_miri/miri.cpp index f7e47a6b..eccc54c9 100644 --- a/tools/standalone_miri/miri.cpp +++ b/tools/standalone_miri/miri.cpp @@ -1856,6 +1856,24 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c rv.write_usize(0, 0); } } + else if( link_name == "strlen" ) + { + // strlen - custom implementation to ensure validity + bool _is_mut; + size_t size; + const char* ptr = reinterpret_cast( args.at(0).read_pointer_unsafe(0, 1, size, _is_mut) ); + size_t len = 0; + while(size -- && *ptr) + { + ptr ++; + len ++; + } + args.at(0).read_pointer_const(0, len + 1); + + //rv = Value::new_usize(len); + rv = Value(::HIR::TypeRef(RawType::USize)); + rv.write_usize(0, len); + } // Allocators! else { @@ -2222,7 +2240,10 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con LOG_FATAL("Attempt to copy* a function"); break; case RelocationPtr::Ty::FfiPointer: - LOG_BUG("Trying to copy from a FFI pointer"); + LOG_ASSERT(src_ofs <= src_alloc.ffi().size, ""); + LOG_ASSERT(byte_count <= src_alloc.ffi().size, ""); + LOG_ASSERT(src_ofs + byte_count <= src_alloc.ffi().size, ""); + dst_alloc.alloc().write_bytes(dst_ofs, src_alloc.ffi().ptr_value + src_ofs, byte_count); break; } } diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index d8eeee01..e9376ce6 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -227,13 +227,16 @@ void* ValueCommonRead::read_pointer_unsafe(size_t rd_ofs, size_t req_valid, size } case RelocationPtr::Ty::Function: LOG_FATAL("read_pointer w/ function"); - case RelocationPtr::Ty::FfiPointer: - if( req_valid ) - LOG_FATAL("Can't request valid data from a FFI pointer"); + case RelocationPtr::Ty::FfiPointer: { + const auto& f = reloc.ffi(); + // TODO: Validity? + //if( req_valid ) + // LOG_FATAL("Can't request valid data from a FFI pointer"); // TODO: Have an idea of mutability and available size from FFI - out_size = 0; + out_size = f.size - ofs; out_is_mut = false; - return reloc.ffi().ptr_value /* + ofs */; + return reloc.ffi().ptr_value + ofs; + } } throw ""; } diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index 7219f1f7..4528b98f 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -315,6 +315,11 @@ struct ValueRef: assert(size <= m_alloc.str().size()); assert(ofs+size <= m_alloc.str().size()); break; + case RelocationPtr::Ty::FfiPointer: + assert(ofs < m_alloc.ffi().size); + assert(size <= m_alloc.ffi().size); + assert(ofs+size <= m_alloc.ffi().size); + break; default: throw "TODO"; } -- cgit v1.2.3 From ae177706bf0b4b2ff05e9102d1403c73799756b0 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 19 May 2018 10:15:20 +0800 Subject: Standalone MIRI - Better logging (can redirect to a file, leaving stdout for the program) --- test_smiri.sh | 2 +- tools/standalone_miri/debug.cpp | 34 +++++++++---- tools/standalone_miri/debug.hpp | 14 +++-- tools/standalone_miri/main.cpp | 61 +++++++++++++++++----- tools/standalone_miri/miri.cpp | 10 ++-- tools/standalone_miri/module_tree.cpp | 96 ++++++++++++++--------------------- tools/standalone_miri/value.cpp | 10 ++-- tools/standalone_miri/value.hpp | 15 ++++-- 8 files changed, 148 insertions(+), 94 deletions(-) (limited to 'tools') diff --git a/test_smiri.sh b/test_smiri.sh index 63c94fa2..5a7de4e4 100755 --- a/test_smiri.sh +++ b/test_smiri.sh @@ -3,4 +3,4 @@ set -e cd $(dirname $0) make -f minicargo.mk MMIR=1 LIBS ./bin/mrustc rustc-1.19.0-src/src/test/run-pass/hello.rs -O -C codegen-type=monomir -o output-mmir/hello -L output-mmir/ > output-mmir/hello_dbg.txt -./tools/bin/standalone_miri output-mmir/hello.mir +./tools/bin/standalone_miri output-mmir/hello.mir --logfile smiri_hello.log diff --git a/tools/standalone_miri/debug.cpp b/tools/standalone_miri/debug.cpp index 415bc5d5..f0476df7 100644 --- a/tools/standalone_miri/debug.cpp +++ b/tools/standalone_miri/debug.cpp @@ -1,6 +1,15 @@ +/* + * mrustc Standalone MIRI + * - by John Hodge (Mutabah) + * + * debug.cpp + * - Interpreter debug logging + */ #include "debug.hpp" +#include unsigned DebugSink::s_indent = 0; +::std::unique_ptr DebugSink::s_out_file; DebugSink::DebugSink(::std::ostream& inner): m_inner(inner) @@ -10,39 +19,44 @@ DebugSink::~DebugSink() { m_inner << "\n"; } +bool DebugSink::set_output_file(const ::std::string& s) +{ + s_out_file.reset(new ::std::ofstream(s)); +} bool DebugSink::enabled(const char* fcn_name) { return true; } DebugSink DebugSink::get(const char* fcn_name, const char* file, unsigned line, DebugLevel lvl) { + auto& sink = s_out_file ? *s_out_file : ::std::cout; for(size_t i = s_indent; i--;) - ::std::cout << " "; + sink << " "; switch(lvl) { case DebugLevel::Trace: - ::std::cout << "Trace: " << file << ":" << line << ": "; + sink << "Trace: " << file << ":" << line << ": "; break; case DebugLevel::Debug: - ::std::cout << "DEBUG: " << fcn_name << ": "; + sink << "DEBUG: " << fcn_name << ": "; break; case DebugLevel::Notice: - ::std::cout << "NOTE: "; + sink << "NOTE: "; break; case DebugLevel::Warn: - ::std::cout << "WARN: "; + sink << "WARN: "; break; case DebugLevel::Error: - ::std::cout << "ERROR: "; + sink << "ERROR: "; break; case DebugLevel::Fatal: - ::std::cout << "FATAL: "; + sink << "FATAL: "; break; case DebugLevel::Bug: - ::std::cout << "BUG: " << file << ":" << line << ": "; + sink << "BUG: " << file << ":" << line << ": "; break; } - return DebugSink(::std::cout); + return DebugSink(sink); } void DebugSink::inc_indent() { @@ -51,4 +65,4 @@ void DebugSink::inc_indent() void DebugSink::dec_indent() { s_indent --; -} \ No newline at end of file +} diff --git a/tools/standalone_miri/debug.hpp b/tools/standalone_miri/debug.hpp index f7d32fe5..6b136ccb 100644 --- a/tools/standalone_miri/debug.hpp +++ b/tools/standalone_miri/debug.hpp @@ -1,10 +1,15 @@ -// -// -// +/* + * mrustc Standalone MIRI + * - by John Hodge (Mutabah) + * + * debug.hpp + * - Interpreter debug logging + */ #pragma once #include #include +#include enum class DebugLevel { Trace, @@ -19,6 +24,7 @@ enum class DebugLevel { class DebugSink { static unsigned s_indent; + static ::std::unique_ptr s_out_file; ::std::ostream& m_inner; DebugSink(::std::ostream& inner); public: @@ -27,6 +33,7 @@ public: template ::std::ostream& operator<<(const T& v) { return m_inner << v; } + static bool set_output_file(const ::std::string& s); static bool enabled(const char* fcn_name); static DebugSink get(const char* fcn_name, const char* file, unsigned line, DebugLevel lvl); // TODO: Add a way to insert an annotation before/after an abort/warning/... that indicates what input location caused it. @@ -90,6 +97,7 @@ struct DebugExceptionError: #define TRACE_FUNCTION_R(entry, exit) auto ftg##__LINE__ = FunctionTrace_d(__FUNCTION__,__FILE__,__LINE__,[&](DebugSink& FunctionTrace_ss){FunctionTrace_ss << entry;}, [&](DebugSink& FunctionTrace_ss) {FunctionTrace_ss << exit;} ) #define LOG_TRACE(strm) do { if(DebugSink::enabled(__FUNCTION__)) DebugSink::get(__FUNCTION__,__FILE__,__LINE__,DebugLevel::Trace) << strm; } while(0) #define LOG_DEBUG(strm) do { if(DebugSink::enabled(__FUNCTION__)) DebugSink::get(__FUNCTION__,__FILE__,__LINE__,DebugLevel::Debug) << strm; } while(0) +#define LOG_NOTICE(strm) do { DebugSink::get(__FUNCTION__,__FILE__,__LINE__,DebugLevel::Notice) << strm; } while(0) #define LOG_ERROR(strm) do { DebugSink::get(__FUNCTION__,__FILE__,__LINE__,DebugLevel::Error) << strm; throw DebugExceptionError{}; } while(0) #define LOG_FATAL(strm) do { DebugSink::get(__FUNCTION__,__FILE__,__LINE__,DebugLevel::Fatal) << strm; exit(1); } while(0) #define LOG_TODO(strm) do { DebugSink::get(__FUNCTION__,__FILE__,__LINE__,DebugLevel::Bug) << "TODO: " << strm; throw DebugExceptionTodo{}; } while(0) diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 1755a9d7..c214676a 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -1,6 +1,10 @@ -// -// -// +/* + * mrustc Standalone MIRI + * - by John Hodge (Mutabah) + * + * main.cpp + * - Program entrypoint + */ #include #include "module_tree.hpp" #include "value.hpp" @@ -17,8 +21,10 @@ struct ProgramOptions //::std::string archname; //TODO: Loadable FFI descriptions //::std::vector ffi_api_files; - //TODO: Logfile - //::std::string logfile; + + // Output logfile + ::std::string logfile; + // Arguments for the program ::std::vector args; int parse(int argc, const char* argv[]); @@ -34,10 +40,17 @@ int main(int argc, const char* argv[]) return 1; } - auto tree = ModuleTree {}; + // Configure logging + if( opts.logfile != "" ) + { + DebugSink::set_output_file(opts.logfile); + } + // Load HIR tree + auto tree = ModuleTree {}; tree.load_file(opts.infile); + // Construct argc/argv values auto val_argc = Value( ::HIR::TypeRef{RawType::ISize} ); ::HIR::TypeRef argv_ty { RawType::I8 }; argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); @@ -54,9 +67,11 @@ int main(int argc, const char* argv[]) argv_alloc->write_usize((1 + i) * POINTER_SIZE, 0); argv_alloc->relocations.push_back({ (1 + i) * POINTER_SIZE, RelocationPtr::new_ffi({ "", (void*)(opts.args[0]), ::std::strlen(opts.args[0]) + 1 }) }); } + //val_argv.write_ptr(0, 0, RelocationPtr::new_alloc(argv_alloc)); val_argv.write_usize(0, 0); val_argv.allocation->relocations.push_back({ 0 * POINTER_SIZE, RelocationPtr::new_alloc(argv_alloc) }); + // Catch various exceptions from the interpreter try { InterpreterThread root_thread(tree); @@ -70,16 +85,24 @@ int main(int argc, const char* argv[]) { } - ::std::cout << rv << ::std::endl; + LOG_NOTICE("Return code: " << rv); } catch(const DebugExceptionTodo& /*e*/) { ::std::cerr << "TODO Hit" << ::std::endl; + if(opts.logfile != "") + { + ::std::cerr << "- See '" << opts.logfile << "' for details" << ::std::endl; + } return 1; } catch(const DebugExceptionError& /*e*/) { ::std::cerr << "Error encountered" << ::std::endl; + if(opts.logfile != "") + { + ::std::cerr << "- See '" << opts.logfile << "' for details" << ::std::endl; + } return 1; } @@ -89,26 +112,31 @@ int main(int argc, const char* argv[]) int ProgramOptions::parse(int argc, const char* argv[]) { bool all_free = false; + // TODO: use getopt? POSIX only for(int argidx = 1; argidx < argc; argidx ++) { const char* arg = argv[argidx]; if( arg[0] != '-' || all_free ) { - // Free + // Free arguments + // - First is the input file if( this->infile == "" ) { this->infile = arg; } else { + // Any subsequent arguments are passed to the taget this->args.push_back(arg); } } else if( arg[1] != '-' ) { - // Short + // Short arguments if( arg[2] != '\0' ) { // Error? + ::std::cerr << "Unexpected option " << arg << ::std::endl; + return 1; } switch(arg[1]) { @@ -116,8 +144,8 @@ int ProgramOptions::parse(int argc, const char* argv[]) this->show_help(argv[0]); exit(0); default: - // TODO: Error - break; + ::std::cerr << "Unexpected option -" << arg[1] << ::std::endl; + return 1; } } else if( arg[2] != '\0' ) @@ -127,10 +155,19 @@ int ProgramOptions::parse(int argc, const char* argv[]) this->show_help(argv[0]); exit(0); } + else if( ::std::strcmp(arg, "--logfile") == 0 ) { + if( argidx + 1 == argc ) { + ::std::cerr << "Option " << arg << " requires an argument" << ::std::endl; + return 1; + } + const char* opt = argv[++argidx]; + this->logfile = opt; + } //else if( ::std::strcmp(arg, "--api") == 0 ) { //} else { - // TODO: Error + ::std::cerr << "Unexpected option " << arg << ::std::endl; + return 1; } } else diff --git a/tools/standalone_miri/miri.cpp b/tools/standalone_miri/miri.cpp index eccc54c9..733aa8a3 100644 --- a/tools/standalone_miri/miri.cpp +++ b/tools/standalone_miri/miri.cpp @@ -1,6 +1,10 @@ -// -// -// +/* + * mrustc Standalone MIRI + * - by John Hodge (Mutabah) + * + * miri.cpp + * - Interpreter core + */ #include #include "module_tree.hpp" #include "value.hpp" diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index 6a7a0b5f..cb6f943d 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -40,12 +40,11 @@ void ModuleTree::load_file(const ::std::string& path) { if( !loaded_files.insert(path).second ) { - ::std::cout << "DEBUG: load_file(" << path << ") - Already loaded" << ::std::endl; + LOG_DEBUG("load_file(" << path << ") - Already loaded"); return ; } - ::std::cout << "DEBUG: load_file(" << path << ")" << ::std::endl; - //TRACE_FUNCTION_F(path); + TRACE_FUNCTION_R(path, ""); auto parse = Parser { *this, path }; while(parse.parse_one()) @@ -56,7 +55,7 @@ void ModuleTree::load_file(const ::std::string& path) // Parse a single item from a .mir file bool Parser::parse_one() { - //::std::cout << "DEBUG: parse_one" << ::std::endl; + //TRACE_FUNCTION_F(""); if( lex.next() == "" ) // EOF? { return false; @@ -68,7 +67,7 @@ bool Parser::parse_one() lex.check(TokenClass::String); auto path = ::std::move(lex.next().strval); lex.consume(); - //::std::cout << "DEBUG: parse_one - crate '" << path << "'" << ::std::endl; + //LOG_TRACE(lex << "crate '" << path << "'"); lex.check_consume(';'); @@ -78,7 +77,7 @@ bool Parser::parse_one() else if( lex.consume_if("fn") ) { auto p = parse_path(); - //::std::cout << "DEBUG: parse_one - fn " << p << ::std::endl; + //LOG_TRACE(lex << "fn " << p); lex.check_consume('('); ::std::vector<::HIR::TypeRef> arg_tys; @@ -94,7 +93,7 @@ bool Parser::parse_one() { rv_ty = parse_type(); } - + if( lex.consume_if('=') ) { auto link_name = ::std::move(lex.check_consume(TokenClass::String).strval); @@ -102,7 +101,7 @@ bool Parser::parse_one() auto abi = ::std::move(lex.check_consume(TokenClass::String).strval); lex.check_consume(';'); - LOG_DEBUG("fn " << p); + LOG_DEBUG(lex << "extern fn " << p); auto p2 = p; tree.functions.insert( ::std::make_pair(::std::move(p), Function { ::std::move(p2), ::std::move(arg_tys), rv_ty, {link_name, abi}, {} }) ); } @@ -110,7 +109,7 @@ bool Parser::parse_one() { auto body = parse_body(); - LOG_DEBUG("fn " << p); + LOG_DEBUG(lex << "fn " << p); auto p2 = p; tree.functions.insert( ::std::make_pair(::std::move(p), Function { ::std::move(p2), ::std::move(arg_tys), rv_ty, {}, ::std::move(body) }) ); } @@ -118,7 +117,7 @@ bool Parser::parse_one() else if( lex.consume_if("static") ) { auto p = parse_path(); - //::std::cout << "DEBUG: parse_one - static " << p << ::std::endl; + //LOG_TRACE(lex << "static " << p); lex.check_consume(':'); auto ty = parse_type(); // TODO: externs? @@ -152,12 +151,12 @@ bool Parser::parse_one() auto a = Allocation::new_alloc( reloc_str.size() ); //a.alloc().set_tag(); a->write_bytes(0, reloc_str.data(), reloc_str.size()); - s.val.allocation->relocations.push_back({ ofs, RelocationPtr::new_alloc(::std::move(a)) }); + s.val.allocation->relocations.push_back({ ofs, /*size,*/ RelocationPtr::new_alloc(::std::move(a)) }); } else if( lex.next() == "::" || lex.next() == "<" ) { auto reloc_path = parse_path(); - s.val.allocation->relocations.push_back({ ofs, RelocationPtr::new_fcn(reloc_path) }); + s.val.allocation->relocations.push_back({ ofs, /*size,*/ RelocationPtr::new_fcn(reloc_path) }); } else { @@ -172,13 +171,13 @@ bool Parser::parse_one() } lex.check_consume(';'); - LOG_DEBUG("static " << p); + LOG_DEBUG(lex << "static " << p); tree.statics.insert(::std::make_pair( ::std::move(p), ::std::move(s) )); } else if( lex.consume_if("type") ) { auto p = (lex.consume_if('(')) ? parse_tuple() : parse_genericpath(); - //::std::cout << "DEBUG: parse_one - type " << p << ::std::endl; + //LOG_TRACE("type " << p); auto rv = DataType {}; rv.my_path = p; @@ -223,7 +222,7 @@ bool Parser::parse_one() lex.check_consume('='); auto ty = parse_type(); lex.check_consume(';'); - //::std::cout << ofs << " " << ty << ::std::endl; + //LOG_DEBUG(ofs << " " << ty); rv.fields.push_back(::std::make_pair(ofs, ::std::move(ty))); } @@ -289,11 +288,10 @@ bool Parser::parse_one() if( rv.alignment == 0 && rv.fields.size() != 0 ) { - ::std::cerr << lex << "Alignment of zero with fields is invalid, " << p << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Alignment of zero with fields is invalid, " << p); } - LOG_DEBUG("type " << p); + LOG_DEBUG(lex << "type " << p); auto it = this->tree.data_types.find(p); if( it != this->tree.data_types.end() ) { @@ -303,10 +301,7 @@ bool Parser::parse_one() } else { - //::std::cerr << lex << "Duplicate definition of " << p << ::std::endl; - - // Not really an error, can happen when loading crates - //throw "ERROR"; + //LOG_ERROR(lex << "Duplicate definition of " << p); } } else @@ -316,7 +311,7 @@ bool Parser::parse_one() } else { - ::std::cerr << lex << "Unexpected token at root - " << lex.next() << ::std::endl; + LOG_ERROR(lex << "Unexpected token at root - " << lex.next()); // Unknown item type throw "ERROR"; @@ -360,8 +355,7 @@ bool Parser::parse_one() lv = ::MIR::LValue::make_Argument({ idx }); } catch(const ::std::exception& e) { - ::std::cerr << lex << "Invalid argument name - " << name << " - " << e.what() << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Invalid argument name - " << name << " - " << e.what()); } } // Hard-coded "RETURN" lvalue @@ -372,8 +366,7 @@ bool Parser::parse_one() else { auto it = ::std::find(var_names.begin(), var_names.end(), name); if( it == var_names.end() ) { - ::std::cerr << lex << "Cannot find variable named '" << name << "'" << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Cannot find variable named '" << name << "'"); } lv = ::MIR::LValue::make_Local(static_cast(it - var_names.begin())); } @@ -384,8 +377,7 @@ bool Parser::parse_one() lv = ::MIR::LValue( ::std::move(path) ); } else { - ::std::cerr << lex << "Unexpected token in LValue - " << lex.next() << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unexpected token in LValue - " << lex.next()); } for(;;) { @@ -455,8 +447,7 @@ bool Parser::parse_one() } else { - ::std::cerr << p.lex << "Expected an integer or float, got " << p.lex.next() << ::std::endl; - throw "ERROR"; + LOG_ERROR(p.lex << "Expected an integer or float, got " << p.lex.next()); } } else if( p.lex.consume_if("true") ) { @@ -471,8 +462,7 @@ bool Parser::parse_one() return ::MIR::Constant::make_ItemAddr({ ::std::move(path) }); } else { - ::std::cerr << p.lex << "BUG? " << p.lex.next() << ::std::endl; - throw "ERROR"; + LOG_BUG(p.lex << "BUG? " << p.lex.next()); } } @@ -653,8 +643,7 @@ bool Parser::parse_one() op = ::MIR::eUniOp::NEG; } else { - ::std::cerr << lex << "Unexpected token in uniop - " << lex.next() << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unexpected token in uniop - " << lex.next()); } auto lv = H::parse_lvalue(*this, var_names); @@ -701,8 +690,7 @@ bool Parser::parse_one() lex.check_consume('='); break; default: - ::std::cerr << lex << "Unexpected token " << t << " in BINOP" << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unexpected token " << t << " in BINOP"); } auto lv2 = H::parse_param(*this, var_names); @@ -723,8 +711,7 @@ bool Parser::parse_one() src_rval = ::MIR::RValue::make_DstMeta({ ::std::move(lv) }); } else { - ::std::cerr << lex << "Unexpected token in RValue - " << lex.next() << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unexpected token in RValue - " << lex.next()); } stmts.push_back(::MIR::Statement::make_Assign({ ::std::move(dst_val), ::std::move(src_rval) })); @@ -735,8 +722,7 @@ bool Parser::parse_one() auto name = ::std::move(lex.consume().strval); auto df_it = ::std::find(drop_flag_names.begin(), drop_flag_names.end(), name); if( df_it == drop_flag_names.end() ) { - ::std::cerr << lex << "Unable to find drop flag '" << name << "'" << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unable to find drop flag '" << name << "'"); } auto df_idx = static_cast( df_it - drop_flag_names.begin() ); lex.check_consume('='); @@ -754,8 +740,7 @@ bool Parser::parse_one() auto name = ::std::move(lex.consume().strval); df_it = ::std::find(drop_flag_names.begin(), drop_flag_names.end(), name); if( df_it == drop_flag_names.end() ) { - ::std::cerr << lex << "Unable to find drop flag '" << name << "'" << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unable to find drop flag '" << name << "'"); } auto other_idx = static_cast( df_it - drop_flag_names.begin() ); @@ -777,8 +762,7 @@ bool Parser::parse_one() auto name = ::std::move(lex.consume().strval); auto df_it = ::std::find(drop_flag_names.begin(), drop_flag_names.end(), name); if( df_it == drop_flag_names.end() ) { - ::std::cerr << lex << "Unable to find drop flag '" << name << "'" << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unable to find drop flag '" << name << "'"); } flag_idx = static_cast( df_it - drop_flag_names.begin() ); } @@ -842,7 +826,7 @@ bool Parser::parse_one() break; } lex.check_consume(';'); - //::std::cout << stmts.back() << ::std::endl; + //LOG_TRACE(stmts.back()); } lex.check(TokenClass::Ident); @@ -928,8 +912,7 @@ bool Parser::parse_one() vals = ::MIR::SwitchValues::make_String(::std::move(values)); } else { - ::std::cerr << lex << "Unexpected token for SWITCHVALUE value - " << lex.next() << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unexpected token for SWITCHVALUE value - " << lex.next()); } lex.check_consume('_'); lex.check_consume('='); @@ -976,8 +959,7 @@ bool Parser::parse_one() } else { - ::std::cerr << lex << "Unexpected token at terminator - " << lex.next() << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unexpected token at terminator - " << lex.next()); } lex.check_consume('}'); @@ -1068,7 +1050,7 @@ bool Parser::parse_one() } RawType Parser::parse_core_type() { - //::std::cout << lex.next() << ::std::endl; + //LOG_TRACE(lex.next()); lex.check(TokenClass::Ident); auto tok = lex.consume(); // Primitive type. @@ -1124,8 +1106,7 @@ RawType Parser::parse_core_type() return RawType::Str; } else { - ::std::cerr << lex << "Unknown core type " << tok << "'" << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unknown core type " << tok << "'"); } } ::HIR::TypeRef Parser::parse_type() @@ -1285,8 +1266,7 @@ RawType Parser::parse_core_type() } else { - ::std::cerr << lex << "Unexpected token in type - " << lex.next() << ::std::endl; - throw "ERROR"; + LOG_ERROR(lex << "Unexpected token in type - " << lex.next()); } } const DataType* Parser::get_composite(::HIR::GenericPath gp) @@ -1312,8 +1292,7 @@ const Function& ModuleTree::get_function(const ::HIR::Path& p) const auto it = functions.find(p); if(it == functions.end()) { - ::std::cerr << "Unable to find function " << p << " for invoke" << ::std::endl; - throw ""; + LOG_ERROR("Unable to find function " << p << " for invoke"); } return it->second; } @@ -1331,8 +1310,7 @@ Static& ModuleTree::get_static(const ::HIR::Path& p) auto it = statics.find(p); if(it == statics.end()) { - ::std::cerr << "Unable to find static " << p << " for invoke" << ::std::endl; - throw ""; + LOG_ERROR("Unable to find static " << p << " for invoke"); } return it->second; } diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index e9376ce6..c3db284a 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -1,6 +1,10 @@ -// -// -// +/* + * mrustc Standalone MIRI + * - by John Hodge (Mutabah) + * + * value.cpp + * - Runtime values + */ #include "value.hpp" #include "hir_sim.hpp" #include "module_tree.hpp" diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index 4528b98f..81302e67 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -1,6 +1,10 @@ -// -// -// +/* + * mrustc Standalone MIRI + * - by John Hodge (Mutabah) + * + * value.hpp + * - Runtime values + */ #pragma once #include @@ -257,9 +261,12 @@ struct Value: Value(); Value(::HIR::TypeRef ty); + static Value with_size(size_t size, bool have_allocation); static Value new_fnptr(const ::HIR::Path& fn_path); static Value new_ffiptr(FFIPointer ffi); + //static Value new_usize(uint64_t v); + //static Value new_isize(int64_t v); void create_allocation(); size_t size() const { return allocation ? allocation->size() : direct_data.size; } @@ -281,6 +288,8 @@ struct Value: void write_value(size_t ofs, Value v); void write_bytes(size_t ofs, const void* src, size_t count) override; + + //void write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc); }; extern ::std::ostream& operator<<(::std::ostream& os, const Value& v); -- cgit v1.2.3 From a96b446e80f109138e2a639ec94222017af0b9b1 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 19 May 2018 12:29:44 +0800 Subject: Standalone MIRI - Use some more helpers --- test_smiri.sh | 4 +- tools/standalone_miri/hir_sim.cpp | 14 +++-- tools/standalone_miri/hir_sim.hpp | 7 ++- tools/standalone_miri/main.cpp | 18 +++---- tools/standalone_miri/miri.cpp | 104 +++++++++++++++----------------------- tools/standalone_miri/value.cpp | 41 +++++++++++++++ tools/standalone_miri/value.hpp | 14 +++-- 7 files changed, 117 insertions(+), 85 deletions(-) (limited to 'tools') diff --git a/test_smiri.sh b/test_smiri.sh index 5a7de4e4..0dbad3fa 100755 --- a/test_smiri.sh +++ b/test_smiri.sh @@ -2,5 +2,7 @@ set -e cd $(dirname $0) make -f minicargo.mk MMIR=1 LIBS +echo "--- mrustc -o output-mmir/hello" ./bin/mrustc rustc-1.19.0-src/src/test/run-pass/hello.rs -O -C codegen-type=monomir -o output-mmir/hello -L output-mmir/ > output-mmir/hello_dbg.txt -./tools/bin/standalone_miri output-mmir/hello.mir --logfile smiri_hello.log +echo "--- standalone_miri output-mmir/hello.mir" +time ./tools/bin/standalone_miri output-mmir/hello.mir --logfile smiri_hello.log diff --git a/tools/standalone_miri/hir_sim.cpp b/tools/standalone_miri/hir_sim.cpp index f3b4d400..94f0d0e1 100644 --- a/tools/standalone_miri/hir_sim.cpp +++ b/tools/standalone_miri/hir_sim.cpp @@ -20,6 +20,7 @@ size_t HIR::TypeRef::get_size(size_t ofs) const case RawType::Unit: return 0; case RawType::Composite: + // NOTE: Don't care if the type has metadata return this->composite_type->size; case RawType::Unreachable: LOG_BUG("Attempting to get size of an unreachable type, " << *this); @@ -53,7 +54,7 @@ size_t HIR::TypeRef::get_size(size_t ofs) const } throw ""; } - + switch(this->wrappers[ofs].type) { case TypeWrapper::Ty::Array: @@ -100,22 +101,25 @@ size_t HIR::TypeRef::get_size(size_t ofs) const } throw ""; } -bool HIR::TypeRef::has_slice_meta() const +bool HIR::TypeRef::has_slice_meta(size_t& out_inner_size) const { if( this->wrappers.size() == 0 ) { if(this->inner_type == RawType::Composite) { - // TODO: Handle metadata better + // TODO: This type could be wrapping a slice, needs to return the inner type size. + // - Also need to know which field is the unsized one return false; } else { + out_inner_size = 1; return (this->inner_type == RawType::Str); } } else { + out_inner_size = this->get_size(1); return (this->wrappers[0].type == TypeWrapper::Ty::Slice); } } @@ -130,9 +134,9 @@ HIR::TypeRef HIR::TypeRef::get_inner() const ity.wrappers.erase(ity.wrappers.begin()); return ity; } -HIR::TypeRef HIR::TypeRef::wrap(TypeWrapper::Ty ty, size_t size) const +HIR::TypeRef HIR::TypeRef::wrap(TypeWrapper::Ty ty, size_t size)&& { - auto rv = *this; + auto rv = ::std::move(*this); rv.wrappers.insert(rv.wrappers.begin(), { ty, size }); return rv; } diff --git a/tools/standalone_miri/hir_sim.hpp b/tools/standalone_miri/hir_sim.hpp index 1dc9bcc4..9f5ba59c 100644 --- a/tools/standalone_miri/hir_sim.hpp +++ b/tools/standalone_miri/hir_sim.hpp @@ -118,11 +118,14 @@ namespace HIR { } size_t get_size(size_t ofs=0) const; - bool has_slice_meta() const; // The attached metadata is a count + bool has_slice_meta(size_t& out_inner_size) const; // The attached metadata is a count of elements const TypeRef* get_usized_type(size_t& running_inner_size) const; TypeRef get_meta_type() const; TypeRef get_inner() const; - TypeRef wrap(TypeWrapper::Ty ty, size_t size) const; + TypeRef wrap(TypeWrapper::Ty ty, size_t size)&&; + TypeRef wrapped(TypeWrapper::Ty ty, size_t size) const { + return TypeRef(*this).wrap(ty, size); + } TypeRef get_field(size_t idx, size_t& ofs) const; bool operator==(const RawType& x) const { diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index c214676a..e3a8d22e 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -50,15 +50,7 @@ int main(int argc, const char* argv[]) auto tree = ModuleTree {}; tree.load_file(opts.infile); - // Construct argc/argv values - auto val_argc = Value( ::HIR::TypeRef{RawType::ISize} ); - ::HIR::TypeRef argv_ty { RawType::I8 }; - argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); - argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); - auto val_argv = Value(argv_ty); - // Create argc/argv based on input arguments - val_argc.write_isize(0, 1 + opts.args.size()); auto argv_alloc = Allocation::new_alloc((1 + opts.args.size()) * POINTER_SIZE); argv_alloc->write_usize(0 * POINTER_SIZE, 0); argv_alloc->relocations.push_back({ 0 * POINTER_SIZE, RelocationPtr::new_ffi(FFIPointer { "", (void*)(opts.infile.c_str()), opts.infile.size() + 1 }) }); @@ -67,9 +59,13 @@ int main(int argc, const char* argv[]) argv_alloc->write_usize((1 + i) * POINTER_SIZE, 0); argv_alloc->relocations.push_back({ (1 + i) * POINTER_SIZE, RelocationPtr::new_ffi({ "", (void*)(opts.args[0]), ::std::strlen(opts.args[0]) + 1 }) }); } - //val_argv.write_ptr(0, 0, RelocationPtr::new_alloc(argv_alloc)); - val_argv.write_usize(0, 0); - val_argv.allocation->relocations.push_back({ 0 * POINTER_SIZE, RelocationPtr::new_alloc(argv_alloc) }); + + // Construct argc/argv values + auto val_argc = Value::new_isize(1 + opts.args.size()); + ::HIR::TypeRef argv_ty { RawType::I8 }; + argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); + argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); + auto val_argv = Value::new_pointer(argv_ty, 0, RelocationPtr::new_alloc(argv_alloc)); // Catch various exceptions from the interpreter try diff --git a/tools/standalone_miri/miri.cpp b/tools/standalone_miri/miri.cpp index 733aa8a3..c0e7d15c 100644 --- a/tools/standalone_miri/miri.cpp +++ b/tools/standalone_miri/miri.cpp @@ -352,16 +352,18 @@ struct MirHelpers LOG_ASSERT(val.m_size == POINTER_SIZE + meta_size, "Deref of " << ty << ", but pointer isn't correct size"); meta_val = ::std::make_shared( val.read_value(POINTER_SIZE, meta_size) ); - // TODO: Get a more sane size from the metadata - if( alloc ) - { + size_t slice_inner_size; + if( ty.has_slice_meta(slice_inner_size) ) { + size = (ty.wrappers.empty() ? ty.get_size() : 0) + meta_val->read_usize(0) * slice_inner_size; + } + //else if( ty == RawType::TraitObject) { + // // NOTE: Getting the size from the allocation is semi-valid, as you can't sub-slice trait objects + // size = alloc.get_size() - ofs; + //} + else { LOG_DEBUG("> Meta " << *meta_val << ", size = " << alloc.get_size() << " - " << ofs); size = alloc.get_size() - ofs; } - else - { - size = 0; - } } else { @@ -406,6 +408,7 @@ struct MirHelpers } void write_lvalue(const ::MIR::LValue& lv, Value val) { + // TODO: Ensure that target is writable? Or should write_value do that? //LOG_DEBUG(lv << " = " << val); ::HIR::TypeRef ty; auto base_value = get_value_and_type(lv, ty); @@ -428,12 +431,14 @@ struct MirHelpers Value val = Value(ty); val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian // TODO: If the write was clipped, sign-extend + // TODO: i128/u128 need the upper bytes cleared+valid return val; } break; TU_ARM(c, Uint, ce) { ty = ::HIR::TypeRef(ce.t); Value val = Value(ty); val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v))); // TODO: Endian + // TODO: i128/u128 need the upper bytes cleared+valid return val; } break; TU_ARM(c, Bool, ce) { @@ -466,11 +471,9 @@ struct MirHelpers ty = ::HIR::TypeRef(RawType::Str); ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); Value val = Value(ty); - val.write_usize(0, 0); + val.write_ptr(0, 0, RelocationPtr::new_string(&ce)); val.write_usize(POINTER_SIZE, ce.size()); - val.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_string(&ce) }); LOG_DEBUG(c << " = " << val); - //return Value::new_dataptr(ce.data()); return val; } break; // --> Accessor @@ -482,11 +485,8 @@ struct MirHelpers } if( const auto* s = this->thread.m_modtree.get_static_opt(ce) ) { ty = s->ty; - ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); - Value val = Value(ty); - val.write_usize(0, 0); - val.allocation->relocations.push_back(Relocation { 0, RelocationPtr::new_alloc(s->val.allocation) }); - return val; + ty.wrappers.insert(ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); + return Value::new_pointer(ty, 0, RelocationPtr::new_alloc(s->val.allocation)); } LOG_ERROR("Constant::ItemAddr - " << ce << " - not found"); } break; @@ -602,19 +602,17 @@ bool InterpreterThread::step_one(Value& out_thread_result) LOG_DEBUG("- alloc=" << alloc); size_t ofs = src_base_value.m_offset; const auto meta = src_ty.get_meta_type(); - //bool is_slice_like = src_ty.has_slice_meta(); src_ty.wrappers.insert(src_ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, static_cast(re.type) }); + // Create the pointer new_val = Value(src_ty); - // ^ Pointer value - new_val.write_usize(0, ofs); + new_val.write_ptr(0, ofs, ::std::move(alloc)); + // - Add metadata if required if( meta != RawType::Unreachable ) { LOG_ASSERT(src_base_value.m_metadata, "Borrow of an unsized value, but no metadata avaliable"); new_val.write_value(POINTER_SIZE, *src_base_value.m_metadata); } - // - Add the relocation after writing the value (writing clears the relocations) - new_val.allocation->relocations.push_back(Relocation { 0, ::std::move(alloc) }); } break; TU_ARM(se.src, Cast, re) { // Determine the type of cast, is it a reinterpret or is it a value transform? @@ -1306,11 +1304,9 @@ bool InterpreterThread::step_one(Value& out_thread_result) size_t ofs = v.m_offset; assert(ty.get_meta_type() == RawType::Unreachable); - auto ptr_ty = ty.wrap(TypeWrapper::Ty::Borrow, 2); + auto ptr_ty = ty.wrapped(TypeWrapper::Ty::Borrow, 2); - auto ptr_val = Value(ptr_ty); - ptr_val.write_usize(0, ofs); - ptr_val.allocation->relocations.push_back(Relocation { 0, ::std::move(alloc) }); + auto ptr_val = Value::new_pointer(ptr_ty, ofs, ::std::move(alloc)); if( !drop_value(ptr_val, ty, /*shallow=*/se.kind == ::MIR::eDropKind::SHALLOW) ) { @@ -1327,7 +1323,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) LOG_TODO(stmt); break; } - + cur_frame.stmt_idx += 1; } else @@ -1456,7 +1452,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) } cur_frame.stmt_idx = 0; } - + return false; } bool InterpreterThread::pop_stack(Value& out_thread_result) @@ -1465,7 +1461,7 @@ bool InterpreterThread::pop_stack(Value& out_thread_result) auto res_v = ::std::move(this->m_stack.back().ret); this->m_stack.pop_back(); - + if( this->m_stack.empty() ) { LOG_DEBUG("Thread complete, result " << res_v); @@ -1539,8 +1535,7 @@ bool InterpreterThread::call_path(Value& ret, const ::HIR::Path& path, ::std::ve { if( path == ::HIR::SimplePath { "std", { "sys", "imp", "c", "SetThreadStackGuarantee" } } ) { - ret = Value(::HIR::TypeRef{RawType::I32}); - ret.write_i32(0, 120); // ERROR_CALL_NOT_IMPLEMENTED + ret = Value::new_i32(120); //ERROR_CALL_NOT_IMPLEMENTED return true; } @@ -1552,7 +1547,7 @@ bool InterpreterThread::call_path(Value& ret, const ::HIR::Path& path, ::std::ve ret.write_u64(8, 0); return true; } - + // - No stack overflow handling needed if( path == ::HIR::SimplePath { "std", { "sys", "imp", "stack_overflow", "imp", "init" } } ) { @@ -1567,7 +1562,7 @@ bool InterpreterThread::call_path(Value& ret, const ::HIR::Path& path, ::std::ve // External function! return this->call_extern(ret, fcn.external.link_name, fcn.external.link_abi, ::std::move(args)); } - + this->m_stack.push_back(StackFrame(fcn, ::std::move(args))); return false; } @@ -1586,10 +1581,8 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c ::HIR::TypeRef rty { RawType::Unit }; rty.wrappers.push_back({ TypeWrapper::Ty::Pointer, 0 }); - rv = Value(rty); - rv.write_usize(0, 0); // TODO: Use the alignment when making an allocation? - rv.allocation->relocations.push_back({ 0, RelocationPtr::new_alloc(Allocation::new_alloc(size)) }); + rv = Value::new_pointer(rty, 0, RelocationPtr::new_alloc(Allocation::new_alloc(size))); } else if( link_name == "__rust_reallocate" ) { @@ -1632,13 +1625,12 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c auto arg = args.at(1); auto data_ptr = args.at(2).read_pointer_valref_mut(0, POINTER_SIZE); auto vtable_ptr = args.at(3).read_pointer_valref_mut(0, POINTER_SIZE); - + ::std::vector sub_args; sub_args.push_back( ::std::move(arg) ); this->m_stack.push_back(StackFrame::make_wrapper([=](Value& out_rv, Value /*rv*/)->bool{ - out_rv = Value(::HIR::TypeRef(RawType::U32)); - out_rv.write_u32(0, 0); + out_rv = Value::new_u32(0); return true; })); @@ -1667,8 +1659,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c else if( link_name == "AddVectoredExceptionHandler" ) { LOG_DEBUG("Call `AddVectoredExceptionHandler` - Ignoring and returning non-null"); - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.write_usize(0, 1); + rv = Value::new_usize(1); } else if( link_name == "GetModuleHandleW" ) { @@ -1732,8 +1723,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c ssize_t val = write(fd, buf, count); - rv = Value(::HIR::TypeRef(RawType::ISize)); - rv.write_isize(0, val); + rv = Value::new_isize(val); } else if( link_name == "sysconf" ) { @@ -1742,33 +1732,27 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c long val = sysconf(name); - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.write_usize(0, val); + rv = Value::new_usize(val); } else if( link_name == "pthread_mutex_init" || link_name == "pthread_mutex_lock" || link_name == "pthread_mutex_unlock" || link_name == "pthread_mutex_destroy" ) { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); + rv = Value::new_i32(0); } else if( link_name == "pthread_rwlock_rdlock" ) { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); + rv = Value::new_i32(0); } else if( link_name == "pthread_mutexattr_init" || link_name == "pthread_mutexattr_settype" || link_name == "pthread_mutexattr_destroy" ) { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); + rv = Value::new_i32(0); } else if( link_name == "pthread_condattr_init" || link_name == "pthread_condattr_destroy" || link_name == "pthread_condattr_setclock" ) { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); + rv = Value::new_i32(0); } else if( link_name == "pthread_cond_init" || link_name == "pthread_cond_destroy" ) { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); + rv = Value::new_i32(0); } else if( link_name == "pthread_key_create" ) { @@ -1776,9 +1760,8 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c auto key = ThreadState::s_next_tls_key ++; key_ref.m_alloc.alloc().write_u32( key_ref.m_offset, key ); - - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); + + rv = Value::new_i32(0); } else if( link_name == "pthread_getspecific" ) { @@ -1787,8 +1770,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c // Get a pointer-sized value from storage uint64_t v = key < m_thread.tls_values.size() ? m_thread.tls_values[key] : 0; - rv = Value(::HIR::TypeRef(RawType::USize)); - rv.write_usize(0, v); + rv = Value::new_usize(v); } else if( link_name == "pthread_setspecific" ) { @@ -1801,13 +1783,11 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c } m_thread.tls_values[key] = v; - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); + rv = Value::new_i32(0); } else if( link_name == "pthread_key_delete" ) { - rv = Value(::HIR::TypeRef(RawType::I32)); - rv.write_i32(0, 0); + rv = Value::new_i32(0); } #endif // std C diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index c3db284a..c1098d1d 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -499,6 +499,11 @@ void Allocation::write_bytes(size_t ofs, const void* src, size_t count) ::std::memcpy(this->data_ptr() + ofs, src, count); mark_bytes_valid(ofs, count); } +void Allocation::write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc) +{ + this->write_usize(ofs, ptr_ofs); + this->relocations.push_back(Relocation { ofs, /*POINTER_SIZE,*/ ::std::move(reloc) }); +} ::std::ostream& operator<<(::std::ostream& os, const Allocation& x) { auto flags = os.flags(); @@ -620,6 +625,34 @@ Value Value::new_ffiptr(FFIPointer ffi) rv.allocation->mask.at(0) = 0xFF; // TODO: Get pointer size and make that much valid instead of 8 bytes return rv; } +Value Value::new_pointer(::HIR::TypeRef ty, uint64_t v, RelocationPtr r) { + assert(!ty.wrappers.empty()); + assert(ty.wrappers[0].type == TypeWrapper::Ty::Borrow || ty.wrappers[0].type == TypeWrapper::Ty::Pointer); + Value rv(ty); + rv.write_usize(0, v); + rv.allocation->relocations.push_back(Relocation { 0, /*POINTER_SIZE,*/ ::std::move(r) }); + return rv; +} +Value Value::new_usize(uint64_t v) { + Value rv( ::HIR::TypeRef(RawType::USize) ); + rv.write_usize(0, v); + return rv; +} +Value Value::new_isize(int64_t v) { + Value rv( ::HIR::TypeRef(RawType::ISize) ); + rv.write_isize(0, v); + return rv; +} +Value Value::new_u32(uint32_t v) { + Value rv( ::HIR::TypeRef(RawType::U32) ); + rv.write_u32(0, v); + return rv; +} +Value Value::new_i32(int32_t v) { + Value rv( ::HIR::TypeRef(RawType::I32) ); + rv.write_i32(0, v); + return rv; +} void Value::create_allocation() { @@ -775,6 +808,14 @@ void Value::write_value(size_t ofs, Value v) } } } +void Value::write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc) +{ + if( !this->allocation ) + { + LOG_ERROR("Writing a pointer with no allocation"); + } + this->allocation->write_ptr(ofs, ptr_ofs, ::std::move(reloc)); +} ::std::ostream& operator<<(::std::ostream& os, const Value& v) { diff --git a/tools/standalone_miri/value.hpp b/tools/standalone_miri/value.hpp index 81302e67..b057b3c4 100644 --- a/tools/standalone_miri/value.hpp +++ b/tools/standalone_miri/value.hpp @@ -201,6 +201,7 @@ struct ValueCommonWrite: void write_f64(size_t ofs, double v) { write_bytes(ofs, &v, 8); } void write_usize(size_t ofs, uint64_t v); void write_isize(size_t ofs, int64_t v) { write_usize(ofs, static_cast(v)); } + virtual void write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc) = 0; }; class Allocation: @@ -245,6 +246,7 @@ public: void write_value(size_t ofs, Value v); void write_bytes(size_t ofs, const void* src, size_t count) override; + void write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc) override; }; extern ::std::ostream& operator<<(::std::ostream& os, const Allocation& x); @@ -254,7 +256,8 @@ struct Value: // If NULL, data is direct AllocationHandle allocation; struct { - uint8_t data[2*sizeof(size_t)-3]; // 16-3 = 13, fits in 16 bits of mask + // NOTE: Can't pack the mask+size tighter, need 4 bits of size (8-15) leaving 12 bits of mask + uint8_t data[2*8-3]; // 13 data bytes, plus 16bit mask, plus size = 16 bytes uint8_t mask[2]; uint8_t size; } direct_data; @@ -265,8 +268,11 @@ struct Value: static Value with_size(size_t size, bool have_allocation); static Value new_fnptr(const ::HIR::Path& fn_path); static Value new_ffiptr(FFIPointer ffi); - //static Value new_usize(uint64_t v); - //static Value new_isize(int64_t v); + static Value new_pointer(::HIR::TypeRef ty, uint64_t v, RelocationPtr r); + static Value new_usize(uint64_t v); + static Value new_isize(int64_t v); + static Value new_u32(uint32_t v); + static Value new_i32(int32_t v); void create_allocation(); size_t size() const { return allocation ? allocation->size() : direct_data.size; } @@ -289,7 +295,7 @@ struct Value: void write_value(size_t ofs, Value v); void write_bytes(size_t ofs, const void* src, size_t count) override; - //void write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc); + void write_ptr(size_t ofs, size_t ptr_ofs, RelocationPtr reloc) override; }; extern ::std::ostream& operator<<(::std::ostream& os, const Value& v); -- cgit v1.2.3 From d97d3a3e9fedb73c612fae542db28626a687ab22 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 19 May 2018 13:29:22 +0800 Subject: Standalone MIRI - Remove direct uses of TypeRef.wrappers --- tools/standalone_miri/hir_sim.cpp | 40 +++++- tools/standalone_miri/hir_sim.hpp | 30 ++++- tools/standalone_miri/main.cpp | 4 +- tools/standalone_miri/miri.cpp | 240 ++++++++++++++++------------------ tools/standalone_miri/module_tree.cpp | 18 +-- tools/standalone_miri/value.cpp | 37 +----- 6 files changed, 186 insertions(+), 183 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/hir_sim.cpp b/tools/standalone_miri/hir_sim.cpp index 94f0d0e1..35f8f608 100644 --- a/tools/standalone_miri/hir_sim.cpp +++ b/tools/standalone_miri/hir_sim.cpp @@ -1,7 +1,12 @@ -// -// -// +/* + * mrustc Standalone MIRI + * - by John Hodge (Mutabah) + * + * value.cpp + * - Copy of the various HIR types from the compiler + */ #include +#include #include "hir_sim.hpp" #include "module_tree.hpp" @@ -140,7 +145,32 @@ HIR::TypeRef HIR::TypeRef::wrap(TypeWrapper::Ty ty, size_t size)&& rv.wrappers.insert(rv.wrappers.begin(), { ty, size }); return rv; } -const HIR::TypeRef* HIR::TypeRef::get_usized_type(size_t& running_inner_size) const +bool HIR::TypeRef::has_pointer() const +{ + // If ALL of the (potentially non) wrappers are Array, look deeper + // - Don't need to worry about unsized types here + if( ::std::all_of(this->wrappers.begin(), this->wrappers.end(), [](const auto& x){ return x.type == TypeWrapper::Ty::Array; }) ) + { + // TODO: Function pointers should be _pointers_ + if( this->inner_type == RawType::Function ) + { + return true; + } + // Check the inner type + if( this->inner_type == RawType::Composite ) + { + // Still not sure, check the inner for any pointers. + for(const auto& fld : this->composite_type->fields) + { + if( fld.second.has_pointer() ) + return true; + } + } + return false; + } + return true; +} +const HIR::TypeRef* HIR::TypeRef::get_unsized_type(size_t& running_inner_size) const { if( this->wrappers.empty() ) { @@ -153,7 +183,7 @@ const HIR::TypeRef* HIR::TypeRef::get_usized_type(size_t& running_inner_size) co return nullptr; running_inner_size = this->composite_type->fields.back().first; size_t tmp; - return this->composite_type->fields.back().second.get_usized_type(tmp); + return this->composite_type->fields.back().second.get_unsized_type(tmp); case RawType::TraitObject: case RawType::Str: return this; diff --git a/tools/standalone_miri/hir_sim.hpp b/tools/standalone_miri/hir_sim.hpp index 9f5ba59c..7730ac48 100644 --- a/tools/standalone_miri/hir_sim.hpp +++ b/tools/standalone_miri/hir_sim.hpp @@ -118,15 +118,41 @@ namespace HIR { } size_t get_size(size_t ofs=0) const; + + // Returns true if this (unsized) type is a wrapper around a slice + // - Fills `out_inner_size` with the size of the slice element bool has_slice_meta(size_t& out_inner_size) const; // The attached metadata is a count of elements - const TypeRef* get_usized_type(size_t& running_inner_size) const; + // Returns the base unsized type for this type (returning nullptr if there's no unsized field) + // - Fills `running_inner_size` with the offset to the unsized field + const TypeRef* get_unsized_type(size_t& running_inner_size) const; + // Returns the type of associated metadata for this (unsized) type (or `!` if not unsized) TypeRef get_meta_type() const; + // Get the inner type (one level of wrapping removed) TypeRef get_inner() const; + + // Add a wrapper over this type (moving) TypeRef wrap(TypeWrapper::Ty ty, size_t size)&&; + // Add a wrapper over this type (copying) TypeRef wrapped(TypeWrapper::Ty ty, size_t size) const { return TypeRef(*this).wrap(ty, size); } + // Get the wrapper at the provided offset (0 = outermost) + const TypeWrapper* get_wrapper(size_t ofs=0) const { + //assert(ofs <= this->wrappers.size()); + if( ofs < this->wrappers.size() ) { + return &this->wrappers[ofs]; + } + else { + return nullptr; + } + } + + // Returns true if the type contains any pointers + bool has_pointer() const; + // Get the type and offset of the specified field index TypeRef get_field(size_t idx, size_t& ofs) const; + // Get the offset and type of a field (recursing using `other_idx`) + size_t get_field_ofs(size_t idx, const ::std::vector& other_idx, TypeRef& ty) const; bool operator==(const RawType& x) const { if( this->wrappers.size() != 0 ) @@ -152,8 +178,6 @@ namespace HIR { return false; } - size_t get_field_ofs(size_t idx, const ::std::vector& other_idx, TypeRef& ty) const; - friend ::std::ostream& operator<<(::std::ostream& os, const TypeRef& x); }; diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index e3a8d22e..90b5eff3 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -62,9 +62,7 @@ int main(int argc, const char* argv[]) // Construct argc/argv values auto val_argc = Value::new_isize(1 + opts.args.size()); - ::HIR::TypeRef argv_ty { RawType::I8 }; - argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); - argv_ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, 0 }); + auto argv_ty = ::HIR::TypeRef(RawType::I8).wrap(TypeWrapper::Ty::Pointer, 0 ).wrap(TypeWrapper::Ty::Pointer, 0); auto val_argv = Value::new_pointer(argv_ty, 0, RelocationPtr::new_alloc(argv_alloc)); // Catch various exceptions from the interpreter diff --git a/tools/standalone_miri/miri.cpp b/tools/standalone_miri/miri.cpp index c0e7d15c..63be419c 100644 --- a/tools/standalone_miri/miri.cpp +++ b/tools/standalone_miri/miri.cpp @@ -175,7 +175,7 @@ public: static PrimitiveValueVirt from_value(const ::HIR::TypeRef& t, const ValueRef& v) { PrimitiveValueVirt rv; - LOG_ASSERT(t.wrappers.empty(), "PrimitiveValueVirt::from_value: " << t); + LOG_ASSERT(t.get_wrapper() == nullptr, "PrimitiveValueVirt::from_value: " << t); switch(t.inner_type) { case RawType::U32: @@ -281,15 +281,18 @@ struct MirHelpers auto idx = get_value_ref(*e.idx).read_usize(0); ::HIR::TypeRef array_ty; auto base_val = get_value_and_type(*e.val, array_ty); - if( array_ty.wrappers.empty() ) + const auto* wrapper = array_ty.get_wrapper(); + if( !wrapper ) + { LOG_ERROR("Indexing non-array/slice - " << array_ty); - if( array_ty.wrappers.front().type == TypeWrapper::Ty::Array ) + } + else if( wrapper->type == TypeWrapper::Ty::Array ) { ty = array_ty.get_inner(); base_val.m_offset += ty.get_size() * idx; return base_val; } - else if( array_ty.wrappers.front().type == TypeWrapper::Ty::Slice ) + else if( wrapper->type == TypeWrapper::Ty::Slice ) { LOG_TODO("Slice index"); } @@ -354,7 +357,7 @@ struct MirHelpers size_t slice_inner_size; if( ty.has_slice_meta(slice_inner_size) ) { - size = (ty.wrappers.empty() ? ty.get_size() : 0) + meta_val->read_usize(0) * slice_inner_size; + size = (ty.get_wrapper() == nullptr ? ty.get_size() : 0) + meta_val->read_usize(0) * slice_inner_size; } //else if( ty == RawType::TraitObject) { // // NOTE: Getting the size from the allocation is semi-valid, as you can't sub-slice trait objects @@ -468,8 +471,7 @@ struct MirHelpers LOG_TODO("Constant::Bytes"); } break; TU_ARM(c, StaticString, ce) { - ty = ::HIR::TypeRef(RawType::Str); - ty.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); + ty = ::HIR::TypeRef(RawType::Str).wrap(TypeWrapper::Ty::Borrow, 0); Value val = Value(ty); val.write_ptr(0, 0, RelocationPtr::new_string(&ce)); val.write_usize(POINTER_SIZE, ce.size()); @@ -484,8 +486,7 @@ struct MirHelpers return Value::new_fnptr(ce); } if( const auto* s = this->thread.m_modtree.get_static_opt(ce) ) { - ty = s->ty; - ty.wrappers.insert(ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, 0 }); + ty = s->ty.wrapped(TypeWrapper::Ty::Borrow, 0); return Value::new_pointer(ty, 0, RelocationPtr::new_alloc(s->val.allocation)); } LOG_ERROR("Constant::ItemAddr - " << ce << " - not found"); @@ -602,10 +603,10 @@ bool InterpreterThread::step_one(Value& out_thread_result) LOG_DEBUG("- alloc=" << alloc); size_t ofs = src_base_value.m_offset; const auto meta = src_ty.get_meta_type(); - src_ty.wrappers.insert(src_ty.wrappers.begin(), TypeWrapper { TypeWrapper::Ty::Borrow, static_cast(re.type) }); + auto dst_ty = src_ty.wrapped(TypeWrapper::Ty::Borrow, static_cast(re.type)); // Create the pointer - new_val = Value(src_ty); + new_val = Value(dst_ty); new_val.write_ptr(0, ofs, ::std::move(alloc)); // - Add metadata if required if( meta != RawType::Unreachable ) @@ -626,26 +627,24 @@ bool InterpreterThread::step_one(Value& out_thread_result) // No-op cast new_val = src_value.read_value(0, re.type.get_size()); } - else if( !re.type.wrappers.empty() ) + else if( const auto* dst_w = re.type.get_wrapper() ) { // Destination can only be a raw pointer - if( re.type.wrappers.at(0).type != TypeWrapper::Ty::Pointer ) { - throw "ERROR"; + if( dst_w->type != TypeWrapper::Ty::Pointer ) { + LOG_ERROR("Attempting to cast to a type other than a raw pointer - " << re.type); } - if( !src_ty.wrappers.empty() ) + if( const auto* src_w = src_ty.get_wrapper() ) { // Source can be either - if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer - && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { - throw "ERROR"; + if( src_w->type != TypeWrapper::Ty::Pointer && src_w->type != TypeWrapper::Ty::Borrow ) { + LOG_ERROR("Attempting to cast to a pointer from a non-pointer - " << src_ty); } - if( src_ty.get_size() > re.type.get_size() ) { - // TODO: How to casting fat to thin? - //LOG_TODO("Handle casting fat to thin, " << src_ty << " -> " << re.type); - new_val = src_value.read_value(0, re.type.get_size()); + if( src_ty.get_size() < re.type.get_size() ) + { + LOG_ERROR("Casting to a fatter pointer, " << src_ty << " -> " << re.type); } - else + else { new_val = src_value.read_value(0, re.type.get_size()); } @@ -660,18 +659,15 @@ bool InterpreterThread::step_one(Value& out_thread_result) } else { - ::std::cerr << "ERROR: Trying to pointer (" << re.type <<" ) from invalid type (" << src_ty << ")\n"; - throw "ERROR"; + LOG_ERROR("Trying to cast to pointer (" << re.type <<" ) from invalid type (" << src_ty << ")\n"); } new_val = src_value.read_value(0, re.type.get_size()); } } - else if( !src_ty.wrappers.empty() ) + else if( const auto* src_w = src_ty.get_wrapper() ) { - // TODO: top wrapper MUST be a pointer - if( src_ty.wrappers.at(0).type != TypeWrapper::Ty::Pointer - && src_ty.wrappers.at(0).type != TypeWrapper::Ty::Borrow ) { - throw "ERROR"; + if( src_w->type != TypeWrapper::Ty::Pointer && src_w->type != TypeWrapper::Ty::Borrow ) { + LOG_ERROR("Attempting to cast to a non-pointer - " << src_ty); } // TODO: MUST be a thin pointer? @@ -802,7 +798,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) LOG_ASSERT(dt.variants[i].field_path.empty(), ""); } ::HIR::TypeRef tag_ty = dt.fields[0].second; - LOG_ASSERT(tag_ty.wrappers.empty(), ""); + LOG_ASSERT(tag_ty.get_wrapper() == nullptr, ""); switch(tag_ty.inner_type) { case RawType::USize: @@ -954,7 +950,33 @@ bool InterpreterThread::step_one(Value& out_thread_result) } LOG_DEBUG("res=" << res << ", " << reloc_l << " ? " << reloc_r); - if( ty_l.wrappers.empty() ) + if( const auto* w = ty_l.get_wrapper() ) + { + if( w->type == TypeWrapper::Ty::Pointer ) + { + // TODO: Technically only EQ/NE are valid. + + res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); + + // Compare fat metadata. + if( res == 0 && v_l.m_size > POINTER_SIZE ) + { + reloc_l = v_l.get_relocation(POINTER_SIZE); + reloc_r = v_r.get_relocation(POINTER_SIZE); + + if( res == 0 && reloc_l != reloc_r ) + { + res = (reloc_l < reloc_r ? -1 : 1); + } + res = res != 0 ? res : Ops::do_compare(v_l.read_usize(POINTER_SIZE), v_r.read_usize(POINTER_SIZE)); + } + } + else + { + LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); + } + } + else { switch(ty_l.inner_type) { @@ -972,29 +994,6 @@ bool InterpreterThread::step_one(Value& out_thread_result) LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); } } - else if( ty_l.wrappers.front().type == TypeWrapper::Ty::Pointer ) - { - // TODO: Technically only EQ/NE are valid. - - res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); - - // Compare fat metadata. - if( res == 0 && v_l.m_size > POINTER_SIZE ) - { - reloc_l = v_l.get_relocation(POINTER_SIZE); - reloc_r = v_r.get_relocation(POINTER_SIZE); - - if( res == 0 && reloc_l != reloc_r ) - { - res = (reloc_l < reloc_r ? -1 : 1); - } - res = res != 0 ? res : Ops::do_compare(v_l.read_usize(POINTER_SIZE), v_r.read_usize(POINTER_SIZE)); - } - } - else - { - LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l); - } bool res_bool; switch(re.op) { @@ -1013,8 +1012,8 @@ bool InterpreterThread::step_one(Value& out_thread_result) } break; case ::MIR::eBinOp::BIT_SHL: case ::MIR::eBinOp::BIT_SHR: { - LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); - LOG_ASSERT(ty_r.wrappers.empty(), "Bitwise operator with non-primitive - " << ty_r); + LOG_ASSERT(ty_l.get_wrapper() == nullptr, "Bitwise operator on non-primitive - " << ty_l); + LOG_ASSERT(ty_r.get_wrapper() == nullptr, "Bitwise operator with non-primitive - " << ty_r); size_t max_bits = ty_r.get_size() * 8; uint8_t shift; auto check_cast = [&](auto v){ LOG_ASSERT(0 <= v && v <= max_bits, "Shift out of range - " << v); return static_cast(v); }; @@ -1051,7 +1050,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) case ::MIR::eBinOp::BIT_OR: case ::MIR::eBinOp::BIT_XOR: LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r); - LOG_ASSERT(ty_l.wrappers.empty(), "Bitwise operator on non-primitive - " << ty_l); + LOG_ASSERT(ty_l.get_wrapper() == nullptr, "Bitwise operator on non-primitive - " << ty_l); new_val = Value(ty_l); switch(ty_l.inner_type) { @@ -1104,7 +1103,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) TU_ARM(se.src, UniOp, re) { ::HIR::TypeRef ty; auto v = state.get_value_and_type(re.val, ty); - LOG_ASSERT(ty.wrappers.empty(), "UniOp on wrapped type - " << ty); + LOG_ASSERT(ty.get_wrapper() == nullptr, "UniOp on wrapped type - " << ty); new_val = Value(ty); switch(re.op) { @@ -1238,7 +1237,6 @@ bool InterpreterThread::step_one(Value& out_thread_result) const auto& data_ty = this->m_modtree.get_composite(re.path); auto dst_ty = ::HIR::TypeRef(&data_ty); new_val = Value(dst_ty); - LOG_DEBUG("Variant " << new_val); // Three cases: // - Unions (no tag) // - Data enums (tag and data) @@ -1250,7 +1248,6 @@ bool InterpreterThread::step_one(Value& out_thread_result) new_val.write_value(fld.first, state.param_to_value(re.val)); } - LOG_DEBUG("Variant " << new_val); if( var.base_field != SIZE_MAX ) { ::HIR::TypeRef tag_ty; @@ -1279,7 +1276,7 @@ bool InterpreterThread::step_one(Value& out_thread_result) } } break; } - LOG_DEBUG("- " << new_val); + LOG_DEBUG("- new_val=" << new_val); state.write_lvalue(se.dst, ::std::move(new_val)); } break; case ::MIR::Statement::TAG_Asm: @@ -1352,8 +1349,8 @@ bool InterpreterThread::step_one(Value& out_thread_result) TU_ARM(bb.terminator, Switch, te) { ::HIR::TypeRef ty; auto v = state.get_value_and_type(te.val, ty); - LOG_ASSERT(ty.wrappers.size() == 0, "" << ty); - LOG_ASSERT(ty.inner_type == RawType::Composite, "" << ty); + LOG_ASSERT(ty.get_wrapper() == nullptr, "Matching on wrapped value - " << ty); + LOG_ASSERT(ty.inner_type == RawType::Composite, "Matching on non-coposite - " << ty); // TODO: Convert the variant list into something that makes it easier to switch on. size_t found_target = SIZE_MAX; @@ -1578,8 +1575,7 @@ bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, c auto size = args.at(0).read_usize(0); auto align = args.at(1).read_usize(0); LOG_DEBUG("__rust_allocate(size=" << size << ", align=" << align << ")"); - ::HIR::TypeRef rty { RawType::Unit }; - rty.wrappers.push_back({ TypeWrapper::Ty::Pointer, 0 }); + auto rty = ::HIR::TypeRef(RawType::Unit).wrap( TypeWrapper::Ty::Pointer, 0 ); // TODO: Use the alignment when making an allocation? rv = Value::new_pointer(rty, 0, RelocationPtr::new_alloc(Allocation::new_alloc(size))); @@ -2051,14 +2047,14 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con // Get unsized type somehow. // - _HAS_ to be the last type, so that makes it easier size_t fixed_size = 0; - if( const auto* ity = ty.get_usized_type(fixed_size) ) + if( const auto* ity = ty.get_unsized_type(fixed_size) ) { const auto meta_ty = ty.get_meta_type(); LOG_DEBUG("size_of_val - " << ty << " ity=" << *ity << " meta_ty=" << meta_ty << " fixed_size=" << fixed_size); size_t flex_size = 0; - if( !ity->wrappers.empty() ) + if( const auto* w = ity->get_wrapper() ) { - LOG_ASSERT(ity->wrappers[0].type == TypeWrapper::Ty::Slice, ""); + LOG_ASSERT(w->type == TypeWrapper::Ty::Slice, "size_of_val on wrapped type that isn't a slice - " << *ity); size_t item_size = ity->get_inner().get_size(); size_t item_count = val.read_usize(POINTER_SIZE); flex_size = item_count * item_size; @@ -2088,40 +2084,7 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con { auto& val = args.at(0); const auto& ty = ty_params.tys.at(0); - if( !ty.wrappers.empty() ) - { - size_t item_count = 0; - switch(ty.wrappers[0].type) - { - case TypeWrapper::Ty::Slice: - case TypeWrapper::Ty::Array: - item_count = (ty.wrappers[0].type == TypeWrapper::Ty::Slice ? val.read_usize(POINTER_SIZE) : ty.wrappers[0].size); - break; - case TypeWrapper::Ty::Pointer: - break; - case TypeWrapper::Ty::Borrow: - // TODO: Only &move has a destructor - break; - } - LOG_ASSERT(ty.wrappers[0].type == TypeWrapper::Ty::Slice, "drop_in_place should only exist for slices - " << ty); - const auto& ity = ty.get_inner(); - size_t item_size = ity.get_size(); - - auto ptr = val.read_value(0, POINTER_SIZE); - for(size_t i = 0; i < item_count; i ++) - { - // TODO: Nested calls? - if( !drop_value(ptr, ity) ) - { - LOG_DEBUG("Handle multiple queued calls"); - } - ptr.write_usize(0, ptr.read_usize(0) + item_size); - } - } - else - { - return drop_value(val, ty); - } + return drop_value(val, ty); } // ---------------------------------------------------------------- // Checked arithmatic @@ -2249,12 +2212,55 @@ bool InterpreterThread::drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_ if( ofs != 0 || !alloc || !alloc.is_alloc() ) { LOG_ERROR("Attempting to shallow drop with invalid pointer (no relocation or non-zero offset) - " << box_ptr_vr); } - + LOG_DEBUG("drop_value SHALLOW deallocate " << alloc); alloc.alloc().mark_as_freed(); return true; } - if( ty.wrappers.empty() ) + if( const auto* w = ty.get_wrapper() ) + { + switch( w->type ) + { + case TypeWrapper::Ty::Borrow: + if( w->size == static_cast(::HIR::BorrowType::Move) ) + { + LOG_TODO("Drop - " << ty << " - dereference and go to inner"); + // TODO: Clear validity on the entire inner value. + //auto iptr = ptr.read_value(0, ty.get_size()); + //drop_value(iptr, ty.get_inner()); + } + else + { + // No destructor + } + break; + case TypeWrapper::Ty::Pointer: + // No destructor + break; + case TypeWrapper::Ty::Slice: { + // - Get thin pointer and count + auto ofs = ptr.read_usize(0); + auto ptr_reloc = ptr.get_relocation(0); + auto count = ptr.read_usize(POINTER_SIZE); + + auto ity = ty.get_inner(); + auto pty = ity.wrapped(TypeWrapper::Ty::Borrow, static_cast(::HIR::BorrowType::Move)); + for(uint64_t i = 0; i < count; i ++) + { + auto ptr = Value::new_pointer(pty, ofs, ptr_reloc); + if( !drop_value(ptr, ity) ) { + LOG_TODO("Handle closure looping when dropping a slice"); + } + ofs += ity.get_size(); + } + } break; + // TODO: Arrays? + default: + LOG_TODO("Drop - " << ty << " - array?"); + break; + } + } + else { if( ty.inner_type == RawType::Composite ) { @@ -2279,29 +2285,5 @@ bool InterpreterThread::drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_ // No destructor } } - else - { - switch( ty.wrappers[0].type ) - { - case TypeWrapper::Ty::Borrow: - if( ty.wrappers[0].size == static_cast(::HIR::BorrowType::Move) ) - { - LOG_TODO("Drop - " << ty << " - dereference and go to inner"); - // TODO: Clear validity on the entire inner value. - } - else - { - // No destructor - } - break; - case TypeWrapper::Ty::Pointer: - // No destructor - break; - // TODO: Arrays - default: - LOG_TODO("Drop - " << ty << " - array?"); - break; - } - } return true; } diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index cb6f943d..db5fd495 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -266,7 +266,7 @@ bool Parser::parse_one() //const auto* tag_ty = &rv.fields.at(base_idx).second; //for(auto idx : other_idx) //{ - // assert(tag_ty->wrappers.size() == 0); + // assert(tag_ty->get_wrapper() == nullptr); // assert(tag_ty->inner_type == RawType::Composite); // LOG_TODO(lex << "Calculate tag offset with nested tag - " << idx << " ty=" << *tag_ty); //} @@ -1130,14 +1130,14 @@ RawType Parser::parse_core_type() { size_t size = lex.next().integer(); lex.consume(); - rv.wrappers.insert( rv.wrappers.begin(), { TypeWrapper::Ty::Array, size }); + lex.check_consume(']'); + return ::std::move(rv).wrap( TypeWrapper::Ty::Array, size ); } else { - rv.wrappers.insert( rv.wrappers.begin(), { TypeWrapper::Ty::Slice, 0 }); + lex.check_consume(']'); + return ::std::move(rv).wrap( TypeWrapper::Ty::Slice, 0 ); } - lex.check_consume(']'); - return rv; } else if( lex.consume_if('!') ) { @@ -1152,9 +1152,7 @@ RawType Parser::parse_core_type() bt = ::HIR::BorrowType::Unique; else ; // keep as shared - auto rv = parse_type(); - rv.wrappers.insert( rv.wrappers.begin(), { TypeWrapper::Ty::Borrow, static_cast(bt) }); - return rv; + return parse_type().wrap( TypeWrapper::Ty::Borrow, static_cast(bt) ); } else if( lex.consume_if('*') ) { @@ -1167,9 +1165,7 @@ RawType Parser::parse_core_type() ; // keep as shared else throw "ERROR"; - auto rv = parse_type(); - rv.wrappers.insert( rv.wrappers.begin(), { TypeWrapper::Ty::Pointer, static_cast(bt) }); - return rv; + return parse_type().wrap( TypeWrapper::Ty::Pointer, static_cast(bt) ); } else if( lex.next() == "::" ) { diff --git a/tools/standalone_miri/value.cpp b/tools/standalone_miri/value.cpp index c1098d1d..cf378077 100644 --- a/tools/standalone_miri/value.cpp +++ b/tools/standalone_miri/value.cpp @@ -545,38 +545,12 @@ Value::Value() Value::Value(::HIR::TypeRef ty) { size_t size = ty.get_size(); -#if 1 + // Support inline data if the data will fit within the inline region (which is the size of the metadata) if( ty.get_size() <= sizeof(this->direct_data.data) ) { - struct H - { - static bool has_pointer(const ::HIR::TypeRef& ty) - { - if( ty.wrappers.empty() || ::std::all_of(ty.wrappers.begin(), ty.wrappers.end(), [](const auto& x){ return x.type == TypeWrapper::Ty::Array; }) ) - { - // TODO: Function pointers should be _pointers_ - if( ty.inner_type == RawType::Function ) - { - return true; - } - // Check the inner type - if( ty.inner_type != RawType::Composite ) - { - return false; - } - // Still not sure, check the inner for any pointers. - for(const auto& fld : ty.composite_type->fields) - { - if( H::has_pointer(fld.second) ) - return true; - } - return false; - } - return true; - } - }; - if( ! H::has_pointer(ty) ) + // AND the type doesn't contain a pointer (of any kind) + if( ! ty.has_pointer() ) { // Will fit in a inline allocation, nice. //LOG_TRACE("No pointers in " << ty << ", storing inline"); @@ -586,7 +560,6 @@ Value::Value(::HIR::TypeRef ty) return ; } } -#endif // Fallback: Make a new allocation //LOG_TRACE(" Creating allocation for " << ty); @@ -626,8 +599,8 @@ Value Value::new_ffiptr(FFIPointer ffi) return rv; } Value Value::new_pointer(::HIR::TypeRef ty, uint64_t v, RelocationPtr r) { - assert(!ty.wrappers.empty()); - assert(ty.wrappers[0].type == TypeWrapper::Ty::Borrow || ty.wrappers[0].type == TypeWrapper::Ty::Pointer); + assert(ty.get_wrapper()); + assert(ty.get_wrapper()->type == TypeWrapper::Ty::Borrow || ty.get_wrapper()->type == TypeWrapper::Ty::Pointer); Value rv(ty); rv.write_usize(0, v); rv.allocation->relocations.push_back(Relocation { 0, /*POINTER_SIZE,*/ ::std::move(r) }); -- cgit v1.2.3 From c2cfe98c96562af2a564a6715fcd6d09c2fa9f9b Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 19 May 2018 13:41:19 +0800 Subject: Standalone MIRI - Clean up more direct uses of TypeRef.wrappers --- tools/standalone_miri/hir_sim.cpp | 207 ++++++++++++++++++++------------------ 1 file changed, 111 insertions(+), 96 deletions(-) (limited to 'tools') diff --git a/tools/standalone_miri/hir_sim.cpp b/tools/standalone_miri/hir_sim.cpp index 35f8f608..88739730 100644 --- a/tools/standalone_miri/hir_sim.cpp +++ b/tools/standalone_miri/hir_sim.cpp @@ -18,7 +18,58 @@ size_t HIR::TypeRef::get_size(size_t ofs) const { - if( this->wrappers.size() <= ofs ) + if( const auto* w = this->get_wrapper(ofs) ) + { + switch(w->type) + { + case TypeWrapper::Ty::Array: + return this->get_size(1) * w->size; + case TypeWrapper::Ty::Borrow: + case TypeWrapper::Ty::Pointer: + if( const auto* next_w = this->get_wrapper(ofs+1) ) + { + if( next_w->type == TypeWrapper::Ty::Slice ) + { + return POINTER_SIZE*2; + } + else + { + return POINTER_SIZE; + } + } + else + { + // Need to look up the metadata type for the actual type + if( this->inner_type == RawType::Composite ) + { + if( this->composite_type->dst_meta == RawType::Unreachable ) + { + return POINTER_SIZE; + } + // Special case: extern types (which appear when a type is only ever used by pointer) + if( this->composite_type->dst_meta == RawType::Unit ) + { + return POINTER_SIZE; + } + + // TODO: Ideally, this inner type wouldn't be unsized itself... but checking that would be interesting. + return POINTER_SIZE + this->composite_type->dst_meta.get_size(); + } + else if( this->inner_type == RawType::Str ) + return POINTER_SIZE*2; + else if( this->inner_type == RawType::TraitObject ) + return POINTER_SIZE*2; + else + { + return POINTER_SIZE; + } + } + case TypeWrapper::Ty::Slice: + LOG_BUG("Getting size of a slice - " << *this); + } + throw ""; + } + else { switch(this->inner_type) { @@ -59,56 +110,15 @@ size_t HIR::TypeRef::get_size(size_t ofs) const } throw ""; } - - switch(this->wrappers[ofs].type) - { - case TypeWrapper::Ty::Array: - return this->get_size(1) * this->wrappers[ofs].size; - case TypeWrapper::Ty::Borrow: - case TypeWrapper::Ty::Pointer: - if( this->wrappers.size() == ofs+1 ) - { - // Need to look up the metadata type for the actual type - if( this->inner_type == RawType::Composite ) - { - if( this->composite_type->dst_meta == RawType::Unreachable ) - { - return POINTER_SIZE; - } - // Special case: extern types (which appear when a type is only ever used by pointer) - if( this->composite_type->dst_meta == RawType::Unit ) - { - return POINTER_SIZE; - } - - // TODO: Ideally, this inner type wouldn't be unsized itself... but checking that would be interesting. - return POINTER_SIZE + this->composite_type->dst_meta.get_size(); - } - else if( this->inner_type == RawType::Str ) - return POINTER_SIZE*2; - else if( this->inner_type == RawType::TraitObject ) - return POINTER_SIZE*2; - else - { - return POINTER_SIZE; - } - } - else if( this->wrappers[ofs+1].type == TypeWrapper::Ty::Slice ) - { - return POINTER_SIZE*2; - } - else - { - return POINTER_SIZE; - } - case TypeWrapper::Ty::Slice: - LOG_BUG("Getting size of a slice - " << *this); - } - throw ""; } bool HIR::TypeRef::has_slice_meta(size_t& out_inner_size) const { - if( this->wrappers.size() == 0 ) + if( const auto* w = this->get_wrapper() ) + { + out_inner_size = this->get_size(1); + return (w->type == TypeWrapper::Ty::Slice); + } + else { if(this->inner_type == RawType::Composite) { @@ -122,22 +132,20 @@ bool HIR::TypeRef::has_slice_meta(size_t& out_inner_size) const return (this->inner_type == RawType::Str); } } - else - { - out_inner_size = this->get_size(1); - return (this->wrappers[0].type == TypeWrapper::Ty::Slice); - } } HIR::TypeRef HIR::TypeRef::get_inner() const { if( this->wrappers.empty() ) { - throw "ERROR"; + LOG_ERROR("Getting inner of a non-wrapped type - " << *this); + } + else + { + auto ity = *this; + ity.wrappers.erase(ity.wrappers.begin()); + return ity; } - auto ity = *this; - ity.wrappers.erase(ity.wrappers.begin()); - return ity; } HIR::TypeRef HIR::TypeRef::wrap(TypeWrapper::Ty ty, size_t size)&& { @@ -172,7 +180,18 @@ bool HIR::TypeRef::has_pointer() const } const HIR::TypeRef* HIR::TypeRef::get_unsized_type(size_t& running_inner_size) const { - if( this->wrappers.empty() ) + if( const auto* w = this->get_wrapper() ) + { + if( w->type == TypeWrapper::Ty::Slice ) + { + return this; + } + else + { + return nullptr; + } + } + else { switch(this->inner_type) { @@ -191,18 +210,21 @@ const HIR::TypeRef* HIR::TypeRef::get_unsized_type(size_t& running_inner_size) c return nullptr; } } - else if( this->wrappers[0].type == TypeWrapper::Ty::Slice ) - { - return this; - } - else - { - return nullptr; - } } HIR::TypeRef HIR::TypeRef::get_meta_type() const { - if( this->wrappers.empty() ) + if( const auto* w = this->get_wrapper() ) + { + if( w->type == TypeWrapper::Ty::Slice ) + { + return TypeRef(RawType::USize); + } + else + { + return TypeRef(RawType::Unreachable); + } + } + else { switch(this->inner_type) { @@ -210,30 +232,38 @@ HIR::TypeRef HIR::TypeRef::get_meta_type() const if( this->composite_type->dst_meta == RawType::Unreachable ) return TypeRef(RawType::Unreachable); return this->composite_type->dst_meta; - case RawType::TraitObject: { - auto rv = ::HIR::TypeRef( this->composite_type ); - rv.wrappers.push_back(TypeWrapper { TypeWrapper::Ty::Pointer, static_cast(BorrowType::Shared) }); - return rv; - } + case RawType::TraitObject: + return ::HIR::TypeRef(this->composite_type).wrap( TypeWrapper::Ty::Pointer, static_cast(BorrowType::Shared) ); case RawType::Str: return TypeRef(RawType::USize); default: return TypeRef(RawType::Unreachable); } } - else if( this->wrappers[0].type == TypeWrapper::Ty::Slice ) - { - return TypeRef(RawType::USize); - } - else - { - return TypeRef(RawType::Unreachable); - } } HIR::TypeRef HIR::TypeRef::get_field(size_t idx, size_t& ofs) const { - if( this->wrappers.empty() ) + if( const auto* w = this->get_wrapper() ) + { + if( w->type == TypeWrapper::Ty::Slice ) + { + // TODO + throw "TODO"; + } + else if( w->type == TypeWrapper::Ty::Array ) + { + LOG_ASSERT(idx < w->size, "Getting field on array with OOB index - " << idx << " >= " << w->size << " - " << *this); + auto ity = this->get_inner(); + ofs = ity.get_size() * idx; + return ity; + } + else + { + throw "ERROR"; + } + } + else { if( this->inner_type == RawType::Composite ) { @@ -247,21 +277,6 @@ HIR::TypeRef HIR::TypeRef::get_field(size_t idx, size_t& ofs) const throw "ERROR"; } } - else if( this->wrappers.front().type == TypeWrapper::Ty::Slice ) - { - // TODO - throw "TODO"; - } - else if( this->wrappers.front().type == TypeWrapper::Ty::Array ) - { - auto ity = this->get_inner(); - ofs = ity.get_size() * idx; - return ity; - } - else - { - throw "ERROR"; - } } size_t HIR::TypeRef::get_field_ofs(size_t base_idx, const ::std::vector& other_idx, TypeRef& ty) const { -- cgit v1.2.3 From b5b70897015ee70d62ddda9711c256ca7c720e0f Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 20 May 2018 09:49:16 +0800 Subject: Standalone MIRI - A few comment notes --- tools/standalone_miri/miri.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'tools') diff --git a/tools/standalone_miri/miri.cpp b/tools/standalone_miri/miri.cpp index 63be419c..5f9c095f 100644 --- a/tools/standalone_miri/miri.cpp +++ b/tools/standalone_miri/miri.cpp @@ -1467,7 +1467,7 @@ bool InterpreterThread::pop_stack(Value& out_thread_result) } else { - // Handle callback wrappers (e.g. for __rust_maybe_catch_panic) + // Handle callback wrappers (e.g. for __rust_maybe_catch_panic, drop_value) if( this->m_stack.back().cb ) { if( !this->m_stack.back().cb(res_v, ::std::move(res_v)) ) @@ -2201,8 +2201,10 @@ bool InterpreterThread::call_intrinsic(Value& rv, const ::std::string& name, con return true; } +// TODO: Use a ValueRef instead? bool InterpreterThread::drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_shallow/*=false*/) { + // TODO: After the drop is done, flag the backing allocation for `ptr` as freed if( is_shallow ) { // HACK: Only works for Box where the first pointer is the data pointer -- cgit v1.2.3 From 7a4733c76c0391578fe04fde9cfa19698878c81e Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 20 May 2018 12:11:32 +0800 Subject: Minicargo - Quieten build output --- minicargo.mk | 14 +++++++------- tools/common/debug.cpp | 8 ++++++++ tools/common/debug.h | 1 + tools/minicargo/Makefile | 2 +- tools/minicargo/main.cpp | 28 +++++++++++++++++++++++----- 5 files changed, 40 insertions(+), 13 deletions(-) (limited to 'tools') diff --git a/minicargo.mk b/minicargo.mk index 0d2d4fb1..db19eab9 100644 --- a/minicargo.mk +++ b/minicargo.mk @@ -45,31 +45,31 @@ LIBS: $(OUTDIR)libstd.hir $(OUTDIR)libtest.hir $(OUTDIR)libpanic_unwind.hir $(OU $(MRUSTC): $(MAKE) -f Makefile all - test -e $@ + @test -e $@ $(MINICARGO): $(MAKE) -C tools/minicargo/ - test -e $@ + @test -e $@ # Standard library crates # - libstd, libpanic_unwind, libtest and libgetopts # - libproc_macro (mrustc) $(OUTDIR)libstd.hir: $(MRUSTC) $(MINICARGO) $(MINICARGO) $(RUSTCSRC)src/libstd --script-overrides $(OVERRIDE_DIR) --output-dir $(OUTDIR) $(MINICARGO_FLAGS) - test -e $@ + @test -e $@ $(OUTDIR)libpanic_unwind.hir: $(MRUSTC) $(MINICARGO) $(OUTDIR)libstd.hir $(MINICARGO) $(RUSTCSRC)src/libpanic_unwind --script-overrides $(OVERRIDE_DIR) --output-dir $(OUTDIR) $(MINICARGO_FLAGS) - test -e $@ + @test -e $@ $(OUTDIR)libtest.hir: $(MRUSTC) $(MINICARGO) $(OUTDIR)libstd.hir $(OUTDIR)libpanic_unwind.hir $(MINICARGO) $(RUSTCSRC)src/libtest --vendor-dir $(RUSTCSRC)src/vendor --output-dir $(OUTDIR) $(MINICARGO_FLAGS) - test -e $@ + @test -e $@ $(OUTDIR)libgetopts.hir: $(MRUSTC) $(MINICARGO) $(OUTDIR)libstd.hir $(MINICARGO) $(RUSTCSRC)src/libgetopts --script-overrides $(OVERRIDE_DIR) --output-dir $(OUTDIR) $(MINICARGO_FLAGS) - test -e $@ + @test -e $@ # MRustC custom version of libproc_macro $(OUTDIR)libproc_macro.hir: $(MRUSTC) $(MINICARGO) $(OUTDIR)libstd.hir $(MINICARGO) lib/libproc_macro --output-dir $(OUTDIR) $(MINICARGO_FLAGS) - test -e $@ + @test -e $@ RUSTC_ENV_VARS := CFG_COMPILER_HOST_TRIPLE=$(RUSTC_TARGET) RUSTC_ENV_VARS += LLVM_CONFIG=$(abspath $(LLVM_CONFIG)) diff --git a/tools/common/debug.cpp b/tools/common/debug.cpp index a3fb9956..94d8ed99 100644 --- a/tools/common/debug.cpp +++ b/tools/common/debug.cpp @@ -34,6 +34,14 @@ void Debug_DisablePhase(const char* phase_name) { gmDisabledDebug.insert( ::std::string(phase_name) ); } +void Debug_EnablePhase(const char* phase_name) +{ + auto it = gmDisabledDebug.find(phase_name); + if( it != gmDisabledDebug.end() ) + { + gmDisabledDebug.erase(it); + } +} void Debug_Print(::std::function cb) { if( !Debug_IsEnabled() ) diff --git a/tools/common/debug.h b/tools/common/debug.h index ace00876..86c88de9 100644 --- a/tools/common/debug.h +++ b/tools/common/debug.h @@ -7,6 +7,7 @@ typedef ::std::function dbg_cb_t; extern void Debug_SetPhase(const char* phase_name); extern void Debug_DisablePhase(const char* phase_name); +extern void Debug_EnablePhase(const char* phase_name); extern bool Debug_IsEnabled(); extern void Debug_EnterScope(const char* name, dbg_cb_t ); extern void Debug_LeaveScope(const char* name, dbg_cb_t ); diff --git a/tools/minicargo/Makefile b/tools/minicargo/Makefile index 01010fb5..363ef4b9 100644 --- a/tools/minicargo/Makefile +++ b/tools/minicargo/Makefile @@ -38,7 +38,7 @@ $(OBJDIR)%.o: %.cpp @echo [CXX] $< $V$(CXX) -o $@ -c $< $(CXXFLAGS) -MMD -MP -MF $@.dep -../bin/common_lib.a: +../bin/common_lib.a: $(wildcard ../common/*.* ../common/Makefile) make -C ../common -include $(OBJS:%.o=%.o.dep) diff --git a/tools/minicargo/main.cpp b/tools/minicargo/main.cpp index 50e08619..b185881b 100644 --- a/tools/minicargo/main.cpp +++ b/tools/minicargo/main.cpp @@ -54,11 +54,29 @@ int main(int argc, const char* argv[]) return 1; } - Debug_DisablePhase("Load Repository"); - Debug_DisablePhase("Load Root"); - Debug_DisablePhase("Load Dependencies"); - Debug_DisablePhase("Enumerate Build"); - //Debug_DisablePhase("Run Build"); + { + Debug_DisablePhase("Load Repository"); + Debug_DisablePhase("Load Root"); + Debug_DisablePhase("Load Dependencies"); + Debug_DisablePhase("Enumerate Build"); + Debug_DisablePhase("Run Build"); + + if( const char* e = getenv("MINICARGO_DEBUG") ) + { + while( *e ) + { + const char* colon = ::std::strchr(e, ':'); + size_t len = colon ? colon - e : ::std::strlen(e); + + Debug_EnablePhase(::std::string(e, len).c_str()); + + if( colon ) + e = colon + 1; + else + e = e + len; + } + } + } try { -- cgit v1.2.3 From 134be5198993096ab5216b6d52a8937430c733b0 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 20 May 2018 16:16:30 +0800 Subject: TestRunner - Don't pass -L when there's no dependencies --- tools/testrunner/main.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'tools') diff --git a/tools/testrunner/main.cpp b/tools/testrunner/main.cpp index 63391fc5..c83c9f32 100644 --- a/tools/testrunner/main.cpp +++ b/tools/testrunner/main.cpp @@ -336,6 +336,12 @@ int main(int argc, const char* argv[]) continue; } + // If there's no pre-build files (dependencies), clear the dependency path (cleaner output) + if( test.m_pre_build.empty() ) + { + depdir = ::helpers::path(); + } + auto compile_logfile = outdir / test.m_name + "-build.log"; if( !run_compiler(test.m_path, outfile, test.m_extra_flags, depdir) ) { @@ -355,6 +361,13 @@ int main(int argc, const char* argv[]) if( !run_executable(outfile, { outfile.str().c_str() }, run_out_file) ) { DEBUG("RUN FAIL " << test.m_name); + + // Move the failing output file + auto fail_file = run_out_file + "_failed"; + remove(fail_file.str().c_str()); + rename(run_out_file.str().c_str(), fail_file.str().c_str()); + DEBUG("- Output in " << fail_file); + n_fail ++; if( opts.fail_fast ) return 1; -- cgit v1.2.3 From def6cf31fff577776692027706fa3a3aa8bc29b3 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 2 Jun 2018 17:53:44 +0800 Subject: Minicargo - Tweaked error reporting --- tools/minicargo/build.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'tools') diff --git a/tools/minicargo/build.cpp b/tools/minicargo/build.cpp index 392e6a64..79a3dcff 100644 --- a/tools/minicargo/build.cpp +++ b/tools/minicargo/build.cpp @@ -1008,8 +1008,8 @@ bool Builder::spawn_process(const char* exe_name, const StringList& args, const if( posix_spawn(&pid, exe_name, &fa, /*attr=*/nullptr, (char* const*)argv.data(), (char* const*)envp.get_vec().data()) != 0 ) { - perror("posix_spawn"); - DEBUG("Unable to spawn compiler"); + ::std::cerr << "Unable to run process '" << exe_name << "' - " << strerror(errno) << ::std::endl; + DEBUG("Unable to spawn executable"); posix_spawn_file_actions_destroy(&fa); return false; } -- cgit v1.2.3 From 2dcdcf9dec83505dde64d21ff7b35ac16c1cccce Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sat, 2 Jun 2018 20:51:23 +0800 Subject: minicargo - Rough OSX support --- tools/minicargo/build.cpp | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) (limited to 'tools') diff --git a/tools/minicargo/build.cpp b/tools/minicargo/build.cpp index 79a3dcff..21d8d809 100644 --- a/tools/minicargo/build.cpp +++ b/tools/minicargo/build.cpp @@ -42,9 +42,16 @@ extern int _putenv_s(const char*, const char*); # include # include #endif +#ifdef __APPLE__ +# include +#endif #ifdef _WIN32 # define EXESUF ".exe" +#else +# define EXESUF "" +#endif +#ifdef _WIN32 # ifdef _MSC_VER # define HOST_TARGET "x86_64-windows-msvc" # elif defined(__MINGW32__) @@ -52,10 +59,8 @@ extern int _putenv_s(const char*, const char*); # else # endif #elif defined(__NetBSD__) -# define EXESUF "" # define HOST_TARGET "x86_64-unknown-netbsd" #else -# define EXESUF "" # define HOST_TARGET "x86_64-unknown-linux-gnu" #endif @@ -549,12 +554,32 @@ Builder::Builder(BuildOptions opts): #ifdef __MINGW32__ m_compiler_path = (minicargo_path / "..\\..\\bin\\mrustc.exe").normalise(); #else + // MSVC, minicargo and mrustc are in the same dir m_compiler_path = minicargo_path / "mrustc.exe"; #endif #else char buf[1024]; - size_t s = readlink("/proc/self/exe", buf, sizeof(buf)-1); - buf[s] = 0; +# ifdef __linux__ + ssize_t s = readlink("/proc/self/exe", buf, sizeof(buf)-1); + if(s >= 0) + { + buf[s] = 0; + } + else +#elif defined(__APPLE__) + uint32_t s = sizeof(buf); + if( _NSGetExecutablePath(buf, &s) == 0 ) + { + // Buffer populated + } + else + // TODO: Buffer too small +#else +# warning "Can't runtime determine path to minicargo" +#endif + { + strcpy(buf, "tools/bin/minicargo"); + } ::helpers::path minicargo_path { buf }; minicargo_path.pop_component(); -- cgit v1.2.3 From 1e8435aa1506c7a77a5748b67a7ff1a1d25e4fb2 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 3 Jun 2018 11:06:18 +0800 Subject: Testrunner - Fix compilation on OSX, add optimisation and debuginfo --- tools/testrunner/main.cpp | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'tools') diff --git a/tools/testrunner/main.cpp b/tools/testrunner/main.cpp index c83c9f32..f21dc7fa 100644 --- a/tools/testrunner/main.cpp +++ b/tools/testrunner/main.cpp @@ -93,6 +93,11 @@ bool run_compiler(const ::helpers::path& source_file, const ::helpers::path& out { ::std::vector args; args.push_back("mrustc"); + + // Force optimised and debuggable + args.push_back("-O"); + args.push_back("-g"); + args.push_back("-L"); args.push_back("output"); if(libdir.is_valid()) @@ -374,6 +379,14 @@ int main(int argc, const char* argv[]) else continue; } + +#ifdef __linux__ + // Run `strip` on the test (if on linux) + // XXX: Make this cleaner, or remove the need for it (by dynamic linking libstd) + if( !run_executable("/usr/bin/strip", { "strip", outfile.str().c_str() }, "/dev/null") ) + { + } +#endif } else { @@ -541,10 +554,11 @@ bool run_executable(const ::helpers::path& exe_name, const ::std::vector(argv.data()), environ); if( rv != 0 ) { - DEBUG("Error in posix_spawn - " << rv); + DEBUG("Error in posix_spawn of " << exe_name << " - " << rv); return false; } -- cgit v1.2.3 From 45023a8b4916de02a77abe23e2a800fc1d2e1d6a Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 3 Jun 2018 12:10:54 +0800 Subject: All - Move host target auto-detection to be common between compiler and minicargo --- src/main.cpp | 66 +++----------------------------------------- tools/common/target_detect.h | 66 ++++++++++++++++++++++++++++++++++++++++++++ tools/minicargo/build.cpp | 14 ++-------- tools/minicargo/manifest.cpp | 2 +- 4 files changed, 73 insertions(+), 75 deletions(-) create mode 100644 tools/common/target_detect.h (limited to 'tools') diff --git a/src/main.cpp b/src/main.cpp index ca55d6ba..358de95e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -26,65 +26,7 @@ #include "trans/target.hpp" #include "expand/cfg.hpp" - -// Hacky default target detection -// - Windows (MSVC) -#ifdef _MSC_VER -# if defined(_WIN64) -# define DEFAULT_TARGET_NAME "x86_64-windows-msvc" -# else -# define DEFAULT_TARGET_NAME "x86-windows-msvc" -# endif -// - Linux -#elif defined(__linux__) -# if defined(__amd64__) -# define DEFAULT_TARGET_NAME "x86_64-linux-gnu" -# elif defined(__aarch64__) -# define DEFAULT_TARGET_NAME "aarch64-linux-gnu" -# elif defined(__arm__) -# define DEFAULT_TARGET_NAME "arm-linux-gnu" -# elif defined(__i386__) -# define DEFAULT_TARGET_NAME "i586-linux-gnu" -# else -# warning "Unable to detect a suitable default target (linux-gnu)" -# endif -// - MinGW -#elif defined(__MINGW32__) -# if defined(_WIN64) -# define DEFAULT_TARGET_NAME "x86_64-windows-gnu" -# else -# define DEFAULT_TARGET_NAME "i586-windows-gnu" -# endif -// - NetBSD -#elif defined(__NetBSD__) -# if defined(__amd64__) -# define DEFAULT_TARGET_NAME "x86_64-unknown-netbsd" -# else -# warning "Unable to detect a suitable default target (NetBSD)" -# endif -// - OpenBSD -#elif defined(__OpenBSD__) -# if defined(__amd64__) -# define DEFAULT_TARGET_NAME "x86_64-unknown-openbsd" -# elif defined(__aarch64__) -# define DEFAULT_TARGET_NAME "aarch64-unknown-openbsd" -# elif defined(__arm__) -# define DEFAULT_TARGET_NAME "arm-unknown-openbsd" -# elif defined(__i386__) -# define DEFAULT_TARGET_NAME "i686-unknown-openbsd" -# else -# warning "Unable to detect a suitable default target (OpenBSD)" -# endif -// - Apple devices -#elif defined(__APPLE__) -# define DEFAULT_TARGET_NAME "x86_64-apple-macosx" -// - Unknown -#else -# warning "Unable to detect a suitable default target" -#endif -#ifndef DEFAULT_TARGET_NAME -# define DEFAULT_TARGET_NAME "" -#endif +#include // tools/common/target_detect.h int g_debug_indent_level = 0; bool g_debug_enabled = true; @@ -929,7 +871,7 @@ ProgramParams::ProgramParams(int argc, char *argv[]) } else if( optname == "dump-hir" ) { no_optval(); - this->debug.dump_mir = true; + this->debug.dump_hir = true; } else if( optname == "dump-mir" ) { no_optval(); @@ -943,10 +885,10 @@ ProgramParams::ProgramParams(int argc, char *argv[]) this->last_stage = STAGE_EXPAND; else if( optval == "resolve" ) this->last_stage = STAGE_RESOLVE; + else if( optval == "typeck" ) + this->last_stage = STAGE_TYPECK; else if( optval == "mir" ) this->last_stage = STAGE_MIR; - else if( optval == "ALL" ) - this->last_stage = STAGE_ALL; else { ::std::cerr << "Unknown argument to -Z stop-after - '" << optval << "'" << ::std::endl; exit(1); diff --git a/tools/common/target_detect.h b/tools/common/target_detect.h new file mode 100644 index 00000000..995ab6a4 --- /dev/null +++ b/tools/common/target_detect.h @@ -0,0 +1,66 @@ +/* + * MRustC - Rust Compiler + * - By John Hodge (Mutabah/thePowersGang) + * + * common/target_detect.h + * - Auto-magical host target detection + */ +#pragma once + +// - Windows (MSVC) +#ifdef _MSC_VER +# if defined(_WIN64) +# define DEFAULT_TARGET_NAME "x86_64-windows-msvc" +# else +# define DEFAULT_TARGET_NAME "x86-windows-msvc" +# endif +// - Linux +#elif defined(__linux__) +# if defined(__amd64__) +# define DEFAULT_TARGET_NAME "x86_64-linux-gnu" +# elif defined(__aarch64__) +# define DEFAULT_TARGET_NAME "aarch64-linux-gnu" +# elif defined(__arm__) +# define DEFAULT_TARGET_NAME "arm-linux-gnu" +# elif defined(__i386__) +# define DEFAULT_TARGET_NAME "i586-linux-gnu" +# else +# warning "Unable to detect a suitable default target (linux-gnu)" +# endif +// - MinGW +#elif defined(__MINGW32__) +# if defined(_WIN64) +# define DEFAULT_TARGET_NAME "x86_64-windows-gnu" +# else +# define DEFAULT_TARGET_NAME "i586-windows-gnu" +# endif +// - NetBSD +#elif defined(__NetBSD__) +# if defined(__amd64__) +# define DEFAULT_TARGET_NAME "x86_64-unknown-netbsd" +# else +# warning "Unable to detect a suitable default target (NetBSD)" +# endif +// - OpenBSD +#elif defined(__OpenBSD__) +# if defined(__amd64__) +# define DEFAULT_TARGET_NAME "x86_64-unknown-openbsd" +# elif defined(__aarch64__) +# define DEFAULT_TARGET_NAME "aarch64-unknown-openbsd" +# elif defined(__arm__) +# define DEFAULT_TARGET_NAME "arm-unknown-openbsd" +# elif defined(__i386__) +# define DEFAULT_TARGET_NAME "i686-unknown-openbsd" +# else +# warning "Unable to detect a suitable default target (OpenBSD)" +# endif +// - Apple devices +#elif defined(__APPLE__) +# define DEFAULT_TARGET_NAME "x86_64-apple-macosx" +// - Unknown +#else +# warning "Unable to detect a suitable default target" +#endif +#ifndef DEFAULT_TARGET_NAME +# define DEFAULT_TARGET_NAME "" +#endif diff --git a/tools/minicargo/build.cpp b/tools/minicargo/build.cpp index 21d8d809..42e19552 100644 --- a/tools/minicargo/build.cpp +++ b/tools/minicargo/build.cpp @@ -51,18 +51,8 @@ extern int _putenv_s(const char*, const char*); #else # define EXESUF "" #endif -#ifdef _WIN32 -# ifdef _MSC_VER -# define HOST_TARGET "x86_64-windows-msvc" -# elif defined(__MINGW32__) -# define HOST_TARGET "x86_64-windows-gnu" -# else -# endif -#elif defined(__NetBSD__) -# define HOST_TARGET "x86_64-unknown-netbsd" -#else -# define HOST_TARGET "x86_64-unknown-linux-gnu" -#endif +#include // tools/common/target_detect.h +#define HOST_TARGET DEFAULT_TARGET_NAME /// Class abstracting access to the compiler class Builder diff --git a/tools/minicargo/manifest.cpp b/tools/minicargo/manifest.cpp index 6e2bf451..687c3e2a 100644 --- a/tools/minicargo/manifest.cpp +++ b/tools/minicargo/manifest.cpp @@ -9,7 +9,7 @@ #include // toupper #include "repository.h" - +// TODO: Extract this from the target at runtime #ifdef _WIN32 # define TARGET_NAME "i586-windows-msvc" # define CFG_UNIX false -- cgit v1.2.3 From ada4bdefc7da9c81e0006553f218efe56a4349ce Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 3 Jun 2018 13:06:12 +0800 Subject: Standalone MIRI - Fix parse errors from mrustc changes, add recursion limit --- test_smiri.sh | 1 + tools/standalone_miri/debug.cpp | 3 ++- tools/standalone_miri/debug.hpp | 2 +- tools/standalone_miri/lex.cpp | 25 +++++++++++++++++++++++-- tools/standalone_miri/lex.hpp | 1 + tools/standalone_miri/main.cpp | 23 ++++++++++++++++++++++- tools/standalone_miri/miri.cpp | 22 ++++++++++++++++++---- tools/standalone_miri/module_tree.cpp | 18 +++++++++++++++--- 8 files changed, 83 insertions(+), 12 deletions(-) (limited to 'tools') diff --git a/test_smiri.sh b/test_smiri.sh index 0dbad3fa..a275420a 100755 --- a/test_smiri.sh +++ b/test_smiri.sh @@ -2,6 +2,7 @@ set -e cd $(dirname $0) make -f minicargo.mk MMIR=1 LIBS +make -C tools/standalone_miri echo "--- mrustc -o output-mmir/hello" ./bin/mrustc rustc-1.19.0-src/src/test/run-pass/hello.rs -O -C codegen-type=monomir -o output-mmir/hello -L output-mmir/ > output-mmir/hello_dbg.txt echo "--- standalone_miri output-mmir/hello.mir" diff --git a/tools/standalone_miri/debug.cpp b/tools/standalone_miri/debug.cpp index f0476df7..c49df960 100644 --- a/tools/standalone_miri/debug.cpp +++ b/tools/standalone_miri/debug.cpp @@ -18,8 +18,9 @@ DebugSink::DebugSink(::std::ostream& inner): DebugSink::~DebugSink() { m_inner << "\n"; + m_inner.flush(); } -bool DebugSink::set_output_file(const ::std::string& s) +void DebugSink::set_output_file(const ::std::string& s) { s_out_file.reset(new ::std::ofstream(s)); } diff --git a/tools/standalone_miri/debug.hpp b/tools/standalone_miri/debug.hpp index 6b136ccb..b3b0d76f 100644 --- a/tools/standalone_miri/debug.hpp +++ b/tools/standalone_miri/debug.hpp @@ -33,7 +33,7 @@ public: template ::std::ostream& operator<<(const T& v) { return m_inner << v; } - static bool set_output_file(const ::std::string& s); + static void set_output_file(const ::std::string& s); static bool enabled(const char* fcn_name); static DebugSink get(const char* fcn_name, const char* file, unsigned line, DebugLevel lvl); // TODO: Add a way to insert an annotation before/after an abort/warning/... that indicates what input location caused it. diff --git a/tools/standalone_miri/lex.cpp b/tools/standalone_miri/lex.cpp index 7cfe1a78..8fc77f7a 100644 --- a/tools/standalone_miri/lex.cpp +++ b/tools/standalone_miri/lex.cpp @@ -11,11 +11,11 @@ bool Token::operator==(TokenClass tc) const } bool Token::operator==(char c) const { - return this->strval.size() == 1 && this->strval[0] == c; + return (this->type == TokenClass::Ident || this->type == TokenClass::Symbol) && this->strval.size() == 1 && this->strval[0] == c; } bool Token::operator==(const char* s) const { - return this->strval == s; + return (this->type == TokenClass::Ident || this->type == TokenClass::Symbol) && this->strval == s; } uint64_t Token::integer() const @@ -56,6 +56,9 @@ double Token::real() const case TokenClass::ByteString: os << "b\"" << x.strval << "\""; break; + case TokenClass::Lifetime: + os << "'" << x.strval << "\""; + break; } return os; } @@ -95,6 +98,7 @@ Token Lexer::consume() auto rv = ::std::move(m_cur); advance(); + //::std::cout << *this << "Lexer::consume " << rv << " -> " << m_cur << ::std::endl; return rv; } @@ -349,6 +353,23 @@ void Lexer::advance() auto val = this->parse_string(); m_cur = Token { TokenClass::String, ::std::move(val) }; } + else if( ch == '\'') + { + ::std::string val; + ch = m_if.get(); + while( ch == '_' || ::std::isalnum(ch) ) + { + val += ch; + ch = m_if.get(); + } + m_if.unget(); + if( val == "" ) + { + ::std::cerr << *this << "Empty lifetime name"; + throw "ERROR"; + } + m_cur = Token { TokenClass::Lifetime, ::std::move(val) }; + } else { switch(ch) diff --git a/tools/standalone_miri/lex.hpp b/tools/standalone_miri/lex.hpp index 95130111..cc1429f7 100644 --- a/tools/standalone_miri/lex.hpp +++ b/tools/standalone_miri/lex.hpp @@ -14,6 +14,7 @@ enum class TokenClass Real, String, ByteString, + Lifetime, }; struct Token diff --git a/tools/standalone_miri/main.cpp b/tools/standalone_miri/main.cpp index 90b5eff3..deed08be 100644 --- a/tools/standalone_miri/main.cpp +++ b/tools/standalone_miri/main.cpp @@ -48,7 +48,28 @@ int main(int argc, const char* argv[]) // Load HIR tree auto tree = ModuleTree {}; - tree.load_file(opts.infile); + try + { + tree.load_file(opts.infile); + } + catch(const DebugExceptionTodo& /*e*/) + { + ::std::cerr << "TODO Hit" << ::std::endl; + if(opts.logfile != "") + { + ::std::cerr << "- See '" << opts.logfile << "' for details" << ::std::endl; + } + return 1; + } + catch(const DebugExceptionError& /*e*/) + { + ::std::cerr << "Error encountered" << ::std::endl; + if(opts.logfile != "") + { + ::std::cerr << "- See '" << opts.logfile << "' for details" << ::std::endl; + } + return 1; + } // Create argc/argv based on input arguments auto argv_alloc = Allocation::new_alloc((1 + opts.args.size()) * POINTER_SIZE); diff --git a/tools/standalone_miri/miri.cpp b/tools/standalone_miri/miri.cpp index 5f9c095f..f4179b5d 100644 --- a/tools/standalone_miri/miri.cpp +++ b/tools/standalone_miri/miri.cpp @@ -540,11 +540,19 @@ InterpreterThread::~InterpreterThread() for(size_t i = 0; i < m_stack.size(); i++) { const auto& frame = m_stack[m_stack.size() - 1 - i]; - ::std::cout << "#" << i << ": " << frame.fcn.my_path << " BB" << frame.bb_idx << "/"; - if( frame.stmt_idx == frame.fcn.m_mir.blocks.at(frame.bb_idx).statements.size() ) - ::std::cout << "TERM"; + ::std::cout << "#" << i << ": "; + if( frame.cb ) + { + ::std::cout << "WRAPPER"; + } else - ::std::cout << frame.stmt_idx; + { + ::std::cout << frame.fcn.my_path << " BB" << frame.bb_idx << "/"; + if( frame.stmt_idx == frame.fcn.m_mir.blocks.at(frame.bb_idx).statements.size() ) + ::std::cout << "TERM"; + else + ::std::cout << frame.stmt_idx; + } ::std::cout << ::std::endl; } } @@ -565,6 +573,12 @@ bool InterpreterThread::step_one(Value& out_thread_result) TRACE_FUNCTION_R(cur_frame.fcn.my_path, ""); const auto& bb = cur_frame.fcn.m_mir.blocks.at( cur_frame.bb_idx ); + const size_t MAX_STACK_DEPTH = 40; + if( this->m_stack.size() > MAX_STACK_DEPTH ) + { + LOG_ERROR("Maximum stack depth of " << MAX_STACK_DEPTH << " exceeded"); + } + MirHelpers state { *this, cur_frame }; if( cur_frame.stmt_idx < bb.statements.size() ) diff --git a/tools/standalone_miri/module_tree.cpp b/tools/standalone_miri/module_tree.cpp index db5fd495..8beba018 100644 --- a/tools/standalone_miri/module_tree.cpp +++ b/tools/standalone_miri/module_tree.cpp @@ -56,7 +56,7 @@ void ModuleTree::load_file(const ::std::string& path) bool Parser::parse_one() { //TRACE_FUNCTION_F(""); - if( lex.next() == "" ) // EOF? + if( lex.next() == TokenClass::Eof ) { return false; } @@ -1145,6 +1145,11 @@ RawType Parser::parse_core_type() } else if( lex.consume_if('&') ) { + if( lex.next() == TokenClass::Lifetime ) + { + // TODO: Handle lifetime names (require them?) + lex.consume(); + } auto bt = ::HIR::BorrowType::Shared; if( lex.consume_if("move") ) bt = ::HIR::BorrowType::Move; @@ -1240,8 +1245,15 @@ RawType Parser::parse_core_type() ::std::vector<::HIR::GenericPath> markers; while(lex.consume_if('+')) { - // TODO: Detect/parse lifetimes? - markers.push_back(parse_genericpath()); + if( lex.next() == TokenClass::Lifetime ) + { + // TODO: Include lifetimes in output? + lex.consume(); + } + else + { + markers.push_back(parse_genericpath()); + } } lex.consume_if(')'); -- cgit v1.2.3 From a7fb27789a2b34543851d207120e2c0001ee9c27 Mon Sep 17 00:00:00 2001 From: John Hodge Date: Sun, 3 Jun 2018 14:49:07 +0800 Subject: Toml - Slightly better commenting --- tools/common/toml.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'tools') diff --git a/tools/common/toml.cpp b/tools/common/toml.cpp index 9fad0ec4..75a93810 100644 --- a/tools/common/toml.cpp +++ b/tools/common/toml.cpp @@ -170,9 +170,11 @@ TomlKeyValue TomlFile::get_next_value() throw ::std::runtime_error(::format("Unexpected token after key - ", t)); t = Token::lex_from(m_if); + // --- Value --- TomlKeyValue rv; switch(t.m_type) { + // String: Return the string value case Token::Type::String: rv.path = m_current_block; rv.path.insert(rv.path.end(), m_current_composite.begin(), m_current_composite.end()); @@ -180,6 +182,7 @@ TomlKeyValue TomlFile::get_next_value() rv.value = TomlValue { t.m_data }; break; + // Array: Parse the entire list and return as Type::List case Token::Type::SquareOpen: rv.path = m_current_block; rv.path.insert(rv.path.end(), m_current_composite.begin(), m_current_composite.end()); @@ -193,7 +196,8 @@ TomlKeyValue TomlFile::get_next_value() if( t.m_type == Token::Type::SquareClose ) break; - // TODO: Recurse parse a value + // TODO: Recursively parse a value + // TODO: OR, support other value types switch(t.m_type) { case Token::Type::String: -- cgit v1.2.3