diff options
Diffstat (limited to 'src')
135 files changed, 334 insertions, 13193 deletions
diff --git a/src/apply-names.cc b/src/apply-names.cc index d0958b7d..506ab1fe 100644 --- a/src/apply-names.cc +++ b/src/apply-names.cc @@ -14,16 +14,16 @@ * limitations under the License. */ -#include "src/apply-names.h" +#include "wabt/apply-names.h" #include <cassert> #include <cstdio> #include <string_view> #include <vector> -#include "src/cast.h" -#include "src/expr-visitor.h" -#include "src/ir.h" +#include "wabt/cast.h" +#include "wabt/expr-visitor.h" +#include "wabt/ir.h" namespace wabt { diff --git a/src/apply-names.h b/src/apply-names.h deleted file mode 100644 index 1837c370..00000000 --- a/src/apply-names.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_APPLY_NAMES_H_ -#define WABT_APPLY_NAMES_H_ - -#include "src/common.h" - -namespace wabt { - -struct Module; - -/* Use function, import, function type, parameter and local names in Vars - * that reference them. - * - * e.g. transform this: - * - * (func $foo ...) - * ... - * (call 0 ...) - * - * to this: - * - * (func $foo ...) - * ... - * (call $foo ...) - */ -Result ApplyNames(struct Module*); - -} // namespace wabt - -#endif /* WABT_APPLY_NAMES_H_ */ diff --git a/src/base-types.h b/src/base-types.h deleted file mode 100644 index dbf37700..00000000 --- a/src/base-types.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2021 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BASE_TYPES_H_ -#define WABT_BASE_TYPES_H_ - -#include <stddef.h> -#include <stdint.h> - -namespace wabt { - -typedef uint32_t Index; // An index into one of the many index spaces. -typedef uint64_t Address; // An address or size in linear memory. -typedef size_t Offset; // An offset into a host's file or memory buffer. - -static const Address kInvalidAddress = ~0; -static const Index kInvalidIndex = ~0; -static const Offset kInvalidOffset = ~0; - -} // namespace wabt - -#endif // WABT_BASE_TYPES_H_ diff --git a/src/binary-reader-ir.cc b/src/binary-reader-ir.cc index 859293ec..3f64157d 100644 --- a/src/binary-reader-ir.cc +++ b/src/binary-reader-ir.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/binary-reader-ir.h" +#include "wabt/binary-reader-ir.h" #include <cassert> #include <cinttypes> @@ -24,10 +24,10 @@ #include <deque> #include <vector> -#include "src/binary-reader-nop.h" -#include "src/cast.h" -#include "src/common.h" -#include "src/ir.h" +#include "wabt/binary-reader-nop.h" +#include "wabt/cast.h" +#include "wabt/common.h" +#include "wabt/ir.h" namespace wabt { diff --git a/src/binary-reader-ir.h b/src/binary-reader-ir.h deleted file mode 100644 index 18c15585..00000000 --- a/src/binary-reader-ir.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_READER_IR_H_ -#define WABT_BINARY_READER_IR_H_ - -#include "src/common.h" -#include "src/error.h" - -namespace wabt { - -struct Module; -struct ReadBinaryOptions; - -Result ReadBinaryIr(const char* filename, - const void* data, - size_t size, - const ReadBinaryOptions& options, - Errors*, - Module* out_module); - -} // namespace wabt - -#endif /* WABT_BINARY_READER_IR_H_ */ diff --git a/src/binary-reader-logging.cc b/src/binary-reader-logging.cc index 0f885e45..e6241093 100644 --- a/src/binary-reader-logging.cc +++ b/src/binary-reader-logging.cc @@ -14,11 +14,11 @@ * limitations under the License. */ -#include "src/binary-reader-logging.h" +#include "wabt/binary-reader-logging.h" #include <cinttypes> -#include "src/stream.h" +#include "wabt/stream.h" namespace wabt { diff --git a/src/binary-reader-logging.h b/src/binary-reader-logging.h deleted file mode 100644 index c5176bdf..00000000 --- a/src/binary-reader-logging.h +++ /dev/null @@ -1,424 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_READER_LOGGING_H_ -#define WABT_BINARY_READER_LOGGING_H_ - -#include "src/binary-reader.h" - -namespace wabt { - -class Stream; - -class BinaryReaderLogging : public BinaryReaderDelegate { - public: - BinaryReaderLogging(Stream*, BinaryReaderDelegate* forward); - - bool OnError(const Error&) override; - void OnSetState(const State* s) override; - - Result BeginModule(uint32_t version) override; - Result EndModule() override; - - Result BeginSection(Index section_index, - BinarySection section_type, - Offset size) override; - - Result BeginCustomSection(Index section_index, - Offset size, - std::string_view section_name) override; - Result EndCustomSection() override; - - Result BeginTypeSection(Offset size) override; - Result OnTypeCount(Index count) override; - Result OnFuncType(Index index, - Index param_count, - Type* param_types, - Index result_count, - Type* result_types) override; - Result OnStructType(Index index, Index field_count, TypeMut* fields) override; - Result OnArrayType(Index index, TypeMut field) override; - Result EndTypeSection() override; - - Result BeginImportSection(Offset size) override; - Result OnImportCount(Index count) override; - Result OnImport(Index index, - ExternalKind kind, - std::string_view module_name, - std::string_view field_name) override; - Result OnImportFunc(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index func_index, - Index sig_index) override; - Result OnImportTable(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index table_index, - Type elem_type, - const Limits* elem_limits) override; - Result OnImportMemory(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index memory_index, - const Limits* page_limits) override; - Result OnImportGlobal(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index global_index, - Type type, - bool mutable_) override; - Result OnImportTag(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index tag_index, - Index sig_index) override; - Result EndImportSection() override; - - Result BeginFunctionSection(Offset size) override; - Result OnFunctionCount(Index count) override; - Result OnFunction(Index index, Index sig_index) override; - Result EndFunctionSection() override; - - Result BeginTableSection(Offset size) override; - Result OnTableCount(Index count) override; - Result OnTable(Index index, - Type elem_type, - const Limits* elem_limits) override; - Result EndTableSection() override; - - Result BeginMemorySection(Offset size) override; - Result OnMemoryCount(Index count) override; - Result OnMemory(Index index, const Limits* limits) override; - Result EndMemorySection() override; - - Result BeginGlobalSection(Offset size) override; - Result OnGlobalCount(Index count) override; - Result BeginGlobal(Index index, Type type, bool mutable_) override; - Result BeginGlobalInitExpr(Index index) override; - Result EndGlobalInitExpr(Index index) override; - Result EndGlobal(Index index) override; - Result EndGlobalSection() override; - - Result BeginExportSection(Offset size) override; - Result OnExportCount(Index count) override; - Result OnExport(Index index, - ExternalKind kind, - Index item_index, - std::string_view name) override; - Result EndExportSection() override; - - Result BeginStartSection(Offset size) override; - Result OnStartFunction(Index func_index) override; - Result EndStartSection() override; - - Result BeginCodeSection(Offset size) override; - Result OnFunctionBodyCount(Index count) override; - Result BeginFunctionBody(Index index, Offset size) override; - Result OnLocalDeclCount(Index count) override; - Result OnLocalDecl(Index decl_index, Index count, Type type) override; - - Result OnOpcode(Opcode opcode) override; - Result OnOpcodeBare() override; - Result OnOpcodeIndex(Index value) override; - Result OnOpcodeIndexIndex(Index value, Index value2) override; - Result OnOpcodeUint32(uint32_t value) override; - Result OnOpcodeUint32Uint32(uint32_t value, uint32_t value2) override; - Result OnOpcodeUint32Uint32Uint32(uint32_t value, - uint32_t value2, - uint32_t value3) override; - Result OnOpcodeUint32Uint32Uint32Uint32(uint32_t value, - uint32_t value2, - uint32_t value3, - uint32_t value4) override; - Result OnOpcodeUint64(uint64_t value) override; - Result OnOpcodeF32(uint32_t value) override; - Result OnOpcodeF64(uint64_t value) override; - Result OnOpcodeV128(v128 value) override; - Result OnOpcodeBlockSig(Type sig_type) override; - Result OnOpcodeType(Type type) override; - Result OnAtomicLoadExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result OnAtomicStoreExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result OnAtomicRmwExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result OnAtomicRmwCmpxchgExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result OnBinaryExpr(Opcode opcode) override; - Result OnBlockExpr(Type sig_type) override; - Result OnBrExpr(Index depth) override; - Result OnBrIfExpr(Index depth) override; - Result OnBrTableExpr(Index num_targets, - Index* target_depths, - Index default_target_depth) override; - Result OnCallExpr(Index func_index) override; - Result OnCatchExpr(Index tag_index) override; - Result OnCatchAllExpr() override; - Result OnCallIndirectExpr(Index sig_index, Index table_index) override; - Result OnCallRefExpr() override; - Result OnCompareExpr(Opcode opcode) override; - Result OnConvertExpr(Opcode opcode) override; - Result OnDelegateExpr(Index depth) override; - Result OnDropExpr() override; - Result OnElseExpr() override; - Result OnEndExpr() override; - Result OnF32ConstExpr(uint32_t value_bits) override; - Result OnF64ConstExpr(uint64_t value_bits) override; - Result OnV128ConstExpr(v128 value_bits) override; - Result OnGlobalGetExpr(Index global_index) override; - Result OnGlobalSetExpr(Index global_index) override; - Result OnI32ConstExpr(uint32_t value) override; - Result OnI64ConstExpr(uint64_t value) override; - Result OnIfExpr(Type sig_type) override; - Result OnLoadExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result OnLocalGetExpr(Index local_index) override; - Result OnLocalSetExpr(Index local_index) override; - Result OnLocalTeeExpr(Index local_index) override; - Result OnLoopExpr(Type sig_type) override; - Result OnMemoryCopyExpr(Index srcmemidx, Index destmemidx) override; - Result OnDataDropExpr(Index segment_index) override; - Result OnMemoryFillExpr(Index memidx) override; - Result OnMemoryGrowExpr(Index memidx) override; - Result OnMemoryInitExpr(Index segment_index, Index memidx) override; - Result OnMemorySizeExpr(Index memidx) override; - Result OnTableCopyExpr(Index dst_index, Index src_index) override; - Result OnElemDropExpr(Index segment_index) override; - Result OnTableInitExpr(Index segment_index, Index table_index) override; - Result OnTableGetExpr(Index table) override; - Result OnTableSetExpr(Index table) override; - Result OnTableGrowExpr(Index table) override; - Result OnTableSizeExpr(Index table) override; - Result OnTableFillExpr(Index table) override; - Result OnRefFuncExpr(Index index) override; - Result OnRefNullExpr(Type type) override; - Result OnRefIsNullExpr() override; - Result OnNopExpr() override; - Result OnRethrowExpr(Index depth) override; - Result OnReturnCallExpr(Index func_index) override; - Result OnReturnCallIndirectExpr(Index sig_index, Index table_index) override; - Result OnReturnExpr() override; - Result OnSelectExpr(Index result_count, Type* result_types) override; - Result OnStoreExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result OnThrowExpr(Index tag_index) override; - Result OnTryExpr(Type sig_type) override; - Result OnUnaryExpr(Opcode opcode) override; - Result OnTernaryExpr(Opcode opcode) override; - Result OnUnreachableExpr() override; - Result OnAtomicWaitExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result OnAtomicFenceExpr(uint32_t consistency_model) override; - Result OnAtomicNotifyExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result EndFunctionBody(Index index) override; - Result EndCodeSection() override; - Result OnSimdLaneOpExpr(Opcode opcode, uint64_t value) override; - Result OnSimdLoadLaneExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset, - uint64_t value) override; - Result OnSimdStoreLaneExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset, - uint64_t value) override; - Result OnSimdShuffleOpExpr(Opcode opcode, v128 value) override; - Result OnLoadSplatExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - Result OnLoadZeroExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override; - - Result BeginElemSection(Offset size) override; - Result OnElemSegmentCount(Index count) override; - Result BeginElemSegment(Index index, - Index table_index, - uint8_t flags) override; - Result BeginElemSegmentInitExpr(Index index) override; - Result EndElemSegmentInitExpr(Index index) override; - Result OnElemSegmentElemType(Index index, Type elem_type) override; - Result OnElemSegmentElemExprCount(Index index, Index count) override; - Result OnElemSegmentElemExpr_RefNull(Index segment_index, Type type) override; - Result OnElemSegmentElemExpr_RefFunc(Index segment_index, - Index func_index) override; - Result EndElemSegment(Index index) override; - Result EndElemSection() override; - - Result BeginDataSection(Offset size) override; - Result OnDataSegmentCount(Index count) override; - Result BeginDataSegment(Index index, - Index memory_index, - uint8_t flags) override; - Result BeginDataSegmentInitExpr(Index index) override; - Result EndDataSegmentInitExpr(Index index) override; - Result OnDataSegmentData(Index index, - const void* data, - Address size) override; - Result EndDataSegment(Index index) override; - Result EndDataSection() override; - - Result BeginDataCountSection(Offset size) override; - Result OnDataCount(Index count) override; - Result EndDataCountSection() override; - - Result BeginNamesSection(Offset size) override; - Result OnModuleNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) override; - Result OnModuleName(std::string_view name) override; - Result OnFunctionNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) override; - Result OnFunctionNamesCount(Index num_functions) override; - Result OnFunctionName(Index function_index, - std::string_view function_name) override; - Result OnLocalNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) override; - Result OnLocalNameFunctionCount(Index num_functions) override; - Result OnLocalNameLocalCount(Index function_index, Index num_locals) override; - Result OnLocalName(Index function_index, - Index local_index, - std::string_view local_name) override; - Result OnNameSubsection(Index index, - NameSectionSubsection subsection_type, - Offset subsection_size) override; - Result OnNameEntry(NameSectionSubsection type, - Index index, - std::string_view name) override; - Result OnNameCount(Index num_names) override; - Result EndNamesSection() override; - - Result BeginRelocSection(Offset size) override; - Result OnRelocCount(Index count, Index section_index) override; - Result OnReloc(RelocType type, - Offset offset, - Index index, - uint32_t addend) override; - Result EndRelocSection() override; - - Result BeginDylinkSection(Offset size) override; - Result OnDylinkInfo(uint32_t mem_size, - uint32_t mem_align, - uint32_t table_size, - uint32_t table_align) override; - Result OnDylinkNeededCount(Index count) override; - Result OnDylinkNeeded(std::string_view needed) override; - Result OnDylinkImportCount(Index count) override; - Result OnDylinkExportCount(Index count) override; - Result OnDylinkImport(std::string_view module, - std::string_view name, - uint32_t flags) override; - Result OnDylinkExport(std::string_view name, uint32_t flags) override; - Result EndDylinkSection() override; - - Result BeginTargetFeaturesSection(Offset size) override; - Result OnFeatureCount(Index count) override; - Result OnFeature(uint8_t prefix, std::string_view name) override; - Result EndTargetFeaturesSection() override; - - Result BeginLinkingSection(Offset size) override; - Result OnSymbolCount(Index count) override; - Result OnDataSymbol(Index index, - uint32_t flags, - std::string_view name, - Index segment, - uint32_t offset, - uint32_t size) override; - Result OnFunctionSymbol(Index index, - uint32_t flags, - std::string_view name, - Index func_index) override; - Result OnGlobalSymbol(Index index, - uint32_t flags, - std::string_view name, - Index global_index) override; - Result OnSectionSymbol(Index index, - uint32_t flags, - Index section_index) override; - Result OnTagSymbol(Index index, - uint32_t flags, - std::string_view name, - Index tag_index) override; - Result OnTableSymbol(Index index, - uint32_t flags, - std::string_view name, - Index tag_index) override; - Result OnSegmentInfoCount(Index count) override; - Result OnSegmentInfo(Index index, - std::string_view name, - Address alignment, - uint32_t flags) override; - Result OnInitFunctionCount(Index count) override; - Result OnInitFunction(uint32_t priority, Index function_index) override; - Result OnComdatCount(Index count) override; - Result OnComdatBegin(std::string_view name, - uint32_t flags, - Index count) override; - Result OnComdatEntry(ComdatType kind, Index index) override; - Result EndLinkingSection() override; - - Result BeginTagSection(Offset size) override; - Result OnTagCount(Index count) override; - Result OnTagType(Index index, Index sig_index) override; - Result EndTagSection() override; - - /* Code Metadata sections */ - Result BeginCodeMetadataSection(std::string_view name, Offset size) override; - Result OnCodeMetadataFuncCount(Index count) override; - Result OnCodeMetadataCount(Index function_index, Index count) override; - Result OnCodeMetadata(Offset offset, const void* data, Address size) override; - Result EndCodeMetadataSection() override; - - private: - void Indent(); - void Dedent(); - void WriteIndent(); - void LogType(Type type); - void LogTypes(Index type_count, Type* types); - void LogTypes(TypeVector& types); - void LogField(TypeMut field); - - Stream* stream_; - BinaryReaderDelegate* reader_; - int indent_; -}; - -} // namespace wabt - -#endif // WABT_BINARY_READER_LOGGING_H_ diff --git a/src/binary-reader-nop.h b/src/binary-reader-nop.h deleted file mode 100644 index c8ee065f..00000000 --- a/src/binary-reader-nop.h +++ /dev/null @@ -1,589 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_READER_NOP_H_ -#define WABT_BINARY_READER_NOP_H_ - -#include "src/binary-reader.h" - -namespace wabt { - -class BinaryReaderNop : public BinaryReaderDelegate { - public: - bool OnError(const Error&) override { return false; } - - /* Module */ - Result BeginModule(uint32_t version) override { return Result::Ok; } - Result EndModule() override { return Result::Ok; } - - Result BeginSection(Index section_index, - BinarySection section_type, - Offset size) override { - return Result::Ok; - } - - /* Custom section */ - Result BeginCustomSection(Index section_index, - Offset size, - std::string_view section_name) override { - return Result::Ok; - } - Result EndCustomSection() override { return Result::Ok; } - - /* Type section */ - Result BeginTypeSection(Offset size) override { return Result::Ok; } - Result OnTypeCount(Index count) override { return Result::Ok; } - Result OnFuncType(Index index, - Index param_count, - Type* param_types, - Index result_count, - Type* result_types) override { - return Result::Ok; - } - Result OnStructType(Index index, - Index field_count, - TypeMut* fields) override { - return Result::Ok; - } - Result OnArrayType(Index index, TypeMut field) override { return Result::Ok; } - Result EndTypeSection() override { return Result::Ok; } - - /* Import section */ - Result BeginImportSection(Offset size) override { return Result::Ok; } - Result OnImportCount(Index count) override { return Result::Ok; } - Result OnImport(Index index, - ExternalKind kind, - std::string_view module_name, - std::string_view field_name) override { - return Result::Ok; - } - Result OnImportFunc(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index func_index, - Index sig_index) override { - return Result::Ok; - } - Result OnImportTable(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index table_index, - Type elem_type, - const Limits* elem_limits) override { - return Result::Ok; - } - Result OnImportMemory(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index memory_index, - const Limits* page_limits) override { - return Result::Ok; - } - Result OnImportGlobal(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index global_index, - Type type, - bool mutable_) override { - return Result::Ok; - } - Result OnImportTag(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index tag_index, - Index sig_index) override { - return Result::Ok; - } - Result EndImportSection() override { return Result::Ok; } - - /* Function section */ - Result BeginFunctionSection(Offset size) override { return Result::Ok; } - Result OnFunctionCount(Index count) override { return Result::Ok; } - Result OnFunction(Index index, Index sig_index) override { - return Result::Ok; - } - Result EndFunctionSection() override { return Result::Ok; } - - /* Table section */ - Result BeginTableSection(Offset size) override { return Result::Ok; } - Result OnTableCount(Index count) override { return Result::Ok; } - Result OnTable(Index index, - Type elem_type, - const Limits* elem_limits) override { - return Result::Ok; - } - Result EndTableSection() override { return Result::Ok; } - - /* Memory section */ - Result BeginMemorySection(Offset size) override { return Result::Ok; } - Result OnMemoryCount(Index count) override { return Result::Ok; } - Result OnMemory(Index index, const Limits* limits) override { - return Result::Ok; - } - Result EndMemorySection() override { return Result::Ok; } - - /* Global section */ - Result BeginGlobalSection(Offset size) override { return Result::Ok; } - Result OnGlobalCount(Index count) override { return Result::Ok; } - Result BeginGlobal(Index index, Type type, bool mutable_) override { - return Result::Ok; - } - Result BeginGlobalInitExpr(Index index) override { return Result::Ok; } - Result EndGlobalInitExpr(Index index) override { return Result::Ok; } - Result EndGlobal(Index index) override { return Result::Ok; } - Result EndGlobalSection() override { return Result::Ok; } - - /* Exports section */ - Result BeginExportSection(Offset size) override { return Result::Ok; } - Result OnExportCount(Index count) override { return Result::Ok; } - Result OnExport(Index index, - ExternalKind kind, - Index item_index, - std::string_view name) override { - return Result::Ok; - } - Result EndExportSection() override { return Result::Ok; } - - /* Start section */ - Result BeginStartSection(Offset size) override { return Result::Ok; } - Result OnStartFunction(Index func_index) override { return Result::Ok; } - Result EndStartSection() override { return Result::Ok; } - - /* Code section */ - Result BeginCodeSection(Offset size) override { return Result::Ok; } - Result OnFunctionBodyCount(Index count) override { return Result::Ok; } - Result BeginFunctionBody(Index index, Offset size) override { - return Result::Ok; - } - Result OnLocalDeclCount(Index count) override { return Result::Ok; } - Result OnLocalDecl(Index decl_index, Index count, Type type) override { - return Result::Ok; - } - - /* Function expressions; called between BeginFunctionBody and - EndFunctionBody */ - Result OnOpcode(Opcode Opcode) override { return Result::Ok; } - Result OnOpcodeBare() override { return Result::Ok; } - Result OnOpcodeIndex(Index value) override { return Result::Ok; } - Result OnOpcodeIndexIndex(Index value, Index value2) override { - return Result::Ok; - } - Result OnOpcodeUint32(uint32_t value) override { return Result::Ok; } - Result OnOpcodeUint32Uint32(uint32_t value, uint32_t value2) override { - return Result::Ok; - } - Result OnOpcodeUint32Uint32Uint32(uint32_t value, - uint32_t value2, - uint32_t value3) override { - return Result::Ok; - } - Result OnOpcodeUint32Uint32Uint32Uint32(uint32_t value, - uint32_t value2, - uint32_t value3, - uint32_t value4) override { - return Result::Ok; - } - Result OnOpcodeUint64(uint64_t value) override { return Result::Ok; } - Result OnOpcodeF32(uint32_t value) override { return Result::Ok; } - Result OnOpcodeF64(uint64_t value) override { return Result::Ok; } - Result OnOpcodeV128(v128 value) override { return Result::Ok; } - Result OnOpcodeBlockSig(Type sig_type) override { return Result::Ok; } - Result OnOpcodeType(Type type) override { return Result::Ok; } - Result OnAtomicLoadExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override { - return Result::Ok; - } - Result OnAtomicStoreExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override { - return Result::Ok; - } - Result OnAtomicRmwExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override { - return Result::Ok; - } - Result OnAtomicRmwCmpxchgExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override { - return Result::Ok; - } - Result OnAtomicWaitExpr(Opcode, Index, Address, Address) override { - return Result::Ok; - } - Result OnAtomicFenceExpr(uint32_t) override { return Result::Ok; } - Result OnAtomicNotifyExpr(Opcode, Index, Address, Address) override { - return Result::Ok; - } - Result OnBinaryExpr(Opcode opcode) override { return Result::Ok; } - Result OnBlockExpr(Type sig_type) override { return Result::Ok; } - Result OnBrExpr(Index depth) override { return Result::Ok; } - Result OnBrIfExpr(Index depth) override { return Result::Ok; } - Result OnBrTableExpr(Index num_targets, - Index* target_depths, - Index default_target_depth) override { - return Result::Ok; - } - Result OnCallExpr(Index func_index) override { return Result::Ok; } - Result OnCallIndirectExpr(Index sig_index, Index table_index) override { - return Result::Ok; - } - Result OnCallRefExpr() override { return Result::Ok; } - Result OnCatchExpr(Index tag_index) override { return Result::Ok; } - Result OnCatchAllExpr() override { return Result::Ok; } - Result OnCompareExpr(Opcode opcode) override { return Result::Ok; } - Result OnConvertExpr(Opcode opcode) override { return Result::Ok; } - Result OnDelegateExpr(Index depth) override { return Result::Ok; } - Result OnDropExpr() override { return Result::Ok; } - Result OnElseExpr() override { return Result::Ok; } - Result OnEndExpr() override { return Result::Ok; } - Result OnF32ConstExpr(uint32_t value_bits) override { return Result::Ok; } - Result OnF64ConstExpr(uint64_t value_bits) override { return Result::Ok; } - Result OnV128ConstExpr(v128 value_bits) override { return Result::Ok; } - Result OnGlobalGetExpr(Index global_index) override { return Result::Ok; } - Result OnGlobalSetExpr(Index global_index) override { return Result::Ok; } - Result OnI32ConstExpr(uint32_t value) override { return Result::Ok; } - Result OnI64ConstExpr(uint64_t value) override { return Result::Ok; } - Result OnIfExpr(Type sig_type) override { return Result::Ok; } - Result OnLoadExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override { - return Result::Ok; - } - Result OnLocalGetExpr(Index local_index) override { return Result::Ok; } - Result OnLocalSetExpr(Index local_index) override { return Result::Ok; } - Result OnLocalTeeExpr(Index local_index) override { return Result::Ok; } - Result OnLoopExpr(Type sig_type) override { return Result::Ok; } - Result OnMemoryCopyExpr(Index srcmemidx, Index destmemidx) override { - return Result::Ok; - } - Result OnDataDropExpr(Index segment_index) override { return Result::Ok; } - Result OnMemoryFillExpr(Index memidx) override { return Result::Ok; } - Result OnMemoryGrowExpr(Index memidx) override { return Result::Ok; } - Result OnMemoryInitExpr(Index segment_index, Index memidx) override { - return Result::Ok; - } - Result OnMemorySizeExpr(Index memidx) override { return Result::Ok; } - Result OnTableCopyExpr(Index dst_index, Index src_index) override { - return Result::Ok; - } - Result OnElemDropExpr(Index segment_index) override { return Result::Ok; } - Result OnTableInitExpr(Index segment_index, Index table_index) override { - return Result::Ok; - } - Result OnTableGetExpr(Index table_index) override { return Result::Ok; } - Result OnTableSetExpr(Index table_index) override { return Result::Ok; } - Result OnTableGrowExpr(Index table_index) override { return Result::Ok; } - Result OnTableSizeExpr(Index table_index) override { return Result::Ok; } - Result OnTableFillExpr(Index table_index) override { return Result::Ok; } - Result OnRefFuncExpr(Index func_index) override { return Result::Ok; } - Result OnRefNullExpr(Type type) override { return Result::Ok; } - Result OnRefIsNullExpr() override { return Result::Ok; } - Result OnNopExpr() override { return Result::Ok; } - Result OnRethrowExpr(Index depth) override { return Result::Ok; } - Result OnReturnCallExpr(Index sig_index) override { return Result::Ok; } - Result OnReturnCallIndirectExpr(Index sig_index, Index table_index) override { - return Result::Ok; - } - Result OnReturnExpr() override { return Result::Ok; } - Result OnSelectExpr(Index result_count, Type* result_types) override { - return Result::Ok; - } - Result OnStoreExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override { - return Result::Ok; - } - Result OnThrowExpr(Index depth) override { return Result::Ok; } - Result OnTryExpr(Type sig_type) override { return Result::Ok; } - Result OnUnaryExpr(Opcode opcode) override { return Result::Ok; } - Result OnTernaryExpr(Opcode opcode) override { return Result::Ok; } - Result OnUnreachableExpr() override { return Result::Ok; } - Result EndFunctionBody(Index index) override { return Result::Ok; } - Result EndCodeSection() override { return Result::Ok; } - Result OnSimdLaneOpExpr(Opcode opcode, uint64_t value) override { - return Result::Ok; - } - Result OnSimdLoadLaneExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset, - uint64_t value) override { - return Result::Ok; - } - Result OnSimdStoreLaneExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset, - uint64_t value) override { - return Result::Ok; - } - Result OnSimdShuffleOpExpr(Opcode opcode, v128 value) override { - return Result::Ok; - } - Result OnLoadSplatExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override { - return Result::Ok; - } - Result OnLoadZeroExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) override { - return Result::Ok; - } - - /* Elem section */ - Result BeginElemSection(Offset size) override { return Result::Ok; } - Result OnElemSegmentCount(Index count) override { return Result::Ok; } - Result BeginElemSegment(Index index, - Index table_index, - uint8_t flags) override { - return Result::Ok; - } - Result BeginElemSegmentInitExpr(Index index) override { return Result::Ok; } - Result EndElemSegmentInitExpr(Index index) override { return Result::Ok; } - Result OnElemSegmentElemType(Index index, Type elem_type) override { - return Result::Ok; - } - Result OnElemSegmentElemExprCount(Index index, Index count) override { - return Result::Ok; - } - Result OnElemSegmentElemExpr_RefNull(Index segment_index, - Type type) override { - return Result::Ok; - } - Result OnElemSegmentElemExpr_RefFunc(Index segment_index, - Index func_index) override { - return Result::Ok; - } - Result EndElemSegment(Index index) override { return Result::Ok; } - Result EndElemSection() override { return Result::Ok; } - - /* Data section */ - Result BeginDataSection(Offset size) override { return Result::Ok; } - Result OnDataSegmentCount(Index count) override { return Result::Ok; } - Result BeginDataSegment(Index index, - Index memory_index, - uint8_t flags) override { - return Result::Ok; - } - Result BeginDataSegmentInitExpr(Index index) override { return Result::Ok; } - Result EndDataSegmentInitExpr(Index index) override { return Result::Ok; } - Result OnDataSegmentData(Index index, - const void* data, - Address size) override { - return Result::Ok; - } - Result EndDataSegment(Index index) override { return Result::Ok; } - Result EndDataSection() override { return Result::Ok; } - - /* DataCount section */ - Result BeginDataCountSection(Offset size) override { return Result::Ok; } - Result OnDataCount(Index count) override { return Result::Ok; } - Result EndDataCountSection() override { return Result::Ok; } - - /* Names section */ - Result BeginNamesSection(Offset size) override { return Result::Ok; } - Result OnModuleNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) override { - return Result::Ok; - } - Result OnModuleName(std::string_view name) override { return Result::Ok; } - Result OnFunctionNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) override { - return Result::Ok; - } - Result OnFunctionNamesCount(Index num_functions) override { - return Result::Ok; - } - Result OnFunctionName(Index function_index, - std::string_view function_name) override { - return Result::Ok; - } - Result OnLocalNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) override { - return Result::Ok; - } - Result OnLocalNameFunctionCount(Index num_functions) override { - return Result::Ok; - } - Result OnLocalNameLocalCount(Index function_index, - Index num_locals) override { - return Result::Ok; - } - Result OnLocalName(Index function_index, - Index local_index, - std::string_view local_name) override { - return Result::Ok; - } - Result EndNamesSection() override { return Result::Ok; } - - Result OnNameSubsection(Index index, - NameSectionSubsection subsection_type, - Offset subsection_size) override { - return Result::Ok; - } - Result OnNameCount(Index num_names) override { return Result::Ok; } - Result OnNameEntry(NameSectionSubsection type, - Index index, - std::string_view name) override { - return Result::Ok; - } - - /* Reloc section */ - Result BeginRelocSection(Offset size) override { return Result::Ok; } - Result OnRelocCount(Index count, Index section_code) override { - return Result::Ok; - } - Result OnReloc(RelocType type, - Offset offset, - Index index, - uint32_t addend) override { - return Result::Ok; - } - Result EndRelocSection() override { return Result::Ok; } - - /* Tag section */ - Result BeginTagSection(Offset size) override { return Result::Ok; } - Result OnTagCount(Index count) override { return Result::Ok; } - Result OnTagType(Index index, Index sig_index) override { return Result::Ok; } - Result EndTagSection() override { return Result::Ok; } - - /* Code Metadata sections */ - Result BeginCodeMetadataSection(std::string_view name, Offset size) override { - return Result::Ok; - } - Result OnCodeMetadataFuncCount(Index count) override { return Result::Ok; } - Result OnCodeMetadataCount(Index function_index, Index count) override { - return Result::Ok; - } - Result OnCodeMetadata(Offset offset, - const void* data, - Address size) override { - return Result::Ok; - } - Result EndCodeMetadataSection() override { return Result::Ok; } - - /* Dylink section */ - Result BeginDylinkSection(Offset size) override { return Result::Ok; } - Result OnDylinkInfo(uint32_t mem_size, - uint32_t mem_align, - uint32_t table_size, - uint32_t table_align) override { - return Result::Ok; - } - Result OnDylinkNeededCount(Index count) override { return Result::Ok; } - Result OnDylinkNeeded(std::string_view so_name) override { - return Result::Ok; - } - Result OnDylinkImportCount(Index count) override { return Result::Ok; } - Result OnDylinkExportCount(Index count) override { return Result::Ok; } - Result OnDylinkImport(std::string_view module, - std::string_view name, - uint32_t flags) override { - return Result::Ok; - } - Result OnDylinkExport(std::string_view name, uint32_t flags) override { - return Result::Ok; - } - Result EndDylinkSection() override { return Result::Ok; } - - /* target_features section */ - Result BeginTargetFeaturesSection(Offset size) override { return Result::Ok; } - Result OnFeatureCount(Index count) override { return Result::Ok; } - Result OnFeature(uint8_t prefix, std::string_view name) override { - return Result::Ok; - } - Result EndTargetFeaturesSection() override { return Result::Ok; } - - /* Linking section */ - Result BeginLinkingSection(Offset size) override { return Result::Ok; } - Result OnSymbolCount(Index count) override { return Result::Ok; } - Result OnDataSymbol(Index index, - uint32_t flags, - std::string_view name, - Index segment, - uint32_t offset, - uint32_t size) override { - return Result::Ok; - } - Result OnFunctionSymbol(Index index, - uint32_t flags, - std::string_view name, - Index func_index) override { - return Result::Ok; - } - Result OnGlobalSymbol(Index index, - uint32_t flags, - std::string_view name, - Index global_index) override { - return Result::Ok; - } - Result OnSectionSymbol(Index index, - uint32_t flags, - Index section_index) override { - return Result::Ok; - } - Result OnTagSymbol(Index index, - uint32_t flags, - std::string_view name, - Index tag_index) override { - return Result::Ok; - } - Result OnTableSymbol(Index index, - uint32_t flags, - std::string_view name, - Index table_index) override { - return Result::Ok; - } - Result OnSegmentInfoCount(Index count) override { return Result::Ok; } - Result OnSegmentInfo(Index index, - std::string_view name, - Address alignment, - uint32_t flags) override { - return Result::Ok; - } - Result OnInitFunctionCount(Index count) override { return Result::Ok; } - Result OnInitFunction(uint32_t priority, Index function_index) override { - return Result::Ok; - } - Result OnComdatCount(Index count) override { return Result::Ok; } - Result OnComdatBegin(std::string_view name, - uint32_t flags, - Index count) override { - return Result::Ok; - } - Result OnComdatEntry(ComdatType kind, Index index) override { - return Result::Ok; - } - Result EndLinkingSection() override { return Result::Ok; } -}; - -} // namespace wabt - -#endif /* WABT_BINARY_READER_H_ */ diff --git a/src/binary-reader-objdump.cc b/src/binary-reader-objdump.cc index b6ff58a6..ad265d5b 100644 --- a/src/binary-reader-objdump.cc +++ b/src/binary-reader-objdump.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/binary-reader-objdump.h" +#include "wabt/binary-reader-objdump.h" #include <algorithm> #include <cassert> @@ -27,10 +27,10 @@ #include <strings.h> #endif -#include "src/binary-reader-nop.h" -#include "src/filenames.h" -#include "src/literal.h" -#include "src/string-util.h" +#include "wabt/binary-reader-nop.h" +#include "wabt/filenames.h" +#include "wabt/literal.h" +#include "wabt/string-util.h" namespace wabt { diff --git a/src/binary-reader-objdump.h b/src/binary-reader-objdump.h deleted file mode 100644 index 3b859160..00000000 --- a/src/binary-reader-objdump.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_READER_OBJDUMP_H_ -#define WABT_BINARY_READER_OBJDUMP_H_ - -#include <map> -#include <string> - -#include "src/common.h" -#include "src/feature.h" -#include "src/stream.h" - -namespace wabt { - -struct Module; -struct ReadBinaryOptions; - -enum class ObjdumpMode { - Prepass, - Headers, - Details, - Disassemble, - RawData, -}; - -struct ObjdumpOptions { - Stream* log_stream; - bool headers; - bool details; - bool raw; - bool disassemble; - bool debug; - bool relocs; - bool section_offsets; - ObjdumpMode mode; - const char* filename; - const char* section_name; -}; - -struct ObjdumpSymbol { - wabt::SymbolType kind; - std::string name; - Index index; -}; - -struct ObjdumpNames { - std::string_view Get(Index index) const; - void Set(Index index, std::string_view name); - - std::map<Index, std::string> names; -}; - -struct ObjdumpLocalNames { - std::string_view Get(Index function_index, Index local_index) const; - void Set(Index function_index, Index local_index, std::string_view name); - - std::map<std::pair<Index, Index>, std::string> names; -}; - -// read_binary_objdump uses this state to store information from previous runs -// and use it to display more useful information. -struct ObjdumpState { - std::vector<Reloc> code_relocations; - std::vector<Reloc> data_relocations; - ObjdumpNames type_names; - ObjdumpNames function_names; - ObjdumpNames global_names; - ObjdumpNames section_names; - ObjdumpNames tag_names; - ObjdumpNames segment_names; - ObjdumpNames table_names; - ObjdumpLocalNames local_names; - std::vector<ObjdumpSymbol> symtab; - std::map<Index, Index> function_param_counts; -}; - -Result ReadBinaryObjdump(const uint8_t* data, - size_t size, - ObjdumpOptions* options, - ObjdumpState* state); - -} // namespace wabt - -#endif /* WABT_BINARY_READER_OBJDUMP_H_ */ diff --git a/src/binary-reader-opcnt.cc b/src/binary-reader-opcnt.cc index 96e3ef23..3177dbb7 100644 --- a/src/binary-reader-opcnt.cc +++ b/src/binary-reader-opcnt.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/binary-reader-opcnt.h" +#include "wabt/binary-reader-opcnt.h" #include <cassert> #include <cinttypes> @@ -22,10 +22,10 @@ #include <cstdint> #include <cstdio> -#include "src/binary-reader-nop.h" -#include "src/common.h" -#include "src/literal.h" -#include "src/stream.h" +#include "wabt/binary-reader-nop.h" +#include "wabt/common.h" +#include "wabt/literal.h" +#include "wabt/stream.h" namespace wabt { diff --git a/src/binary-reader-opcnt.h b/src/binary-reader-opcnt.h deleted file mode 100644 index e499c75d..00000000 --- a/src/binary-reader-opcnt.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_READER_OPCNT_H_ -#define WABT_BINARY_READER_OPCNT_H_ - -#include <map> -#include <vector> - -#include "src/common.h" -#include "src/opcode.h" - -namespace wabt { - -struct Module; -struct ReadBinaryOptions; -class Stream; - -class OpcodeInfo { - public: - enum class Kind { - Bare, - Uint32, - Uint64, - Index, - Float32, - Float64, - Uint32Uint32, - Uint32Uint32Uint32, - Uint32Uint32Uint32Uint32, - BlockSig, - BrTable, - V128, - }; - - explicit OpcodeInfo(Opcode, Kind); - template <typename T> - OpcodeInfo(Opcode, Kind, T* data, size_t count = 1); - template <typename T> - OpcodeInfo(Opcode, Kind, T* data, size_t count, T extra); - - Opcode opcode() const { return opcode_; } - - void Write(Stream&); - - private: - template <typename T> - std::pair<const T*, size_t> GetDataArray() const; - template <typename T> - const T* GetData(size_t expected_size = 1) const; - - template <typename T, typename F> - void WriteArray(Stream& stream, F&& write_func); - - Opcode opcode_; - Kind kind_; - std::vector<uint8_t> data_; - - friend bool operator==(const OpcodeInfo&, const OpcodeInfo&); - friend bool operator!=(const OpcodeInfo&, const OpcodeInfo&); - friend bool operator<(const OpcodeInfo&, const OpcodeInfo&); - friend bool operator<=(const OpcodeInfo&, const OpcodeInfo&); - friend bool operator>(const OpcodeInfo&, const OpcodeInfo&); - friend bool operator>=(const OpcodeInfo&, const OpcodeInfo&); -}; - -bool operator==(const OpcodeInfo&, const OpcodeInfo&); -bool operator!=(const OpcodeInfo&, const OpcodeInfo&); -bool operator<(const OpcodeInfo&, const OpcodeInfo&); -bool operator<=(const OpcodeInfo&, const OpcodeInfo&); -bool operator>(const OpcodeInfo&, const OpcodeInfo&); -bool operator>=(const OpcodeInfo&, const OpcodeInfo&); - -typedef std::map<OpcodeInfo, size_t> OpcodeInfoCounts; - -Result ReadBinaryOpcnt(const void* data, - size_t size, - const ReadBinaryOptions& options, - OpcodeInfoCounts* opcode_counts); - -} // namespace wabt - -#endif /* WABT_BINARY_READER_OPCNT_H_ */ diff --git a/src/binary-reader.cc b/src/binary-reader.cc index 3408b9da..63362636 100644 --- a/src/binary-reader.cc +++ b/src/binary-reader.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/binary-reader.h" +#include "wabt/binary-reader.h" #include <cassert> #include <cinttypes> @@ -24,13 +24,13 @@ #include <cstring> #include <vector> -#include "config.h" +#include "wabt/config.h" -#include "src/binary-reader-logging.h" -#include "src/binary.h" -#include "src/leb128.h" -#include "src/stream.h" -#include "src/utf8.h" +#include "wabt/binary-reader-logging.h" +#include "wabt/binary.h" +#include "wabt/leb128.h" +#include "wabt/stream.h" +#include "wabt/utf8.h" #if HAVE_ALLOCA #include <alloca.h> diff --git a/src/binary-reader.h b/src/binary-reader.h deleted file mode 100644 index 9ab067fe..00000000 --- a/src/binary-reader.h +++ /dev/null @@ -1,505 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_READER_H_ -#define WABT_BINARY_READER_H_ - -#include <stddef.h> -#include <stdint.h> -#include <string_view> - -#include "src/binary.h" -#include "src/common.h" -#include "src/error.h" -#include "src/feature.h" -#include "src/opcode.h" - -namespace wabt { - -class Stream; - -struct ReadBinaryOptions { - ReadBinaryOptions() = default; - ReadBinaryOptions(const Features& features, - Stream* log_stream, - bool read_debug_names, - bool stop_on_first_error, - bool fail_on_custom_section_error) - : features(features), - log_stream(log_stream), - read_debug_names(read_debug_names), - stop_on_first_error(stop_on_first_error), - fail_on_custom_section_error(fail_on_custom_section_error) {} - - Features features; - Stream* log_stream = nullptr; - bool read_debug_names = false; - bool stop_on_first_error = true; - bool fail_on_custom_section_error = true; - bool skip_function_bodies = false; -}; - -// TODO: Move somewhere else? -struct TypeMut { - Type type; - bool mutable_; -}; -using TypeMutVector = std::vector<TypeMut>; - -class BinaryReaderDelegate { - public: - struct State { - State(const uint8_t* data, Offset size) - : data(data), size(size), offset(0) {} - - const uint8_t* data; - Offset size; - Offset offset; - }; - - virtual ~BinaryReaderDelegate() {} - - virtual bool OnError(const Error&) = 0; - virtual void OnSetState(const State* s) { state = s; } - - /* Module */ - virtual Result BeginModule(uint32_t version) = 0; - virtual Result EndModule() = 0; - - virtual Result BeginSection(Index section_index, - BinarySection section_type, - Offset size) = 0; - - /* Custom section */ - virtual Result BeginCustomSection(Index section_index, - Offset size, - std::string_view section_name) = 0; - virtual Result EndCustomSection() = 0; - - /* Type section */ - virtual Result BeginTypeSection(Offset size) = 0; - virtual Result OnTypeCount(Index count) = 0; - virtual Result OnFuncType(Index index, - Index param_count, - Type* param_types, - Index result_count, - Type* result_types) = 0; - virtual Result OnStructType(Index index, - Index field_count, - TypeMut* fields) = 0; - virtual Result OnArrayType(Index index, TypeMut field) = 0; - virtual Result EndTypeSection() = 0; - - /* Import section */ - virtual Result BeginImportSection(Offset size) = 0; - virtual Result OnImportCount(Index count) = 0; - virtual Result OnImport(Index index, - ExternalKind kind, - std::string_view module_name, - std::string_view field_name) = 0; - virtual Result OnImportFunc(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index func_index, - Index sig_index) = 0; - virtual Result OnImportTable(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index table_index, - Type elem_type, - const Limits* elem_limits) = 0; - virtual Result OnImportMemory(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index memory_index, - const Limits* page_limits) = 0; - virtual Result OnImportGlobal(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index global_index, - Type type, - bool mutable_) = 0; - virtual Result OnImportTag(Index import_index, - std::string_view module_name, - std::string_view field_name, - Index tag_index, - Index sig_index) = 0; - virtual Result EndImportSection() = 0; - - /* Function section */ - virtual Result BeginFunctionSection(Offset size) = 0; - virtual Result OnFunctionCount(Index count) = 0; - virtual Result OnFunction(Index index, Index sig_index) = 0; - virtual Result EndFunctionSection() = 0; - - /* Table section */ - virtual Result BeginTableSection(Offset size) = 0; - virtual Result OnTableCount(Index count) = 0; - virtual Result OnTable(Index index, - Type elem_type, - const Limits* elem_limits) = 0; - virtual Result EndTableSection() = 0; - - /* Memory section */ - virtual Result BeginMemorySection(Offset size) = 0; - virtual Result OnMemoryCount(Index count) = 0; - virtual Result OnMemory(Index index, const Limits* limits) = 0; - virtual Result EndMemorySection() = 0; - - /* Global section */ - virtual Result BeginGlobalSection(Offset size) = 0; - virtual Result OnGlobalCount(Index count) = 0; - virtual Result BeginGlobal(Index index, Type type, bool mutable_) = 0; - virtual Result BeginGlobalInitExpr(Index index) = 0; - virtual Result EndGlobalInitExpr(Index index) = 0; - virtual Result EndGlobal(Index index) = 0; - virtual Result EndGlobalSection() = 0; - - /* Exports section */ - virtual Result BeginExportSection(Offset size) = 0; - virtual Result OnExportCount(Index count) = 0; - virtual Result OnExport(Index index, - ExternalKind kind, - Index item_index, - std::string_view name) = 0; - virtual Result EndExportSection() = 0; - - /* Start section */ - virtual Result BeginStartSection(Offset size) = 0; - virtual Result OnStartFunction(Index func_index) = 0; - virtual Result EndStartSection() = 0; - - /* Code section */ - virtual Result BeginCodeSection(Offset size) = 0; - virtual Result OnFunctionBodyCount(Index count) = 0; - virtual Result BeginFunctionBody(Index index, Offset size) = 0; - virtual Result OnLocalDeclCount(Index count) = 0; - virtual Result OnLocalDecl(Index decl_index, Index count, Type type) = 0; - - /* Function expressions; called between BeginFunctionBody and - EndFunctionBody */ - virtual Result OnOpcode(Opcode Opcode) = 0; - virtual Result OnOpcodeBare() = 0; - virtual Result OnOpcodeUint32(uint32_t value) = 0; - virtual Result OnOpcodeIndex(Index value) = 0; - virtual Result OnOpcodeIndexIndex(Index value, Index value2) = 0; - virtual Result OnOpcodeUint32Uint32(uint32_t value, uint32_t value2) = 0; - virtual Result OnOpcodeUint32Uint32Uint32(uint32_t value, - uint32_t value2, - uint32_t value3) = 0; - virtual Result OnOpcodeUint32Uint32Uint32Uint32(uint32_t value, - uint32_t value2, - uint32_t value3, - uint32_t value4) = 0; - virtual Result OnOpcodeUint64(uint64_t value) = 0; - virtual Result OnOpcodeF32(uint32_t value) = 0; - virtual Result OnOpcodeF64(uint64_t value) = 0; - virtual Result OnOpcodeV128(v128 value) = 0; - virtual Result OnOpcodeBlockSig(Type sig_type) = 0; - virtual Result OnOpcodeType(Type type) = 0; - virtual Result OnAtomicLoadExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnAtomicStoreExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnAtomicRmwExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnAtomicRmwCmpxchgExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnAtomicWaitExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnAtomicFenceExpr(uint32_t consistency_model) = 0; - virtual Result OnAtomicNotifyExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnBinaryExpr(Opcode opcode) = 0; - virtual Result OnBlockExpr(Type sig_type) = 0; - virtual Result OnBrExpr(Index depth) = 0; - virtual Result OnBrIfExpr(Index depth) = 0; - virtual Result OnBrTableExpr(Index num_targets, - Index* target_depths, - Index default_target_depth) = 0; - virtual Result OnCallExpr(Index func_index) = 0; - virtual Result OnCallIndirectExpr(Index sig_index, Index table_index) = 0; - virtual Result OnCallRefExpr() = 0; - virtual Result OnCatchExpr(Index tag_index) = 0; - virtual Result OnCatchAllExpr() = 0; - virtual Result OnCompareExpr(Opcode opcode) = 0; - virtual Result OnConvertExpr(Opcode opcode) = 0; - virtual Result OnDelegateExpr(Index depth) = 0; - virtual Result OnDropExpr() = 0; - virtual Result OnElseExpr() = 0; - virtual Result OnEndExpr() = 0; - virtual Result OnF32ConstExpr(uint32_t value_bits) = 0; - virtual Result OnF64ConstExpr(uint64_t value_bits) = 0; - virtual Result OnV128ConstExpr(v128 value_bits) = 0; - virtual Result OnGlobalGetExpr(Index global_index) = 0; - virtual Result OnGlobalSetExpr(Index global_index) = 0; - virtual Result OnI32ConstExpr(uint32_t value) = 0; - virtual Result OnI64ConstExpr(uint64_t value) = 0; - virtual Result OnIfExpr(Type sig_type) = 0; - virtual Result OnLoadExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnLocalGetExpr(Index local_index) = 0; - virtual Result OnLocalSetExpr(Index local_index) = 0; - virtual Result OnLocalTeeExpr(Index local_index) = 0; - virtual Result OnLoopExpr(Type sig_type) = 0; - virtual Result OnMemoryCopyExpr(Index srcmemidx, Index destmemidx) = 0; - virtual Result OnDataDropExpr(Index segment_index) = 0; - virtual Result OnMemoryFillExpr(Index memidx) = 0; - virtual Result OnMemoryGrowExpr(Index memidx) = 0; - virtual Result OnMemoryInitExpr(Index segment_index, Index memidx) = 0; - virtual Result OnMemorySizeExpr(Index memidx) = 0; - virtual Result OnTableCopyExpr(Index dst_index, Index src_index) = 0; - virtual Result OnElemDropExpr(Index segment_index) = 0; - virtual Result OnTableInitExpr(Index segment_index, Index table_index) = 0; - virtual Result OnTableGetExpr(Index table_index) = 0; - virtual Result OnTableSetExpr(Index table_index) = 0; - virtual Result OnTableGrowExpr(Index table_index) = 0; - virtual Result OnTableSizeExpr(Index table_index) = 0; - virtual Result OnTableFillExpr(Index table_index) = 0; - virtual Result OnRefFuncExpr(Index func_index) = 0; - virtual Result OnRefNullExpr(Type type) = 0; - virtual Result OnRefIsNullExpr() = 0; - virtual Result OnNopExpr() = 0; - virtual Result OnRethrowExpr(Index depth) = 0; - virtual Result OnReturnExpr() = 0; - virtual Result OnReturnCallExpr(Index func_index) = 0; - virtual Result OnReturnCallIndirectExpr(Index sig_index, - Index table_index) = 0; - virtual Result OnSelectExpr(Index result_count, Type* result_types) = 0; - virtual Result OnStoreExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnThrowExpr(Index tag_index) = 0; - virtual Result OnTryExpr(Type sig_type) = 0; - - virtual Result OnUnaryExpr(Opcode opcode) = 0; - virtual Result OnTernaryExpr(Opcode opcode) = 0; - virtual Result OnUnreachableExpr() = 0; - virtual Result EndFunctionBody(Index index) = 0; - virtual Result EndCodeSection() = 0; - - /* Simd instructions with Lane Imm operand*/ - virtual Result OnSimdLaneOpExpr(Opcode opcode, uint64_t value) = 0; - virtual Result OnSimdShuffleOpExpr(Opcode opcode, v128 value) = 0; - virtual Result OnSimdLoadLaneExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset, - uint64_t value) = 0; - virtual Result OnSimdStoreLaneExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset, - uint64_t value) = 0; - - virtual Result OnLoadSplatExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - virtual Result OnLoadZeroExpr(Opcode opcode, - Index memidx, - Address alignment_log2, - Address offset) = 0; - - /* Elem section */ - virtual Result BeginElemSection(Offset size) = 0; - virtual Result OnElemSegmentCount(Index count) = 0; - virtual Result BeginElemSegment(Index index, - Index table_index, - uint8_t flags) = 0; - virtual Result BeginElemSegmentInitExpr(Index index) = 0; - virtual Result EndElemSegmentInitExpr(Index index) = 0; - virtual Result OnElemSegmentElemType(Index index, Type elem_type) = 0; - virtual Result OnElemSegmentElemExprCount(Index index, Index count) = 0; - virtual Result OnElemSegmentElemExpr_RefNull(Index segment_index, - Type type) = 0; - virtual Result OnElemSegmentElemExpr_RefFunc(Index segment_index, - Index func_index) = 0; - virtual Result EndElemSegment(Index index) = 0; - virtual Result EndElemSection() = 0; - - /* Data section */ - virtual Result BeginDataSection(Offset size) = 0; - virtual Result OnDataSegmentCount(Index count) = 0; - virtual Result BeginDataSegment(Index index, - Index memory_index, - uint8_t flags) = 0; - virtual Result BeginDataSegmentInitExpr(Index index) = 0; - virtual Result EndDataSegmentInitExpr(Index index) = 0; - virtual Result OnDataSegmentData(Index index, - const void* data, - Address size) = 0; - virtual Result EndDataSegment(Index index) = 0; - virtual Result EndDataSection() = 0; - - /* DataCount section */ - virtual Result BeginDataCountSection(Offset size) = 0; - virtual Result OnDataCount(Index count) = 0; - virtual Result EndDataCountSection() = 0; - - /* Names section */ - virtual Result BeginNamesSection(Offset size) = 0; - virtual Result OnModuleNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) = 0; - virtual Result OnModuleName(std::string_view name) = 0; - virtual Result OnFunctionNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) = 0; - virtual Result OnFunctionNamesCount(Index num_functions) = 0; - virtual Result OnFunctionName(Index function_index, - std::string_view function_name) = 0; - virtual Result OnLocalNameSubsection(Index index, - uint32_t name_type, - Offset subsection_size) = 0; - virtual Result OnLocalNameFunctionCount(Index num_functions) = 0; - virtual Result OnLocalNameLocalCount(Index function_index, - Index num_locals) = 0; - virtual Result OnLocalName(Index function_index, - Index local_index, - std::string_view local_name) = 0; - virtual Result OnNameSubsection(Index index, - NameSectionSubsection subsection_type, - Offset subsection_size) = 0; - virtual Result OnNameCount(Index num_names) = 0; - virtual Result OnNameEntry(NameSectionSubsection type, - Index index, - std::string_view name) = 0; - virtual Result EndNamesSection() = 0; - - /* Reloc section */ - virtual Result BeginRelocSection(Offset size) = 0; - virtual Result OnRelocCount(Index count, Index section_index) = 0; - virtual Result OnReloc(RelocType type, - Offset offset, - Index index, - uint32_t addend) = 0; - virtual Result EndRelocSection() = 0; - - /* Dylink section */ - virtual Result BeginDylinkSection(Offset size) = 0; - virtual Result OnDylinkInfo(uint32_t mem_size, - uint32_t mem_align_log2, - uint32_t table_size, - uint32_t table_align_log2) = 0; - virtual Result OnDylinkImportCount(Index count) = 0; - virtual Result OnDylinkExportCount(Index count) = 0; - virtual Result OnDylinkImport(std::string_view module, - std::string_view name, - uint32_t flags) = 0; - virtual Result OnDylinkExport(std::string_view name, uint32_t flags) = 0; - virtual Result OnDylinkNeededCount(Index count) = 0; - virtual Result OnDylinkNeeded(std::string_view so_name) = 0; - virtual Result EndDylinkSection() = 0; - - /* target_features section */ - virtual Result BeginTargetFeaturesSection(Offset size) = 0; - virtual Result OnFeatureCount(Index count) = 0; - virtual Result OnFeature(uint8_t prefix, std::string_view name) = 0; - virtual Result EndTargetFeaturesSection() = 0; - - /* Linking section */ - virtual Result BeginLinkingSection(Offset size) = 0; - virtual Result OnSymbolCount(Index count) = 0; - virtual Result OnDataSymbol(Index index, - uint32_t flags, - std::string_view name, - Index segment, - uint32_t offset, - uint32_t size) = 0; - virtual Result OnFunctionSymbol(Index index, - uint32_t flags, - std::string_view name, - Index function_index) = 0; - virtual Result OnGlobalSymbol(Index index, - uint32_t flags, - std::string_view name, - Index global_index) = 0; - virtual Result OnSectionSymbol(Index index, - uint32_t flags, - Index section_index) = 0; - virtual Result OnTagSymbol(Index index, - uint32_t flags, - std::string_view name, - Index tag_index) = 0; - virtual Result OnTableSymbol(Index index, - uint32_t flags, - std::string_view name, - Index table_index) = 0; - virtual Result OnSegmentInfoCount(Index count) = 0; - virtual Result OnSegmentInfo(Index index, - std::string_view name, - Address alignment_log2, - uint32_t flags) = 0; - virtual Result OnInitFunctionCount(Index count) = 0; - virtual Result OnInitFunction(uint32_t priority, Index function_index) = 0; - virtual Result OnComdatCount(Index count) = 0; - virtual Result OnComdatBegin(std::string_view name, - uint32_t flags, - Index count) = 0; - virtual Result OnComdatEntry(ComdatType kind, Index index) = 0; - virtual Result EndLinkingSection() = 0; - - /* Tag section */ - virtual Result BeginTagSection(Offset size) = 0; - virtual Result OnTagCount(Index count) = 0; - virtual Result OnTagType(Index index, Index sig_index) = 0; - virtual Result EndTagSection() = 0; - - /* Code Metadata sections */ - virtual Result BeginCodeMetadataSection(std::string_view name, - Offset size) = 0; - virtual Result OnCodeMetadataFuncCount(Index count) = 0; - virtual Result OnCodeMetadataCount(Index function_index, Index count) = 0; - virtual Result OnCodeMetadata(Offset offset, - const void* data, - Address size) = 0; - virtual Result EndCodeMetadataSection() = 0; - - const State* state = nullptr; -}; - -Result ReadBinary(const void* data, - size_t size, - BinaryReaderDelegate* reader, - const ReadBinaryOptions& options); - -size_t ReadU32Leb128(const uint8_t* ptr, - const uint8_t* end, - uint32_t* out_value); - -size_t ReadI32Leb128(const uint8_t* ptr, - const uint8_t* end, - uint32_t* out_value); - -} // namespace wabt - -#endif /* WABT_BINARY_READER_H_ */ diff --git a/src/binary-writer-spec.cc b/src/binary-writer-spec.cc index 8d467fcc..af75464a 100644 --- a/src/binary-writer-spec.cc +++ b/src/binary-writer-spec.cc @@ -14,21 +14,21 @@ * limitations under the License. */ -#include "src/binary-writer-spec.h" +#include "wabt/binary-writer-spec.h" #include <cassert> #include <cinttypes> #include <string_view> -#include "config.h" +#include "wabt/config.h" -#include "src/binary-writer.h" -#include "src/binary.h" -#include "src/cast.h" -#include "src/filenames.h" -#include "src/ir.h" -#include "src/literal.h" -#include "src/stream.h" +#include "wabt/binary-writer.h" +#include "wabt/binary.h" +#include "wabt/cast.h" +#include "wabt/filenames.h" +#include "wabt/ir.h" +#include "wabt/literal.h" +#include "wabt/stream.h" namespace wabt { diff --git a/src/binary-writer-spec.h b/src/binary-writer-spec.h deleted file mode 100644 index 65c2460a..00000000 --- a/src/binary-writer-spec.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_WRITER_SPEC_H_ -#define WABT_BINARY_WRITER_SPEC_H_ - -#include <functional> -#include <utility> -#include <vector> - -#include "src/binary-writer.h" -#include "src/common.h" -#include "src/ir.h" - -namespace wabt { - -struct FilenameMemoryStreamPair { - FilenameMemoryStreamPair(std::string_view filename, - std::unique_ptr<MemoryStream> stream) - : filename(filename), stream(std::move(stream)) {} - std::string filename; - std::unique_ptr<MemoryStream> stream; -}; - -typedef std::function<Stream*(std::string_view filename)> - WriteBinarySpecStreamFactory; - -Result WriteBinarySpecScript(Stream* json_stream, - WriteBinarySpecStreamFactory module_stream_factory, - Script*, - std::string_view source_filename, - std::string_view module_filename_noext, - const WriteBinaryOptions&); - -// Convenience function for producing MemoryStream outputs all modules. -Result WriteBinarySpecScript( - Stream* json_stream, - Script*, - std::string_view source_filename, - std::string_view module_filename_noext, - const WriteBinaryOptions&, - std::vector<FilenameMemoryStreamPair>* out_module_streams, - Stream* log_stream = nullptr); - -} // namespace wabt - -#endif /* WABT_BINARY_WRITER_SPEC_H_ */ diff --git a/src/binary-writer.cc b/src/binary-writer.cc index 423eed3e..93db5b19 100644 --- a/src/binary-writer.cc +++ b/src/binary-writer.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/binary-writer.h" +#include "wabt/binary-writer.h" #include <cassert> #include <cmath> @@ -25,14 +25,14 @@ #include <string_view> #include <vector> -#include "config.h" +#include "wabt/config.h" -#include "src/binary.h" -#include "src/cast.h" -#include "src/expr-visitor.h" -#include "src/ir.h" -#include "src/leb128.h" -#include "src/stream.h" +#include "wabt/binary.h" +#include "wabt/cast.h" +#include "wabt/expr-visitor.h" +#include "wabt/ir.h" +#include "wabt/leb128.h" +#include "wabt/stream.h" #define PRINT_HEADER_NO_INDEX -1 #define MAX_U32_LEB128_BYTES 5 diff --git a/src/binary-writer.h b/src/binary-writer.h deleted file mode 100644 index 158ed2d3..00000000 --- a/src/binary-writer.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_WRITER_H_ -#define WABT_BINARY_WRITER_H_ - -#include "src/common.h" -#include "src/feature.h" -#include "src/opcode.h" -#include "src/stream.h" - -namespace wabt { - -struct Module; -struct Script; - -struct WriteBinaryOptions { - WriteBinaryOptions() = default; - WriteBinaryOptions(const Features& features, - bool canonicalize_lebs, - bool relocatable, - bool write_debug_names) - : features(features), - canonicalize_lebs(canonicalize_lebs), - relocatable(relocatable), - write_debug_names(write_debug_names) {} - - Features features; - bool canonicalize_lebs = true; - bool relocatable = false; - bool write_debug_names = false; -}; - -Result WriteBinaryModule(Stream*, const Module*, const WriteBinaryOptions&); - -void WriteType(Stream* stream, Type type, const char* desc = nullptr); - -void WriteStr(Stream* stream, - std::string_view s, - const char* desc, - PrintChars print_chars = PrintChars::No); - -void WriteOpcode(Stream* stream, Opcode opcode); - -void WriteLimits(Stream* stream, const Limits* limits); - -} // namespace wabt - -#endif /* WABT_BINARY_WRITER_H_ */ diff --git a/src/binary.cc b/src/binary.cc index 14ed98ce..d4938a19 100644 --- a/src/binary.cc +++ b/src/binary.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/binary.h" +#include "wabt/binary.h" namespace wabt { diff --git a/src/binary.h b/src/binary.h deleted file mode 100644 index 39e0f201..00000000 --- a/src/binary.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_H_ -#define WABT_BINARY_H_ - -#include "src/common.h" - -#define WABT_BINARY_MAGIC 0x6d736100 -#define WABT_BINARY_VERSION 1 -#define WABT_BINARY_LIMITS_HAS_MAX_FLAG 0x1 -#define WABT_BINARY_LIMITS_IS_SHARED_FLAG 0x2 -#define WABT_BINARY_LIMITS_IS_64_FLAG 0x4 -#define WABT_BINARY_LIMITS_ALL_FLAGS \ - (WABT_BINARY_LIMITS_HAS_MAX_FLAG | WABT_BINARY_LIMITS_IS_SHARED_FLAG | \ - WABT_BINARY_LIMITS_IS_64_FLAG) - -#define WABT_BINARY_SECTION_NAME "name" -#define WABT_BINARY_SECTION_RELOC "reloc" -#define WABT_BINARY_SECTION_LINKING "linking" -#define WABT_BINARY_SECTION_TARGET_FEATURES "target_features" -#define WABT_BINARY_SECTION_DYLINK "dylink" -#define WABT_BINARY_SECTION_DYLINK0 "dylink.0" -#define WABT_BINARY_SECTION_CODE_METADATA "metadata.code." - -#define WABT_FOREACH_BINARY_SECTION(V) \ - V(Custom, custom, 0) \ - V(Type, type, 1) \ - V(Import, import, 2) \ - V(Function, function, 3) \ - V(Table, table, 4) \ - V(Memory, memory, 5) \ - V(Tag, tag, 13) \ - V(Global, global, 6) \ - V(Export, export, 7) \ - V(Start, start, 8) \ - V(Elem, elem, 9) \ - V(DataCount, data_count, 12) \ - V(Code, code, 10) \ - V(Data, data, 11) - -namespace wabt { - -/* clang-format off */ -enum class BinarySection { -#define V(Name, name, code) Name = code, - WABT_FOREACH_BINARY_SECTION(V) -#undef V - Invalid = ~0, - - First = Custom, - Last = Tag, -}; -/* clang-format on */ -static const int kBinarySectionCount = WABT_ENUM_COUNT(BinarySection); - -enum class BinarySectionOrder { -#define V(Name, name, code) Name, - WABT_FOREACH_BINARY_SECTION(V) -#undef V -}; - -BinarySectionOrder GetSectionOrder(BinarySection); -const char* GetSectionName(BinarySection); - -// See -// https://github.com/WebAssembly/extended-name-section/blob/main/proposals/extended-name-section/Overview.md -enum class NameSectionSubsection { - Module = 0, - Function = 1, - Local = 2, - Label = 3, - Type = 4, - Table = 5, - Memory = 6, - Global = 7, - ElemSegment = 8, - DataSegment = 9, - // tag names are yet part of the extended-name-section proposal (because it - // only deals with naming things that are in the spec already). However, we - // include names for Tags in wabt using this enum value on the basis that tags - // can only exist when exceptions are enabled and that engines should ignore - // unknown name types. - Tag = 10, - - First = Module, - Last = Tag, -}; -const char* GetNameSectionSubsectionName(NameSectionSubsection subsec); - -} // namespace wabt - -#endif /* WABT_BINARY_H_ */ diff --git a/src/binding-hash.cc b/src/binding-hash.cc index f52682d7..cd1b5f5a 100644 --- a/src/binding-hash.cc +++ b/src/binding-hash.cc @@ -14,12 +14,12 @@ * limitations under the License. */ -#include "src/binding-hash.h" +#include "wabt/binding-hash.h" #include <algorithm> #include <vector> -#include "src/ir.h" +#include "wabt/ir.h" namespace wabt { diff --git a/src/binding-hash.h b/src/binding-hash.h deleted file mode 100644 index 1799ce54..00000000 --- a/src/binding-hash.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINDING_HASH_H_ -#define WABT_BINDING_HASH_H_ - -#include <functional> -#include <string> -#include <string_view> -#include <unordered_map> -#include <vector> - -#include "src/common.h" - -namespace wabt { - -struct Var; - -struct Binding { - explicit Binding(Index index) : index(index) {} - Binding(const Location& loc, Index index) : loc(loc), index(index) {} - - Location loc; - Index index; -}; - -// This class derives from a C++ container, which is usually not advisable -// because they don't have virtual destructors. So don't delete a BindingHash -// object through a pointer to std::unordered_multimap. -class BindingHash : public std::unordered_multimap<std::string, Binding> { - public: - typedef std::function<void(const value_type&, const value_type&)> - DuplicateCallback; - - void FindDuplicates(DuplicateCallback callback) const; - - Index FindIndex(const Var&) const; - - Index FindIndex(const std::string& name) const { - auto iter = find(name); - return iter != end() ? iter->second.index : kInvalidIndex; - } - - Index FindIndex(std::string_view name) const { - return FindIndex(std::string(name)); - } - - private: - typedef std::vector<const value_type*> ValueTypeVector; - - void CreateDuplicatesVector(ValueTypeVector* out_duplicates) const; - void SortDuplicatesVectorByLocation(ValueTypeVector* duplicates) const; - void CallCallbacks(const ValueTypeVector& duplicates, - DuplicateCallback callback) const; -}; - -} // namespace wabt - -#endif /* WABT_BINDING_HASH_H_ */ diff --git a/src/c-writer.cc b/src/c-writer.cc index c38a3c7a..0c90aa72 100644 --- a/src/c-writer.cc +++ b/src/c-writer.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/c-writer.h" +#include "wabt/c-writer.h" #include <cctype> #include <cinttypes> @@ -22,12 +22,12 @@ #include <set> #include <string_view> -#include "src/cast.h" -#include "src/common.h" -#include "src/ir.h" -#include "src/literal.h" -#include "src/stream.h" -#include "src/string-util.h" +#include "wabt/cast.h" +#include "wabt/common.h" +#include "wabt/ir.h" +#include "wabt/literal.h" +#include "wabt/stream.h" +#include "wabt/string-util.h" #define INDENT_SIZE 2 diff --git a/src/c-writer.h b/src/c-writer.h deleted file mode 100644 index 34033bca..00000000 --- a/src/c-writer.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_C_WRITER_H_ -#define WABT_C_WRITER_H_ - -#include "src/common.h" - -namespace wabt { - -struct Module; -class Stream; - -struct WriteCOptions { - std::string_view module_name; -}; - -Result WriteC(Stream* c_stream, - Stream* h_stream, - const char* header_name, - const Module*, - const WriteCOptions&); - -} // namespace wabt - -#endif /* WABT_C_WRITER_H_ */ diff --git a/src/cast.h b/src/cast.h deleted file mode 100644 index 72754150..00000000 --- a/src/cast.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_CAST_H_ -#define WABT_CAST_H_ - -#include <memory> -#include <type_traits> - -#include "src/common.h" - -// Modeled after LLVM's dynamic casts: -// http://llvm.org/docs/ProgrammersManual.html#the-isa-cast-and-dyn-cast-templates -// -// Use isa<T>(foo) to check whether foo is a T*: -// -// if (isa<Minivan>(car)) { -// ... -// } -// -// Use cast<T>(foo) when you know that foo is a T* -- it will assert that the -// type matches: -// -// switch (car.type) { -// case CarType::Minivan: { -// auto minivan = cast<Minivan>(car); -// ... -// } -// } -// -// Use dyn_cast<T>(foo) as a combination if isa and cast, it will return -// nullptr if the type doesn't match: -// -// if (auto minivan = dyn_cast<Minivan>(car)) { -// ... -// } -// -// -// To use these classes in a type hierarchy, you must implement classof: -// -// enum CarType { Minivan, ... }; -// struct Car { CarType type; ... }; -// struct Minivan : Car { -// static bool classof(const Car* car) { return car->type == Minivan; } -// ... -// }; -// - -namespace wabt { - -template <typename Derived, typename Base> -bool isa(const Base* base) { - WABT_STATIC_ASSERT((std::is_base_of<Base, Derived>::value)); - return Derived::classof(base); -} - -template <typename Derived, typename Base> -const Derived* cast(const Base* base) { - assert(isa<Derived>(base)); - return static_cast<const Derived*>(base); -}; - -template <typename Derived, typename Base> -Derived* cast(Base* base) { - assert(isa<Derived>(base)); - return static_cast<Derived*>(base); -}; - -template <typename Derived, typename Base> -const Derived* dyn_cast(const Base* base) { - return isa<Derived>(base) ? static_cast<const Derived*>(base) : nullptr; -}; - -template <typename Derived, typename Base> -Derived* dyn_cast(Base* base) { - return isa<Derived>(base) ? static_cast<Derived*>(base) : nullptr; -}; - -// Cast functionality for unique_ptr. isa and dyn_cast are not included because -// they won't always pass ownership back to the caller. - -template <typename Derived, typename Base> -std::unique_ptr<const Derived> cast(std::unique_ptr<const Base>&& base) { - assert(isa<Derived>(base.get())); - return std::unique_ptr<Derived>(static_cast<const Derived*>(base.release())); -}; - -template <typename Derived, typename Base> -std::unique_ptr<Derived> cast(std::unique_ptr<Base>&& base) { - assert(isa<Derived>(base.get())); - return std::unique_ptr<Derived>(static_cast<Derived*>(base.release())); -}; - -} // namespace wabt - -#endif // WABT_CAST_H_ diff --git a/src/circular-array.h b/src/circular-array.h deleted file mode 100644 index afdead77..00000000 --- a/src/circular-array.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_CIRCULAR_ARRAY_H_ -#define WABT_CIRCULAR_ARRAY_H_ - -#include <array> -#include <cassert> -#include <cstddef> -#include <type_traits> - -namespace wabt { - -// TODO(karlschimpf) Complete the API -// Note: Capacity must be a power of 2. -template <class T, size_t kCapacity> -class CircularArray { - public: - typedef T value_type; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - - CircularArray() { - static_assert(kCapacity && ((kCapacity & (kCapacity - 1)) == 0), - "Capacity must be a power of 2."); - } - - CircularArray(const CircularArray&) = default; - CircularArray& operator=(const CircularArray&) = default; - - CircularArray(CircularArray&&) = default; - CircularArray& operator=(CircularArray&&) = default; - - ~CircularArray() { clear(); } - - reference at(size_type index) { - assert(index < size_); - return (*this)[index]; - } - - const_reference at(size_type index) const { - assert(index < size_); - return (*this)[index]; - } - - reference operator[](size_type index) { return contents_[position(index)]; } - - const_reference operator[](size_type index) const { - return contents_[position(index)]; - } - - reference back() { return at(size_ - 1); } - - const_reference back() const { return at(size_ - 1); } - - bool empty() const { return size_ == 0; } - - reference front() { return at(0); } - - const_reference front() const { return at(0); } - - size_type max_size() const { return kCapacity; } - - void pop_back() { - assert(size_ > 0); - SetElement(back()); - --size_; - } - - void pop_front() { - assert(size_ > 0); - SetElement(front()); - front_ = (front_ + 1) & kMask; - --size_; - } - - void push_back(const value_type& value) { - assert(size_ < kCapacity); - SetElement(at(size_++), value); - } - - size_type size() const { return size_; } - - void clear() { - while (!empty()) { - pop_back(); - } - } - - private: - static const size_type kMask = kCapacity - 1; - - size_t position(size_t index) const { return (front_ + index) & kMask; } - - template <typename... Args> - void SetElement(reference element, Args&&... args) { - element.~T(); - new (&element) T(std::forward<Args>(args)...); - } - - std::array<T, kCapacity> contents_; - size_type size_ = 0; - size_type front_ = 0; -}; - -} // namespace wabt - -#endif // WABT_CIRCULAR_ARRAY_H_ diff --git a/src/color.cc b/src/color.cc index 8fdc5d00..6a756b92 100644 --- a/src/color.cc +++ b/src/color.cc @@ -14,11 +14,11 @@ * limitations under the License. */ -#include "src/color.h" +#include "wabt/color.h" #include <cstdlib> -#include "src/common.h" +#include "wabt/common.h" #if _WIN32 #include <io.h> diff --git a/src/color.h b/src/color.h deleted file mode 100644 index 8af57f33..00000000 --- a/src/color.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_COLOR_H_ -#define WABT_COLOR_H_ - -#include <cstdio> - -namespace wabt { - -#define WABT_FOREACH_COLOR_CODE(V) \ - V(Default, "\x1b[0m") \ - V(Bold, "\x1b[1m") \ - V(NoBold, "\x1b[22m") \ - V(Black, "\x1b[30m") \ - V(Red, "\x1b[31m") \ - V(Green, "\x1b[32m") \ - V(Yellow, "\x1b[33m") \ - V(Blue, "\x1b[34m") \ - V(Magenta, "\x1b[35m") \ - V(Cyan, "\x1b[36m") \ - V(White, "\x1b[37m") - -class Color { - public: - Color() : file_(nullptr), enabled_(false) {} - Color(FILE*, bool enabled = true); - -// Write the given color to the file, if enabled. -#define WABT_COLOR(Name, code) \ - void Name() const { WriteCode(Name##Code()); } - WABT_FOREACH_COLOR_CODE(WABT_COLOR) -#undef WABT_COLOR - -// Get the color code as a string, if enabled. -#define WABT_COLOR(Name, code) \ - const char* Maybe##Name##Code() const { return enabled_ ? Name##Code() : ""; } - WABT_FOREACH_COLOR_CODE(WABT_COLOR) -#undef WABT_COLOR - -// Get the color code as a string. -#define WABT_COLOR(Name, code) \ - static const char* Name##Code() { return code; } - WABT_FOREACH_COLOR_CODE(WABT_COLOR) -#undef WABT_COLOR - - private: - static bool SupportsColor(FILE*); - void WriteCode(const char*) const; - - FILE* file_; - bool enabled_; -}; - -#undef WABT_FOREACH_COLOR_CODE - -} // namespace wabt - -#endif // WABT_COLOR_H_ diff --git a/src/common.cc b/src/common.cc index a4c7a108..037b8304 100644 --- a/src/common.cc +++ b/src/common.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/common.h" +#include "wabt/common.h" #include <cassert> #include <cerrno> diff --git a/src/common.h b/src/common.h deleted file mode 100644 index bcd17039..00000000 --- a/src/common.h +++ /dev/null @@ -1,465 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_COMMON_H_ -#define WABT_COMMON_H_ - -#include <algorithm> -#include <cassert> -#include <cstdarg> -#include <cstddef> -#include <cstdint> -#include <cstdio> -#include <cstdlib> -#include <cstring> -#include <memory> -#include <string> -#include <string_view> -#include <type_traits> -#include <vector> - -#include "config.h" - -#include "src/base-types.h" -#include "src/make-unique.h" -#include "src/result.h" -#include "src/string-format.h" -#include "src/type.h" - -#define WABT_FATAL(...) fprintf(stderr, __VA_ARGS__), exit(1) -#define WABT_ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) - -#define WABT_USE(x) static_cast<void>(x) - -// 64k -#define WABT_PAGE_SIZE 0x10000 -// # of pages that fit in 32-bit address space -#define WABT_MAX_PAGES32 0x10000 -// # of pages that fit in 64-bit address space -#define WABT_MAX_PAGES64 0x1000000000000 -#define WABT_BYTES_TO_PAGES(x) ((x) >> 16) -#define WABT_ALIGN_UP_TO_PAGE(x) \ - (((x) + WABT_PAGE_SIZE - 1) & ~(WABT_PAGE_SIZE - 1)) - -#define WABT_ENUM_COUNT(name) \ - (static_cast<int>(name::Last) - static_cast<int>(name::First) + 1) - -#define WABT_DISALLOW_COPY_AND_ASSIGN(type) \ - type(const type&) = delete; \ - type& operator=(const type&) = delete; - -#if WITH_EXCEPTIONS -#define WABT_TRY try { -#define WABT_CATCH_BAD_ALLOC \ - } \ - catch (std::bad_alloc&) { \ - } -#define WABT_CATCH_BAD_ALLOC_AND_EXIT \ - } \ - catch (std::bad_alloc&) { \ - WABT_FATAL("Memory allocation failure.\n"); \ - } -#else -#define WABT_TRY -#define WABT_CATCH_BAD_ALLOC -#define WABT_CATCH_BAD_ALLOC_AND_EXIT -#endif - -#define PRIindex "u" -#define PRIaddress PRIu64 -#define PRIoffset PRIzx - -namespace wabt { -#if WABT_BIG_ENDIAN -inline void MemcpyEndianAware(void* dst, - const void* src, - size_t dsize, - size_t ssize, - size_t doff, - size_t soff, - size_t len) { - memcpy(static_cast<char*>(dst) + (dsize) - (len) - (doff), - static_cast<const char*>(src) + (ssize) - (len) - (soff), (len)); -} -#else -inline void MemcpyEndianAware(void* dst, - const void* src, - size_t dsize, - size_t ssize, - size_t doff, - size_t soff, - size_t len) { - memcpy(static_cast<char*>(dst) + (doff), - static_cast<const char*>(src) + (soff), (len)); -} -#endif -} - -struct v128 { - v128() = default; - v128(uint32_t x0, uint32_t x1, uint32_t x2, uint32_t x3) { - set_u32(0, x0); - set_u32(1, x1); - set_u32(2, x2); - set_u32(3, x3); - } - - bool operator==(const v128& other) const { - return std::equal(std::begin(v), std::end(v), std::begin(other.v)); - } - bool operator!=(const v128& other) const { return !(*this == other); } - - uint8_t u8(int lane) const { return To<uint8_t>(lane); } - uint16_t u16(int lane) const { return To<uint16_t>(lane); } - uint32_t u32(int lane) const { return To<uint32_t>(lane); } - uint64_t u64(int lane) const { return To<uint64_t>(lane); } - uint32_t f32_bits(int lane) const { return To<uint32_t>(lane); } - uint64_t f64_bits(int lane) const { return To<uint64_t>(lane); } - - void set_u8(int lane, uint8_t x) { return From<uint8_t>(lane, x); } - void set_u16(int lane, uint16_t x) { return From<uint16_t>(lane, x); } - void set_u32(int lane, uint32_t x) { return From<uint32_t>(lane, x); } - void set_u64(int lane, uint64_t x) { return From<uint64_t>(lane, x); } - void set_f32_bits(int lane, uint32_t x) { return From<uint32_t>(lane, x); } - void set_f64_bits(int lane, uint64_t x) { return From<uint64_t>(lane, x); } - - bool is_zero() const { - return std::all_of(std::begin(v), std::end(v), - [](uint8_t x) { return x == 0; }); - } - void set_zero() { std::fill(std::begin(v), std::end(v), 0); } - - template <typename T> - T To(int lane) const { - static_assert(sizeof(T) <= sizeof(v), "Invalid cast!"); - assert((lane + 1) * sizeof(T) <= sizeof(v)); - T result; - wabt::MemcpyEndianAware(&result, v, sizeof(result), sizeof(v), 0, - lane * sizeof(T), sizeof(result)); - return result; - } - - template <typename T> - void From(int lane, T data) { - static_assert(sizeof(T) <= sizeof(v), "Invalid cast!"); - assert((lane + 1) * sizeof(T) <= sizeof(v)); - wabt::MemcpyEndianAware(v, &data, sizeof(v), sizeof(data), lane * sizeof(T), - 0, sizeof(data)); - } - - uint8_t v[16]; -}; - -namespace wabt { - -template <typename Dst, typename Src> -Dst WABT_VECTORCALL Bitcast(Src&& value) { - static_assert(sizeof(Src) == sizeof(Dst), "Bitcast sizes must match."); - Dst result; - memcpy(&result, &value, sizeof(result)); - return result; -} - -template <typename T> -void ZeroMemory(T& v) { - WABT_STATIC_ASSERT(std::is_pod<T>::value); - memset(&v, 0, sizeof(v)); -} - -// Placement construct -template <typename T, typename... Args> -void Construct(T& placement, Args&&... args) { - new (&placement) T(std::forward<Args>(args)...); -} - -// Placement destruct -template <typename T> -void Destruct(T& placement) { - placement.~T(); -} - -enum class LabelType { - Func, - InitExpr, - Block, - Loop, - If, - Else, - Try, - Catch, - - First = Func, - Last = Catch, -}; -static const int kLabelTypeCount = WABT_ENUM_COUNT(LabelType); - -struct Location { - enum class Type { - Text, - Binary, - }; - - Location() : line(0), first_column(0), last_column(0) {} - Location(std::string_view filename, - int line, - int first_column, - int last_column) - : filename(filename), - line(line), - first_column(first_column), - last_column(last_column) {} - explicit Location(size_t offset) : offset(offset) {} - - std::string_view filename; - union { - // For text files. - struct { - int line; - int first_column; - int last_column; - }; - // For binary files. - struct { - size_t offset; - }; - }; -}; - -enum class SegmentKind { - Active, - Passive, - Declared, -}; - -// Used in test asserts for special expected values "nan:canonical" and -// "nan:arithmetic" -enum class ExpectedNan { - None, - Canonical, - Arithmetic, -}; - -// Matches binary format, do not change. -enum SegmentFlags : uint8_t { - SegFlagsNone = 0, - SegPassive = 1, // bit 0: Is passive - SegExplicitIndex = 2, // bit 1: Has explict index (Implies table 0 if absent) - SegDeclared = 3, // Only used for declared segments - SegUseElemExprs = 4, // bit 2: Is elemexpr (Or else index sequence) - - SegFlagMax = (SegUseElemExprs << 1) - 1, // All bits set. -}; - -enum class RelocType { - FuncIndexLEB = 0, // e.g. Immediate of call instruction - TableIndexSLEB = 1, // e.g. Loading address of function - TableIndexI32 = 2, // e.g. Function address in DATA - MemoryAddressLEB = 3, // e.g. Memory address in load/store offset immediate - MemoryAddressSLEB = 4, // e.g. Memory address in i32.const - MemoryAddressI32 = 5, // e.g. Memory address in DATA - TypeIndexLEB = 6, // e.g. Immediate type in call_indirect - GlobalIndexLEB = 7, // e.g. Immediate of global.get inst - FunctionOffsetI32 = 8, // e.g. Code offset in DWARF metadata - SectionOffsetI32 = 9, // e.g. Section offset in DWARF metadata - TagIndexLEB = 10, // Used in throw instructions - MemoryAddressRelSLEB = 11, // In PIC code, addr relative to __memory_base - TableIndexRelSLEB = 12, // In PIC code, table index relative to __table_base - GlobalIndexI32 = 13, // e.g. Global index in data (e.g. DWARF) - MemoryAddressLEB64 = 14, // Memory64: Like MemoryAddressLEB - MemoryAddressSLEB64 = 15, // Memory64: Like MemoryAddressSLEB - MemoryAddressI64 = 16, // Memory64: Like MemoryAddressI32 - MemoryAddressRelSLEB64 = 17, // Memory64: Like MemoryAddressRelSLEB - TableIndexSLEB64 = 18, // Memory64: Like TableIndexSLEB - TableIndexI64 = 19, // Memory64: Like TableIndexI32 - TableNumberLEB = 20, // e.g. Immediate of table.get - MemoryAddressTLSSLEB = 21, // Address relative to __tls_base - MemoryAddressTLSI32 = 22, // Address relative to __tls_base - - First = FuncIndexLEB, - Last = MemoryAddressTLSI32, -}; -static const int kRelocTypeCount = WABT_ENUM_COUNT(RelocType); - -struct Reloc { - Reloc(RelocType, size_t offset, Index index, int32_t addend = 0); - - RelocType type; - size_t offset; - Index index; - int32_t addend; -}; - -enum class LinkingEntryType { - SegmentInfo = 5, - InitFunctions = 6, - ComdatInfo = 7, - SymbolTable = 8, -}; - -enum class DylinkEntryType { - MemInfo = 1, - Needed = 2, - ExportInfo = 3, - ImportInfo = 4, -}; - -enum class SymbolType { - Function = 0, - Data = 1, - Global = 2, - Section = 3, - Tag = 4, - Table = 5, -}; - -enum class ComdatType { - Data = 0x0, - Function = 0x1, -}; - -#define WABT_SYMBOL_MASK_VISIBILITY 0x4 -#define WABT_SYMBOL_MASK_BINDING 0x3 -#define WABT_SYMBOL_FLAG_UNDEFINED 0x10 -#define WABT_SYMBOL_FLAG_EXPORTED 0x20 -#define WABT_SYMBOL_FLAG_EXPLICIT_NAME 0x40 -#define WABT_SYMBOL_FLAG_NO_STRIP 0x80 -#define WABT_SYMBOL_FLAG_TLS 0x100 -#define WABT_SYMBOL_FLAG_MAX 0x1ff - -#define WABT_SEGMENT_FLAG_STRINGS 0x1 -#define WABT_SEGMENT_FLAG_TLS 0x2 -#define WABT_SEGMENT_FLAG_MAX 0xff - -enum class SymbolVisibility { - Default = 0, - Hidden = 4, -}; - -enum class SymbolBinding { - Global = 0, - Weak = 1, - Local = 2, -}; - -/* matches binary format, do not change */ -enum class ExternalKind { - Func = 0, - Table = 1, - Memory = 2, - Global = 3, - Tag = 4, - - First = Func, - Last = Tag, -}; -static const int kExternalKindCount = WABT_ENUM_COUNT(ExternalKind); - -struct Limits { - Limits() = default; - explicit Limits(uint64_t initial) : initial(initial) {} - Limits(uint64_t initial, uint64_t max) - : initial(initial), max(max), has_max(true) {} - Limits(uint64_t initial, uint64_t max, bool is_shared) - : initial(initial), max(max), has_max(true), is_shared(is_shared) {} - Limits(uint64_t initial, uint64_t max, bool is_shared, bool is_64) - : initial(initial), - max(max), - has_max(true), - is_shared(is_shared), - is_64(is_64) {} - Type IndexType() const { return is_64 ? Type::I64 : Type::I32; } - - uint64_t initial = 0; - uint64_t max = 0; - bool has_max = false; - bool is_shared = false; - bool is_64 = false; -}; - -enum { WABT_USE_NATURAL_ALIGNMENT = 0xFFFFFFFFFFFFFFFF }; - -Result ReadFile(std::string_view filename, std::vector<uint8_t>* out_data); - -void InitStdio(); - -/* external kind */ - -extern const char* g_kind_name[]; - -static WABT_INLINE const char* GetKindName(ExternalKind kind) { - return static_cast<size_t>(kind) < kExternalKindCount - ? g_kind_name[static_cast<size_t>(kind)] - : "<error_kind>"; -} - -/* reloc */ - -extern const char* g_reloc_type_name[]; - -static WABT_INLINE const char* GetRelocTypeName(RelocType reloc) { - return static_cast<size_t>(reloc) < kRelocTypeCount - ? g_reloc_type_name[static_cast<size_t>(reloc)] - : "<error_reloc_type>"; -} - -/* symbol */ - -static WABT_INLINE const char* GetSymbolTypeName(SymbolType type) { - switch (type) { - case SymbolType::Function: - return "func"; - case SymbolType::Global: - return "global"; - case SymbolType::Data: - return "data"; - case SymbolType::Section: - return "section"; - case SymbolType::Tag: - return "tag"; - case SymbolType::Table: - return "table"; - default: - return "<error_symbol_type>"; - } -} - -template <typename T> -void ConvertBackslashToSlash(T begin, T end) { - std::replace(begin, end, '\\', '/'); -} - -inline void ConvertBackslashToSlash(char* s, size_t length) { - ConvertBackslashToSlash(s, s + length); -} - -inline void ConvertBackslashToSlash(char* s) { - ConvertBackslashToSlash(s, strlen(s)); -} - -inline void ConvertBackslashToSlash(std::string* s) { - ConvertBackslashToSlash(s->begin(), s->end()); -} - -inline void SwapBytesSized(void* addr, size_t size) { - auto bytes = static_cast<uint8_t*>(addr); - for (size_t i = 0; i < size / 2; i++) { - std::swap(bytes[i], bytes[size - 1 - i]); - } -} - -} // namespace wabt - -#endif // WABT_COMMON_H_ diff --git a/src/config.cc b/src/config.cc index 00f60aa8..ccf80e68 100644 --- a/src/config.cc +++ b/src/config.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "config.h" +#include "wabt/config.h" #include <cstdarg> #include <cstdio> diff --git a/src/decompiler-ast.h b/src/decompiler-ast.h deleted file mode 100644 index e5dd358e..00000000 --- a/src/decompiler-ast.h +++ /dev/null @@ -1,406 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_DECOMPILER_AST_H_ -#define WABT_DECOMPILER_AST_H_ - -#include "src/cast.h" -#include "src/generate-names.h" -#include "src/ir-util.h" -#include "src/ir.h" - -#include <map> - -namespace wabt { - -enum class NodeType { - Uninitialized, - FlushToVars, - FlushedVar, - Statements, - EndReturn, - Decl, - DeclInit, - Expr -}; - -// The AST we're going to convert the standard IR into. -struct Node { - NodeType ntype; - ExprType etype; // Only if ntype == Expr. - const Expr* e; - std::vector<Node> children; - // Node specific annotations. - union { - struct { - Index var_start, var_count; // FlushedVar/FlushToVars - }; - const Var* var; // Decl/DeclInit. - LabelType lt; // br/br_if target. - } u; - - Node() : ntype(NodeType::Uninitialized), etype(ExprType::Nop), e(nullptr) {} - Node(NodeType ntype, ExprType etype, const Expr* e, const Var* v) - : ntype(ntype), etype(etype), e(e) { - u.var = v; - } - - // This value should really never be copied, only moved. - Node(const Node& rhs) = delete; - Node& operator=(const Node& rhs) = delete; - - Node(Node&& rhs) { *this = std::move(rhs); } - Node& operator=(Node&& rhs) { - ntype = rhs.ntype; - // Reset ntype to avoid moved from values still being used. - rhs.ntype = NodeType::Uninitialized; - etype = rhs.etype; - rhs.etype = ExprType::Nop; - e = rhs.e; - std::swap(children, rhs.children); - u = rhs.u; - return *this; - } -}; - -struct AST { - AST(ModuleContext& mc, const Func* f) : mc(mc), f(f) { - if (f) { - mc.BeginFunc(*f); - for (Index i = 0; i < f->GetNumParams(); i++) { - auto name = "$" + IndexToAlphaName(i); - vars_defined.insert({name, {0, false}}); - } - } - } - - ~AST() { - if (f) { - mc.EndFunc(); - } - } - - // Create a new node, take nargs existing nodes on the exp stack as children. - Node& InsertNode(NodeType ntype, ExprType etype, const Expr* e, Index nargs) { - assert(exp_stack.size() >= nargs); - Node n{ntype, etype, e, nullptr}; - n.children.reserve(nargs); - std::move(exp_stack.end() - nargs, exp_stack.end(), - std::back_inserter(n.children)); - exp_stack.erase(exp_stack.end() - nargs, exp_stack.end()); - exp_stack.push_back(std::move(n)); - return exp_stack.back(); - } - - template <ExprType T> - void PreDecl(const VarExpr<T>& ve) { - // FIXME: this is slow, and would be better to avoid in callers. - // See https://github.com/WebAssembly/wabt/issues/1565 - // And https://github.com/WebAssembly/wabt/issues/1665 - for (auto& n : predecls) { - if (n.u.var->name() == ve.var.name()) { - return; - } - } - predecls.emplace_back(NodeType::Decl, ExprType::Nop, nullptr, &ve.var); - } - - template <ExprType T> - void Get(const VarExpr<T>& ve, bool local) { - if (local) { - auto ret = vars_defined.insert({ve.var.name(), {cur_block_id, false}}); - if (ret.second) { - // Use before def, may happen since locals are guaranteed 0. - PreDecl(ve); - } else if (blocks_closed[ret.first->second.block_id]) { - // This is a use of a variable that was defined in a block that has - // already ended. This happens rarely, but we should cater for this - // case by lifting it to the top scope. - PreDecl(ve); - } - } - InsertNode(NodeType::Expr, T, &ve, 0); - } - - template <ExprType T> - void Set(const VarExpr<T>& ve, bool local) { - // Seen this var before? - if (local && - vars_defined.insert({ve.var.name(), {cur_block_id, false}}).second) { - if (value_stack_depth == 1) { - // Top level, declare it here. - InsertNode(NodeType::DeclInit, ExprType::Nop, nullptr, 1).u.var = - &ve.var; - return; - } else { - // Inside exp, better leave it as assignment exp and lift the decl out. - PreDecl(ve); - } - } - InsertNode(NodeType::Expr, T, &ve, 1); - } - - template <ExprType T> - void Block(const BlockExprBase<T>& be, LabelType label) { - mc.BeginBlock(label, be.block); - Construct(be.block.exprs, be.block.decl.GetNumResults(), - be.block.decl.GetNumParams(), false); - mc.EndBlock(); - InsertNode(NodeType::Expr, T, &be, 1); - } - - void Construct(const Expr& e) { - auto arity = mc.GetExprArity(e); - switch (e.type()) { - case ExprType::LocalGet: { - Get(*cast<LocalGetExpr>(&e), true); - return; - } - case ExprType::GlobalGet: { - Get(*cast<GlobalGetExpr>(&e), false); - return; - } - case ExprType::LocalSet: { - Set(*cast<LocalSetExpr>(&e), true); - return; - } - case ExprType::GlobalSet: { - Set(*cast<GlobalSetExpr>(&e), false); - return; - } - case ExprType::LocalTee: { - auto& lt = *cast<LocalTeeExpr>(&e); - Set(lt, true); - if (value_stack_depth == 1) { // Tee is the only thing on there. - Get(lt, true); // Now Set + Get instead. - } else { - // Things are above us on the stack so the Tee can't be eliminated. - // The Set makes this work as a Tee when consumed by a parent. - } - return; - } - case ExprType::If: { - auto ife = cast<IfExpr>(&e); - value_stack_depth--; // Condition. - mc.BeginBlock(LabelType::Block, ife->true_); - Construct(ife->true_.exprs, ife->true_.decl.GetNumResults(), - ife->true_.decl.GetNumParams(), false); - if (!ife->false_.empty()) { - Construct(ife->false_, ife->true_.decl.GetNumResults(), - ife->true_.decl.GetNumParams(), false); - } - mc.EndBlock(); - value_stack_depth++; // Put Condition back. - InsertNode(NodeType::Expr, ExprType::If, &e, - ife->false_.empty() ? 2 : 3); - return; - } - case ExprType::Block: { - Block(*cast<BlockExpr>(&e), LabelType::Block); - return; - } - case ExprType::Loop: { - Block(*cast<LoopExpr>(&e), LabelType::Loop); - return; - } - case ExprType::Br: { - InsertNode(NodeType::Expr, ExprType::Br, &e, 0).u.lt = - mc.GetLabel(cast<BrExpr>(&e)->var)->label_type; - return; - } - case ExprType::BrIf: { - InsertNode(NodeType::Expr, ExprType::BrIf, &e, 1).u.lt = - mc.GetLabel(cast<BrIfExpr>(&e)->var)->label_type; - return; - } - case ExprType::BrTable: { - InsertNode(NodeType::Expr, ExprType::BrTable, &e, 1).u.lt = - mc.GetLabel(cast<BrTableExpr>(&e)->default_target)->label_type; - return; - } - default: { - InsertNode(NodeType::Expr, e.type(), &e, arity.nargs); - return; - } - } - } - - void Construct(const ExprList& es, - Index nresults, - Index nparams, - bool is_function_body) { - block_stack.push_back(cur_block_id); - cur_block_id = blocks_closed.size(); - blocks_closed.push_back(false); - auto start = exp_stack.size(); - int value_stack_depth_start = value_stack_depth - nparams; - auto value_stack_in_variables = value_stack_depth; - bool unreachable = false; - for (auto& e : es) { - Construct(e); - auto arity = mc.GetExprArity(e); - value_stack_depth -= arity.nargs; - value_stack_in_variables = - std::min(value_stack_in_variables, value_stack_depth); - unreachable = unreachable || arity.unreachable; - assert(unreachable || value_stack_depth >= value_stack_depth_start); - value_stack_depth += arity.nreturns; - // We maintain the invariant that a value_stack_depth of N is represented - // by the last N exp_stack items (each of which returning exactly 1 - // value), all exp_stack items before it return void ("statements"). - // In particular for the wasm stack: - // - The values between 0 and value_stack_depth_start are part of the - // parent block, and not touched here. - // - The values from there up to value_stack_in_variables are variables - // to be used, representing previous statements that flushed the - // stack into variables. - // - Values on top of that up to value_stack_depth are exps returning - // a single value. - // The code below maintains the above invariants. With this in place - // code "falls into place" the way you expect it. - if (arity.nreturns != 1) { - auto num_vars = value_stack_in_variables - value_stack_depth_start; - auto num_vals = value_stack_depth - value_stack_in_variables; - auto GenFlushVars = [&](int nargs) { - auto& ftv = - InsertNode(NodeType::FlushToVars, ExprType::Nop, nullptr, nargs); - ftv.u.var_start = flushed_vars; - ftv.u.var_count = num_vals; - }; - auto MoveStatementsBelowVars = [&](size_t amount) { - std::rotate(exp_stack.end() - num_vars - amount, - exp_stack.end() - amount, exp_stack.end()); - }; - auto GenFlushedVars = [&]() { - // Re-generate these values as vars. - for (int i = 0; i < num_vals; i++) { - auto& fv = - InsertNode(NodeType::FlushedVar, ExprType::Nop, nullptr, 0); - fv.u.var_start = flushed_vars++; - fv.u.var_count = 1; - } - }; - if (arity.nreturns == 0 && - value_stack_depth > value_stack_depth_start) { - // We have a void item on top of the exp_stack, so we must "lift" the - // previous values around it. - // We track what part of the stack is in variables to avoid doing - // this unnecessarily. - if (num_vals > 0) { - // We have actual new values that need lifting. - // This puts the part of the stack that wasn't already a variable - // (before the current void exp) into a FlushToVars. - auto void_exp = std::move(exp_stack.back()); - exp_stack.pop_back(); - GenFlushVars(num_vals); - exp_stack.push_back(std::move(void_exp)); - // Put this flush statement + void statement before any - // existing variables. - MoveStatementsBelowVars(2); - // Now re-generate these values after the void exp as vars. - GenFlushedVars(); - } else { - // We have existing variables that need lifting, but no need to - // create them anew. - std::rotate(exp_stack.end() - num_vars - 1, exp_stack.end() - 1, - exp_stack.end()); - } - value_stack_in_variables = value_stack_depth; - } else if (arity.nreturns > 1) { - // Multivalue: we flush the stack also. - // Number of other non-variable values that may be present: - assert(num_vals >= static_cast<int>(arity.nreturns)); - // Flush multi-value exp + others. - GenFlushVars(num_vals - arity.nreturns + 1); - // Put this flush statement before any existing variables. - MoveStatementsBelowVars(1); - GenFlushedVars(); - value_stack_in_variables = value_stack_depth; - } - } else { - // Special optimisation: for constant instructions, we can mark these - // as if they were variables, so they can be re-ordered for free with - // the above code, without needing new variables! - // TODO: this would be nice to also do for local.get and maybe others, - // though that needs a way to ensure there's no local.set in between - // when they get lifted, so complicates matters a bit. - if (e.type() == ExprType::Const && - value_stack_in_variables == value_stack_depth - 1) { - value_stack_in_variables++; - } - } - } - assert(unreachable || value_stack_depth - value_stack_depth_start == - static_cast<int>(nresults)); - // Undo any changes to value_stack_depth, since parent takes care of arity - // changes. - value_stack_depth = value_stack_depth_start; - auto end = exp_stack.size(); - assert(end >= start); - if (is_function_body) { - if (!exp_stack.empty()) { - if (exp_stack.back().etype == ExprType::Return) { - if (exp_stack.back().children.empty()) { - // Return statement at the end of a void function. - exp_stack.pop_back(); - } - } else if (nresults) { - // Combine nresults into a return statement, for when this is used as - // a function body. - // TODO: if this is some other kind of block and >1 value is being - // returned, probably need some kind of syntax to make that clearer. - InsertNode(NodeType::EndReturn, ExprType::Nop, nullptr, nresults); - } - } - // TODO: these predecls are always at top level, but in the case of - // use inside an exp, it be nice to do it in the current block. Can't - // do that for predecls that are "out if scope" however. - std::move(predecls.begin(), predecls.end(), - std::back_inserter(exp_stack)); - std::rotate(exp_stack.begin(), exp_stack.end() - predecls.size(), - exp_stack.end()); - predecls.clear(); - } - end = exp_stack.size(); - assert(end >= start); - auto size = end - start; - if (size != 1) { - InsertNode(NodeType::Statements, ExprType::Nop, nullptr, size); - } - blocks_closed[cur_block_id] = true; - cur_block_id = block_stack.back(); - block_stack.pop_back(); - } - - ModuleContext& mc; - std::vector<Node> exp_stack; - std::vector<Node> predecls; - const Func* f; - int value_stack_depth = 0; - struct Variable { - size_t block_id; - bool defined; - }; - std::map<std::string, Variable> vars_defined; - Index flushed_vars = 0; - size_t cur_block_id = 0; - std::vector<size_t> block_stack; - std::vector<bool> blocks_closed; -}; - -} // namespace wabt - -#endif // WABT_DECOMPILER_AST_H_ diff --git a/src/decompiler-ls.h b/src/decompiler-ls.h deleted file mode 100644 index 3e68dad3..00000000 --- a/src/decompiler-ls.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2019 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_DECOMPILER_LS_H_ -#define WABT_DECOMPILER_LS_H_ - -#include "src/decompiler-ast.h" -#include "src/string-util.h" - -#include <map> - -namespace wabt { - -// Names starting with "u" are unsigned, the rest are "signed or doesn't matter" -inline const char* GetDecompTypeName(Type t) { - switch (t) { - case Type::I8: return "byte"; - case Type::I8U: return "ubyte"; - case Type::I16: return "short"; - case Type::I16U: return "ushort"; - case Type::I32: return "int"; - case Type::I32U: return "uint"; - case Type::I64: return "long"; - case Type::F32: return "float"; - case Type::F64: return "double"; - case Type::V128: return "simd"; - case Type::Func: return "func"; - case Type::FuncRef: return "funcref"; - case Type::ExternRef: return "externref"; - case Type::Void: return "void"; - default: return "ILLEGAL"; - } -} - -inline Type GetMemoryType(Type operand_type, Opcode opc) { - // TODO: something something SIMD. - // TODO: this loses information of the type it is read into. - // That may well not be the biggest deal since that is usually obvious - // from context, if not, we should probably represent that as a cast around - // the access, since it should not be part of the field type. - if (operand_type == Type::I32 || operand_type == Type::I64) { - auto name = std::string_view(opc.GetName()); - // FIXME: change into a new column in opcode.def instead? - auto is_unsigned = name.substr(name.size() - 2) == "_u"; - switch (opc.GetMemorySize()) { - case 1: return is_unsigned ? Type::I8U : Type::I8; - case 2: return is_unsigned ? Type::I16U : Type::I16; - case 4: return is_unsigned ? Type::I32U : Type::I32; - } - } - return operand_type; -} - -// Track all loads and stores inside a single function, to be able to detect -// struct layouts we can use to annotate variables with, to make code more -// readable. -struct LoadStoreTracking { - struct LSAccess { - Address byte_size = 0; - Type type = Type::Any; - Address align = 0; - uint32_t idx = 0; - bool is_uniform = true; - }; - - struct LSVar { - std::map<uint64_t, LSAccess> accesses; - bool struct_layout = true; - Type same_type = Type::Any; - Address same_align = kInvalidAddress; - Opcode last_opc; - }; - - void Track(const Node& n) { - for (auto& c : n.children) { - Track(c); - } - switch (n.etype) { - case ExprType::Load: { - auto& le = *cast<LoadExpr>(n.e); - LoadStore(le.offset, le.opcode, le.opcode.GetResultType(), le.align, - n.children[0]); - break; - } - case ExprType::Store: { - auto& se = *cast<StoreExpr>(n.e); - LoadStore(se.offset, se.opcode, se.opcode.GetParamType2(), se.align, - n.children[0]); - break; - } - default: - break; - } - } - - const std::string AddrExpName(const Node& addr_exp) const { - // TODO: expand this to more kinds of address expressions. - switch (addr_exp.etype) { - case ExprType::LocalGet: - return cast<LocalGetExpr>(addr_exp.e)->var.name(); - break; - case ExprType::LocalTee: - return cast<LocalTeeExpr>(addr_exp.e)->var.name(); - break; - default: - return ""; - } - } - - void LoadStore(uint64_t offset, - Opcode opc, - Type type, - Address align, - const Node& addr_exp) { - auto byte_size = opc.GetMemorySize(); - type = GetMemoryType(type, opc); - // We want to associate memory ops of a certain offset & size as being - // relative to a uniquely identifiable pointer, such as a local. - auto name = AddrExpName(addr_exp); - if (name.empty()) { - return; - } - auto& var = vars[name]; - auto& access = var.accesses[offset]; - // Check if previous access at this offset (if any) is of same size - // and type (see Checklayouts below). - if (access.byte_size && ((access.byte_size != byte_size) || - (access.type != type) || (access.align != align))) - access.is_uniform = false; - // Also exclude weird alignment accesses from structs. - if (!opc.IsNaturallyAligned(align)) - access.is_uniform = false; - access.byte_size = byte_size; - access.type = type; - access.align = align; - // Additionally, check if all accesses are to the same type, so - // if layout check fails, we can at least declare it as pointer to - // a type. - if ((var.same_type == type || var.same_type == Type::Any) && - (var.same_align == align || var.same_align == kInvalidAddress)) { - var.same_type = type; - var.same_align = align; - var.last_opc = opc; - } else { - var.same_type = Type::Void; - var.same_align = kInvalidAddress; - } - } - - void CheckLayouts() { - // Here we check if the set of accesses we have collected form a sequence - // we could declare as a struct, meaning they are properly aligned, - // contiguous, and have no overlaps between different types and sizes. - // We do this because an int access of size 2 at offset 0 followed by - // a float access of size 4 at offset 4 can compactly represented as a - // struct { short, float }, whereas something that reads from overlapping - // or discontinuous offsets would need a more complicated syntax that - // involves explicit offsets. - // We assume that the bulk of memory accesses are of this very regular kind, - // so we choose not to even emit struct layouts for irregular ones, - // given that they are rare and confusing, and thus do not benefit from - // being represented as if they were structs. - for (auto& var : vars) { - if (var.second.accesses.size() == 1) { - // If we have just one access, this is better represented as a pointer - // than a struct. - var.second.struct_layout = false; - continue; - } - uint64_t cur_offset = 0; - uint32_t idx = 0; - for (auto& access : var.second.accesses) { - access.second.idx = idx++; - if (!access.second.is_uniform) { - var.second.struct_layout = false; - break; - } - // Align to next access: all elements are expected to be aligned to - // a memory address thats a multiple of their own size. - auto mask = static_cast<uint64_t>(access.second.byte_size - 1); - cur_offset = (cur_offset + mask) & ~mask; - if (cur_offset != access.first) { - var.second.struct_layout = false; - break; - } - cur_offset += access.second.byte_size; - } - } - } - - std::string IdxToName(uint32_t idx) const { - return IndexToAlphaName(idx); // TODO: more descriptive names? - } - - std::string GenAlign(Address align, Opcode opc) const { - return opc.IsNaturallyAligned(align) ? "" : cat("@", std::to_string(align)); - } - - std::string GenTypeDecl(const std::string& name) const { - auto it = vars.find(name); - if (it == vars.end()) { - return ""; - } - if (it->second.struct_layout) { - std::string s = "{ "; - for (auto& access : it->second.accesses) { - if (access.second.idx) { - s += ", "; - } - s += IdxToName(access.second.idx); - s += ':'; - s += GetDecompTypeName(access.second.type); - } - s += " }"; - return s; - } - // We don't have a struct layout, or the struct has just one field, - // so maybe we can just declare it as a pointer to one type? - if (it->second.same_type != Type::Void) { - return cat(GetDecompTypeName(it->second.same_type), "_ptr", - GenAlign(it->second.same_align, it->second.last_opc)); - } - return ""; - } - - std::string GenAccess(uint64_t offset, const Node& addr_exp) const { - auto name = AddrExpName(addr_exp); - if (name.empty()) { - return ""; - } - auto it = vars.find(name); - if (it == vars.end()) { - return ""; - } - if (it->second.struct_layout) { - auto ait = it->second.accesses.find(offset); - assert(ait != it->second.accesses.end()); - return IdxToName(ait->second.idx); - } - // Not a struct, see if it is a typed pointer. - if (it->second.same_type != Type::Void) { - return "*"; - } - return ""; - } - - void Clear() { vars.clear(); } - - std::map<std::string, LSVar> vars; -}; - -} // namespace wabt - -#endif // WABT_DECOMPILER_LS_H_ diff --git a/src/decompiler-naming.h b/src/decompiler-naming.h deleted file mode 100644 index bb7a0819..00000000 --- a/src/decompiler-naming.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2019 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_DECOMPILER_NAMING_H_ -#define WABT_DECOMPILER_NAMING_H_ - -#include "src/decompiler-ast.h" - -#include <set> - -namespace wabt { - -inline void RenameToIdentifier(std::string& name, - Index i, - BindingHash& bh, - const std::set<std::string_view>* filter) { - // Filter out non-identifier characters, and try to reduce the size of - // gigantic C++ signature names. - std::string s; - size_t nesting = 0; - size_t read = 0; - size_t word_start = 0; - for (auto c : name) { - read++; - // We most certainly don't want to parse the entirety of C++ signatures, - // but these names are sometimes several lines long, so would be great - // to trim down. One quick way to do that is to remove anything between - // nested (), which usually means the parameter list. - if (c == '(') { - nesting++; - } - if (c == ')') { - nesting--; - } - if (nesting) { - continue; - } - if (!isalnum(static_cast<unsigned char>(c))) { - c = '_'; - } - if (c == '_') { - if (s.empty()) { - continue; // Skip leading. - } - if (s.back() == '_') { - continue; // Consecutive. - } - } - s += c; - if (filter && (c == '_' || read == name.size())) { - // We found a "word" inside a snake_case identifier. - auto word_end = s.size(); - if (c == '_') { - word_end--; - } - assert(word_end > word_start); - auto word = - std::string_view(s.c_str() + word_start, word_end - word_start); - if (filter->find(word) != filter->end()) { - s.resize(word_start); - } - word_start = s.size(); - } - } - if (!s.empty() && s.back() == '_') { - s.pop_back(); // Trailing. - } - // If after all this culling, we're still gigantic (STL identifier can - // easily be hundreds of chars in size), just cut the identifier - // down, it will be disambiguated below, if needed. - const size_t max_identifier_length = 100; - if (s.size() > max_identifier_length) { - s.resize(max_identifier_length); - } - if (s.empty()) { - s = "__empty"; - } - // Remove original binding first, such that it doesn't match with our - // new name. - bh.erase(name); - // Find a unique name. - Index disambiguator = 0; - auto base_len = s.size(); - for (;;) { - if (bh.count(s) == 0) { - break; - } - disambiguator++; - s.resize(base_len); - s += '_'; - s += std::to_string(disambiguator); - } - // Replace name in bindings. - name = s; - bh.emplace(s, Binding(i)); -} - -template <typename T> -void RenameToIdentifiers(std::vector<T*>& things, - BindingHash& bh, - const std::set<std::string_view>* filter) { - Index i = 0; - for (auto thing : things) { - RenameToIdentifier(thing->name, i++, bh, filter); - } -} - -enum { - // This a bit arbitrary, change at will. - min_content_identifier_size = 7, - max_content_identifier_size = 30 -}; - -void RenameToContents(std::vector<DataSegment*>& segs, BindingHash& bh) { - std::string s; - for (auto seg : segs) { - if (seg->name.substr(0, 2) != "d_") { - // This segment was named explicitly by a symbol. - // FIXME: this is not a great check, a symbol could start with d_. - continue; - } - s = "d_"; - for (auto c : seg->data) { - if (isalnum(c) || c == '_') { - s += static_cast<char>(c); - } - if (s.size() >= max_content_identifier_size) { - // We truncate any very long names, since those make for hard to - // format output. They can be somewhat long though, since data segment - // references tend to not occur that often. - break; - } - } - if (s.size() < min_content_identifier_size) { - // It is useful to have a minimum, since if there few printable characters - // in a data section, that is probably a sign of binary, and those few - // characters are not going to be very significant. - continue; - } - // We could do the same disambiguition as RenameToIdentifier and - // GenerateNames do, but if we come up with a clashing name here it is - // likely a sign of not very meaningful binary data, so it is easier to - // just keep the original generated name in that case. - if (bh.count(s) != 0) { - continue; - } - // Remove original entry. - bh.erase(seg->name); - seg->name = s; - bh.emplace(s, Binding(static_cast<Index>(&seg - &segs[0]))); - } -} - -// Function names may contain arbitrary C++ syntax, so we want to -// filter those to look like identifiers. A function name may be set -// by a name section (applied in ReadBinaryIr, called before this function) -// or by an export (applied by GenerateNames, called before this function), -// to both the Func and func_bindings. -// Those names then further perculate down the IR in ApplyNames (called after -// this function). -// To not have to add too many decompiler-specific code into those systems -// (using a callback??) we instead rename everything here. -// Also do data section renaming here. -void RenameAll(Module& module) { - // We also filter common C++ keywords/STL idents that make for huge - // identifiers. - // FIXME: this can obviously give bad results if the input is not C++.. - std::set<std::string_view> filter = { - {"const"}, {"std"}, {"allocator"}, {"char"}, {"basic"}, - {"traits"}, {"wchar"}, {"t"}, {"void"}, {"int"}, - {"unsigned"}, {"2"}, {"cxxabiv1"}, {"short"}, {"4096ul"}, - }; - RenameToIdentifiers(module.funcs, module.func_bindings, &filter); - // Also do this for some other kinds of names, but without the keyword - // substitution. - RenameToIdentifiers(module.globals, module.global_bindings, nullptr); - RenameToIdentifiers(module.tables, module.table_bindings, nullptr); - RenameToIdentifiers(module.tags, module.tag_bindings, nullptr); - RenameToIdentifiers(module.exports, module.export_bindings, nullptr); - RenameToIdentifiers(module.types, module.type_bindings, nullptr); - RenameToIdentifiers(module.memories, module.memory_bindings, nullptr); - RenameToIdentifiers(module.data_segments, module.data_segment_bindings, - nullptr); - RenameToIdentifiers(module.elem_segments, module.elem_segment_bindings, - nullptr); - // Special purpose naming for data segments. - RenameToContents(module.data_segments, module.data_segment_bindings); -} - -} // namespace wabt - -#endif // WABT_DECOMPILER_NAMING_H_ diff --git a/src/decompiler.cc b/src/decompiler.cc index 09fa6950..dd8eb767 100644 --- a/src/decompiler.cc +++ b/src/decompiler.cc @@ -14,16 +14,16 @@ * limitations under the License. */ -#include "src/decompiler.h" +#include "wabt/decompiler.h" -#include "src/decompiler-ast.h" -#include "src/decompiler-ls.h" -#include "src/decompiler-naming.h" +#include "wabt/decompiler-ast.h" +#include "wabt/decompiler-ls.h" +#include "wabt/decompiler-naming.h" -#include "src/stream.h" +#include "wabt/stream.h" #define WABT_TRACING 0 -#include "src/tracing.h" +#include "wabt/tracing.h" #include <inttypes.h> diff --git a/src/decompiler.h b/src/decompiler.h deleted file mode 100644 index e52a8215..00000000 --- a/src/decompiler.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_DECOMPILER_H_ -#define WABT_DECOMPILER_H_ - -#include "src/common.h" - -namespace wabt { - -struct Module; -class Stream; - -struct DecompileOptions {}; - -void RenameAll(Module&); - -std::string Decompile(const Module&, const DecompileOptions&); - -} // namespace wabt - -#endif /* WABT_DECOMPILER_H_ */ diff --git a/src/emscripten-helpers.cc b/src/emscripten-helpers.cc index 4f5a0c4a..cd050f6d 100644 --- a/src/emscripten-helpers.cc +++ b/src/emscripten-helpers.cc @@ -25,22 +25,22 @@ #include <utility> #include <vector> -#include "src/apply-names.h" -#include "src/binary-reader-ir.h" -#include "src/binary-reader.h" -#include "src/binary-writer-spec.h" -#include "src/binary-writer.h" -#include "src/common.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/filenames.h" -#include "src/generate-names.h" -#include "src/ir.h" -#include "src/stream.h" -#include "src/validator.h" -#include "src/wast-lexer.h" -#include "src/wast-parser.h" -#include "src/wat-writer.h" +#include "wabt/apply-names.h" +#include "wabt/binary-reader-ir.h" +#include "wabt/binary-reader.h" +#include "wabt/binary-writer-spec.h" +#include "wabt/binary-writer.h" +#include "wabt/common.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/filenames.h" +#include "wabt/generate-names.h" +#include "wabt/ir.h" +#include "wabt/stream.h" +#include "wabt/validator.h" +#include "wabt/wast-lexer.h" +#include "wabt/wast-parser.h" +#include "wabt/wat-writer.h" typedef std::unique_ptr<wabt::OutputBuffer> WabtOutputBufferPtr; typedef std::pair<std::string, WabtOutputBufferPtr> @@ -91,7 +91,7 @@ void wabt_destroy_features(wabt::Features* f) { void wabt_set_##variable##_enabled(wabt::Features* f, int enabled) { \ f->set_##variable##_enabled(enabled); \ } -#include "src/feature.def" +#include "wabt/feature.def" #undef WABT_FEATURE wabt::WastLexer* wabt_new_wast_buffer_lexer(const char* filename, diff --git a/src/error-formatter.cc b/src/error-formatter.cc index aa4995a5..5b0d4952 100644 --- a/src/error-formatter.cc +++ b/src/error-formatter.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/error-formatter.h" +#include "wabt/error-formatter.h" namespace wabt { diff --git a/src/error-formatter.h b/src/error-formatter.h deleted file mode 100644 index 7d28a8f9..00000000 --- a/src/error-formatter.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2018 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_ERROR_FORMATTER_H_ -#define WABT_ERROR_FORMATTER_H_ - -#include <cstdio> -#include <memory> -#include <string> - -#include "src/color.h" -#include "src/error.h" -#include "src/lexer-source-line-finder.h" - -namespace wabt { - -enum class PrintHeader { - Never, - Once, - Always, -}; - -std::string FormatErrorsToString(const Errors&, - Location::Type, - LexerSourceLineFinder* = nullptr, - const Color& color = Color(nullptr, false), - const std::string& header = {}, - PrintHeader print_header = PrintHeader::Never, - int source_line_max_length = 80); - -void FormatErrorsToFile(const Errors&, - Location::Type, - LexerSourceLineFinder* = nullptr, - FILE* = stderr, - const std::string& header = {}, - PrintHeader print_header = PrintHeader::Never, - int source_line_max_length = 80); - -} // namespace wabt - -#endif // WABT_ERROR_FORMATTER_H_ diff --git a/src/error.h b/src/error.h deleted file mode 100644 index 4f3375ab..00000000 --- a/src/error.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2018 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_ERROR_H_ -#define WABT_ERROR_H_ - -#include <string> -#include <string_view> -#include <vector> - -#include "src/common.h" - -namespace wabt { - -enum class ErrorLevel { - Warning, - Error, -}; - -static WABT_INLINE const char* GetErrorLevelName(ErrorLevel error_level) { - switch (error_level) { - case ErrorLevel::Warning: - return "warning"; - case ErrorLevel::Error: - return "error"; - } - WABT_UNREACHABLE; -} - -class Error { - public: - Error() : error_level(ErrorLevel::Error) {} - Error(ErrorLevel error_level, Location loc, std::string_view message) - : error_level(error_level), loc(loc), message(message) {} - - ErrorLevel error_level; - Location loc; - std::string message; -}; - -using Errors = std::vector<Error>; - -} // namespace wabt - -#endif // WABT_ERROR_H_ diff --git a/src/expr-visitor.cc b/src/expr-visitor.cc index e7fee9bf..05cd2798 100644 --- a/src/expr-visitor.cc +++ b/src/expr-visitor.cc @@ -14,10 +14,10 @@ * limitations under the License. */ -#include "src/expr-visitor.h" +#include "wabt/expr-visitor.h" -#include "src/cast.h" -#include "src/ir.h" +#include "wabt/cast.h" +#include "wabt/ir.h" namespace wabt { diff --git a/src/expr-visitor.h b/src/expr-visitor.h deleted file mode 100644 index e00c487d..00000000 --- a/src/expr-visitor.h +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_EXPR_VISITOR_H_ -#define WABT_EXPR_VISITOR_H_ - -#include "src/common.h" -#include "src/ir.h" - -namespace wabt { - -class ExprVisitor { - public: - class Delegate; - class DelegateNop; - - explicit ExprVisitor(Delegate* delegate); - - Result VisitExpr(Expr*); - Result VisitExprList(ExprList&); - Result VisitFunc(Func*); - - private: - enum class State { - Default, - Block, - IfTrue, - IfFalse, - Loop, - Try, - Catch, - }; - - Result HandleDefaultState(Expr*); - void PushDefault(Expr*); - void PopDefault(); - void PushExprlist(State state, Expr*, ExprList&); - void PopExprlist(); - void PushCatch(Expr*, Index catch_index, ExprList&); - void PopCatch(); - - Delegate* delegate_; - - // Use parallel arrays instead of array of structs so we can avoid allocating - // unneeded objects. ExprList::iterator has no default constructor, so it - // must only be allocated for states that use it. - std::vector<State> state_stack_; - std::vector<Expr*> expr_stack_; - std::vector<ExprList::iterator> expr_iter_stack_; - std::vector<Index> catch_index_stack_; -}; - -class ExprVisitor::Delegate { - public: - virtual ~Delegate() {} - - virtual Result OnBinaryExpr(BinaryExpr*) = 0; - virtual Result BeginBlockExpr(BlockExpr*) = 0; - virtual Result EndBlockExpr(BlockExpr*) = 0; - virtual Result OnBrExpr(BrExpr*) = 0; - virtual Result OnBrIfExpr(BrIfExpr*) = 0; - virtual Result OnBrTableExpr(BrTableExpr*) = 0; - virtual Result OnCallExpr(CallExpr*) = 0; - virtual Result OnCallIndirectExpr(CallIndirectExpr*) = 0; - virtual Result OnCallRefExpr(CallRefExpr*) = 0; - virtual Result OnCodeMetadataExpr(CodeMetadataExpr*) = 0; - virtual Result OnCompareExpr(CompareExpr*) = 0; - virtual Result OnConstExpr(ConstExpr*) = 0; - virtual Result OnConvertExpr(ConvertExpr*) = 0; - virtual Result OnDropExpr(DropExpr*) = 0; - virtual Result OnGlobalGetExpr(GlobalGetExpr*) = 0; - virtual Result OnGlobalSetExpr(GlobalSetExpr*) = 0; - virtual Result BeginIfExpr(IfExpr*) = 0; - virtual Result AfterIfTrueExpr(IfExpr*) = 0; - virtual Result EndIfExpr(IfExpr*) = 0; - virtual Result OnLoadExpr(LoadExpr*) = 0; - virtual Result OnLocalGetExpr(LocalGetExpr*) = 0; - virtual Result OnLocalSetExpr(LocalSetExpr*) = 0; - virtual Result OnLocalTeeExpr(LocalTeeExpr*) = 0; - virtual Result BeginLoopExpr(LoopExpr*) = 0; - virtual Result EndLoopExpr(LoopExpr*) = 0; - virtual Result OnMemoryCopyExpr(MemoryCopyExpr*) = 0; - virtual Result OnDataDropExpr(DataDropExpr*) = 0; - virtual Result OnMemoryFillExpr(MemoryFillExpr*) = 0; - virtual Result OnMemoryGrowExpr(MemoryGrowExpr*) = 0; - virtual Result OnMemoryInitExpr(MemoryInitExpr*) = 0; - virtual Result OnMemorySizeExpr(MemorySizeExpr*) = 0; - virtual Result OnTableCopyExpr(TableCopyExpr*) = 0; - virtual Result OnElemDropExpr(ElemDropExpr*) = 0; - virtual Result OnTableInitExpr(TableInitExpr*) = 0; - virtual Result OnTableGetExpr(TableGetExpr*) = 0; - virtual Result OnTableSetExpr(TableSetExpr*) = 0; - virtual Result OnTableGrowExpr(TableGrowExpr*) = 0; - virtual Result OnTableSizeExpr(TableSizeExpr*) = 0; - virtual Result OnTableFillExpr(TableFillExpr*) = 0; - virtual Result OnRefFuncExpr(RefFuncExpr*) = 0; - virtual Result OnRefNullExpr(RefNullExpr*) = 0; - virtual Result OnRefIsNullExpr(RefIsNullExpr*) = 0; - virtual Result OnNopExpr(NopExpr*) = 0; - virtual Result OnReturnExpr(ReturnExpr*) = 0; - virtual Result OnReturnCallExpr(ReturnCallExpr*) = 0; - virtual Result OnReturnCallIndirectExpr(ReturnCallIndirectExpr*) = 0; - virtual Result OnSelectExpr(SelectExpr*) = 0; - virtual Result OnStoreExpr(StoreExpr*) = 0; - virtual Result OnUnaryExpr(UnaryExpr*) = 0; - virtual Result OnUnreachableExpr(UnreachableExpr*) = 0; - virtual Result BeginTryExpr(TryExpr*) = 0; - virtual Result OnCatchExpr(TryExpr*, Catch*) = 0; - virtual Result OnDelegateExpr(TryExpr*) = 0; - virtual Result EndTryExpr(TryExpr*) = 0; - virtual Result OnThrowExpr(ThrowExpr*) = 0; - virtual Result OnRethrowExpr(RethrowExpr*) = 0; - virtual Result OnAtomicWaitExpr(AtomicWaitExpr*) = 0; - virtual Result OnAtomicFenceExpr(AtomicFenceExpr*) = 0; - virtual Result OnAtomicNotifyExpr(AtomicNotifyExpr*) = 0; - virtual Result OnAtomicLoadExpr(AtomicLoadExpr*) = 0; - virtual Result OnAtomicStoreExpr(AtomicStoreExpr*) = 0; - virtual Result OnAtomicRmwExpr(AtomicRmwExpr*) = 0; - virtual Result OnAtomicRmwCmpxchgExpr(AtomicRmwCmpxchgExpr*) = 0; - virtual Result OnTernaryExpr(TernaryExpr*) = 0; - virtual Result OnSimdLaneOpExpr(SimdLaneOpExpr*) = 0; - virtual Result OnSimdLoadLaneExpr(SimdLoadLaneExpr*) = 0; - virtual Result OnSimdStoreLaneExpr(SimdStoreLaneExpr*) = 0; - virtual Result OnSimdShuffleOpExpr(SimdShuffleOpExpr*) = 0; - virtual Result OnLoadSplatExpr(LoadSplatExpr*) = 0; - virtual Result OnLoadZeroExpr(LoadZeroExpr*) = 0; -}; - -class ExprVisitor::DelegateNop : public ExprVisitor::Delegate { - public: - Result OnBinaryExpr(BinaryExpr*) override { return Result::Ok; } - Result BeginBlockExpr(BlockExpr*) override { return Result::Ok; } - Result EndBlockExpr(BlockExpr*) override { return Result::Ok; } - Result OnBrExpr(BrExpr*) override { return Result::Ok; } - Result OnBrIfExpr(BrIfExpr*) override { return Result::Ok; } - Result OnBrTableExpr(BrTableExpr*) override { return Result::Ok; } - Result OnCallExpr(CallExpr*) override { return Result::Ok; } - Result OnCallIndirectExpr(CallIndirectExpr*) override { return Result::Ok; } - Result OnCallRefExpr(CallRefExpr*) override { return Result::Ok; } - Result OnCodeMetadataExpr(CodeMetadataExpr*) override { return Result::Ok; } - Result OnCompareExpr(CompareExpr*) override { return Result::Ok; } - Result OnConstExpr(ConstExpr*) override { return Result::Ok; } - Result OnConvertExpr(ConvertExpr*) override { return Result::Ok; } - Result OnDropExpr(DropExpr*) override { return Result::Ok; } - Result OnGlobalGetExpr(GlobalGetExpr*) override { return Result::Ok; } - Result OnGlobalSetExpr(GlobalSetExpr*) override { return Result::Ok; } - Result BeginIfExpr(IfExpr*) override { return Result::Ok; } - Result AfterIfTrueExpr(IfExpr*) override { return Result::Ok; } - Result EndIfExpr(IfExpr*) override { return Result::Ok; } - Result OnLoadExpr(LoadExpr*) override { return Result::Ok; } - Result OnLocalGetExpr(LocalGetExpr*) override { return Result::Ok; } - Result OnLocalSetExpr(LocalSetExpr*) override { return Result::Ok; } - Result OnLocalTeeExpr(LocalTeeExpr*) override { return Result::Ok; } - Result BeginLoopExpr(LoopExpr*) override { return Result::Ok; } - Result EndLoopExpr(LoopExpr*) override { return Result::Ok; } - Result OnMemoryCopyExpr(MemoryCopyExpr*) override { return Result::Ok; } - Result OnDataDropExpr(DataDropExpr*) override { return Result::Ok; } - Result OnMemoryFillExpr(MemoryFillExpr*) override { return Result::Ok; } - Result OnMemoryGrowExpr(MemoryGrowExpr*) override { return Result::Ok; } - Result OnMemoryInitExpr(MemoryInitExpr*) override { return Result::Ok; } - Result OnMemorySizeExpr(MemorySizeExpr*) override { return Result::Ok; } - Result OnTableCopyExpr(TableCopyExpr*) override { return Result::Ok; } - Result OnElemDropExpr(ElemDropExpr*) override { return Result::Ok; } - Result OnTableInitExpr(TableInitExpr*) override { return Result::Ok; } - Result OnTableGetExpr(TableGetExpr*) override { return Result::Ok; } - Result OnTableSetExpr(TableSetExpr*) override { return Result::Ok; } - Result OnTableGrowExpr(TableGrowExpr*) override { return Result::Ok; } - Result OnTableSizeExpr(TableSizeExpr*) override { return Result::Ok; } - Result OnTableFillExpr(TableFillExpr*) override { return Result::Ok; } - Result OnRefFuncExpr(RefFuncExpr*) override { return Result::Ok; } - Result OnRefNullExpr(RefNullExpr*) override { return Result::Ok; } - Result OnRefIsNullExpr(RefIsNullExpr*) override { return Result::Ok; } - Result OnNopExpr(NopExpr*) override { return Result::Ok; } - Result OnReturnExpr(ReturnExpr*) override { return Result::Ok; } - Result OnReturnCallExpr(ReturnCallExpr*) override { return Result::Ok; } - Result OnReturnCallIndirectExpr(ReturnCallIndirectExpr*) override { - return Result::Ok; - } - Result OnSelectExpr(SelectExpr*) override { return Result::Ok; } - Result OnStoreExpr(StoreExpr*) override { return Result::Ok; } - Result OnUnaryExpr(UnaryExpr*) override { return Result::Ok; } - Result OnUnreachableExpr(UnreachableExpr*) override { return Result::Ok; } - Result BeginTryExpr(TryExpr*) override { return Result::Ok; } - Result OnCatchExpr(TryExpr*, Catch*) override { return Result::Ok; } - Result OnDelegateExpr(TryExpr*) override { return Result::Ok; } - Result EndTryExpr(TryExpr*) override { return Result::Ok; } - Result OnThrowExpr(ThrowExpr*) override { return Result::Ok; } - Result OnRethrowExpr(RethrowExpr*) override { return Result::Ok; } - Result OnAtomicWaitExpr(AtomicWaitExpr*) override { return Result::Ok; } - Result OnAtomicFenceExpr(AtomicFenceExpr*) override { return Result::Ok; } - Result OnAtomicNotifyExpr(AtomicNotifyExpr*) override { return Result::Ok; } - Result OnAtomicLoadExpr(AtomicLoadExpr*) override { return Result::Ok; } - Result OnAtomicStoreExpr(AtomicStoreExpr*) override { return Result::Ok; } - Result OnAtomicRmwExpr(AtomicRmwExpr*) override { return Result::Ok; } - Result OnAtomicRmwCmpxchgExpr(AtomicRmwCmpxchgExpr*) override { - return Result::Ok; - } - Result OnTernaryExpr(TernaryExpr*) override { return Result::Ok; } - Result OnSimdLaneOpExpr(SimdLaneOpExpr*) override { return Result::Ok; } - Result OnSimdLoadLaneExpr(SimdLoadLaneExpr*) override { return Result::Ok; } - Result OnSimdStoreLaneExpr(SimdStoreLaneExpr*) override { return Result::Ok; } - Result OnSimdShuffleOpExpr(SimdShuffleOpExpr*) override { return Result::Ok; } - Result OnLoadSplatExpr(LoadSplatExpr*) override { return Result::Ok; } - Result OnLoadZeroExpr(LoadZeroExpr*) override { return Result::Ok; } -}; - -} // namespace wabt - -#endif // WABT_EXPR_VISITOR_H_ diff --git a/src/feature.cc b/src/feature.cc index 9a8cb7a4..88b474c2 100644 --- a/src/feature.cc +++ b/src/feature.cc @@ -14,9 +14,9 @@ * limitations under the License. */ -#include "src/feature.h" +#include "wabt/feature.h" -#include "src/option-parser.h" +#include "wabt/option-parser.h" namespace wabt { @@ -30,7 +30,7 @@ void Features::AddOptions(OptionParser* parser) { [this]() { enable_##variable(); }); \ } -#include "src/feature.def" +#include "wabt/feature.def" #undef WABT_FEATURE parser->AddOption("enable-all", "Enable all features", [this]() { EnableAll(); }); diff --git a/src/feature.def b/src/feature.def deleted file mode 100644 index 26b1db79..00000000 --- a/src/feature.def +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_FEATURE -#error "You must define WABT_FEATURE before including this file." -#endif - -/* - * variable flag default help - * ========================================================================= */ - -WABT_FEATURE(exceptions, "exceptions", false, "Experimental exception handling") -WABT_FEATURE(mutable_globals, "mutable-globals", true, "Import/export mutable globals") -WABT_FEATURE(sat_float_to_int, "saturating-float-to-int", true, "Saturating float-to-int operators") -WABT_FEATURE(sign_extension, "sign-extension", true, "Sign-extension operators") -WABT_FEATURE(simd, "simd", true, "SIMD support") -WABT_FEATURE(threads, "threads", false, "Threading support") -WABT_FEATURE(function_references, "function-references", false, "Typed function references") -WABT_FEATURE(multi_value, "multi-value", true, "Multi-value") -WABT_FEATURE(tail_call, "tail-call", false, "Tail-call support") -WABT_FEATURE(bulk_memory, "bulk-memory", true, "Bulk-memory operations") -WABT_FEATURE(reference_types, "reference-types", true, "Reference types (externref)") -WABT_FEATURE(annotations, "annotations", false, "Custom annotation syntax") -WABT_FEATURE(code_metadata, "code-metadata", false, "Code metadata") -WABT_FEATURE(gc, "gc", false, "Garbage collection") -WABT_FEATURE(memory64, "memory64", false, "64-bit memory") -WABT_FEATURE(multi_memory, "multi-memory", false, "Multi-memory") -WABT_FEATURE(extended_const, "extended-const", false, "Extended constant expressions") diff --git a/src/feature.h b/src/feature.h deleted file mode 100644 index 7ebc9ef8..00000000 --- a/src/feature.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_FEATURE_H_ -#define WABT_FEATURE_H_ - -#include "src/common.h" - -namespace wabt { - -class OptionParser; - -class Features { - public: - void AddOptions(OptionParser*); - - void EnableAll() { -#define WABT_FEATURE(variable, flag, default_, help) enable_##variable(); -#include "src/feature.def" -#undef WABT_FEATURE - } - -#define WABT_FEATURE(variable, flag, default_, help) \ - bool variable##_enabled() const { return variable##_enabled_; } \ - void enable_##variable() { set_##variable##_enabled(true); } \ - void disable_##variable() { set_##variable##_enabled(false); } \ - void set_##variable##_enabled(bool value) { \ - variable##_enabled_ = value; \ - UpdateDependencies(); \ - } -#include "src/feature.def" -#undef WABT_FEATURE - - private: - void UpdateDependencies(); - -#define WABT_FEATURE(variable, flag, default_, help) \ - bool variable##_enabled_ = default_; -#include "src/feature.def" -#undef WABT_FEATURE -}; - -} // namespace wabt - -#endif // WABT_FEATURE_H_ diff --git a/src/filenames.cc b/src/filenames.cc index 3cb6fd1c..9f020f46 100644 --- a/src/filenames.cc +++ b/src/filenames.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/filenames.h" +#include "wabt/filenames.h" namespace wabt { diff --git a/src/filenames.h b/src/filenames.h deleted file mode 100644 index dc4719e7..00000000 --- a/src/filenames.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_FILENAMES_H_ -#define WABT_FILENAMES_H_ - -#include "src/common.h" - -namespace wabt { - -extern const char* kWasmExtension; -extern const char* kWatExtension; - -// Return only the file extension, e.g.: -// -// "foo.txt", => ".txt" -// "foo" => "" -// "/foo/bar/foo.wasm" => ".wasm" -std::string_view GetExtension(std::string_view filename); - -// Strip extension, e.g.: -// -// "foo", => "foo" -// "foo.bar" => "foo" -// "/path/to/foo.bar" => "/path/to/foo" -// "\\path\\to\\foo.bar" => "\\path\\to\\foo" -std::string_view StripExtension(std::string_view s); - -// Strip everything up to and including the last slash, e.g.: -// -// "/foo/bar/baz", => "baz" -// "/usr/local/include/stdio.h", => "stdio.h" -// "foo.bar", => "foo.bar" -std::string_view GetBasename(std::string_view filename); - -} // namespace wabt - -#endif /* WABT_FILENAMES_H_ */ diff --git a/src/generate-names.cc b/src/generate-names.cc index a7f5d360..ec3612d7 100644 --- a/src/generate-names.cc +++ b/src/generate-names.cc @@ -14,16 +14,16 @@ * limitations under the License. */ -#include "src/generate-names.h" +#include "wabt/generate-names.h" #include <cassert> #include <cstdio> #include <string> #include <vector> -#include "src/cast.h" -#include "src/expr-visitor.h" -#include "src/ir.h" +#include "wabt/cast.h" +#include "wabt/expr-visitor.h" +#include "wabt/ir.h" namespace wabt { diff --git a/src/generate-names.h b/src/generate-names.h deleted file mode 100644 index 9cd926e4..00000000 --- a/src/generate-names.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_GENERATE_NAMES_H_ -#define WABT_GENERATE_NAMES_H_ - -#include "src/common.h" - -namespace wabt { - -struct Module; - -enum NameOpts { - None = 0, - AlphaNames = 1 << 0, -}; - -Result GenerateNames(struct Module*, NameOpts opts = NameOpts::None); - -inline std::string IndexToAlphaName(Index index) { - std::string s; - do { - // For multiple chars, put most frequently changing char first. - s += 'a' + (index % 26); - index /= 26; - // Continue remaining sequence with 'a' rather than 'b'. - } while (index--); - return s; -} - -} // namespace wabt - -#endif /* WABT_GENERATE_NAMES_H_ */ diff --git a/src/interp/binary-reader-interp.cc b/src/interp/binary-reader-interp.cc index 05296220..def91b64 100644 --- a/src/interp/binary-reader-interp.cc +++ b/src/interp/binary-reader-interp.cc @@ -14,16 +14,16 @@ * limitations under the License. */ -#include "src/interp/binary-reader-interp.h" +#include "wabt/interp/binary-reader-interp.h" #include <map> #include <set> -#include "src/binary-reader-nop.h" -#include "src/feature.h" -#include "src/interp/interp.h" -#include "src/shared-validator.h" -#include "src/stream.h" +#include "wabt/binary-reader-nop.h" +#include "wabt/feature.h" +#include "wabt/interp/interp.h" +#include "wabt/shared-validator.h" +#include "wabt/stream.h" namespace wabt { namespace interp { diff --git a/src/interp/binary-reader-interp.h b/src/interp/binary-reader-interp.h deleted file mode 100644 index b3b7e46d..00000000 --- a/src/interp/binary-reader-interp.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_BINARY_READER_INTERP_H_ -#define WABT_BINARY_READER_INTERP_H_ - -#include "src/common.h" -#include "src/error.h" -#include "src/interp/interp.h" - -namespace wabt { - -struct ReadBinaryOptions; - -namespace interp { - -Result ReadBinaryInterp(std::string_view filename, - const void* data, - size_t size, - const ReadBinaryOptions& options, - Errors*, - ModuleDesc* out_module); - -} // namespace interp -} // namespace wabt - -#endif /* WABT_BINARY_READER_INTERP_H_ */ diff --git a/src/interp/interp-inl.h b/src/interp/interp-inl.h deleted file mode 100644 index d985bea4..00000000 --- a/src/interp/interp-inl.h +++ /dev/null @@ -1,1000 +0,0 @@ -/* - * Copyright 2020 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include <cassert> -#include <limits> -#include <string> - -namespace wabt { -namespace interp { - -//// Ref //// -inline Ref::Ref(size_t index) : index(index) {} - -inline bool operator==(Ref lhs, Ref rhs) { - return lhs.index == rhs.index; -} - -inline bool operator!=(Ref lhs, Ref rhs) { - return lhs.index != rhs.index; -} - -//// ExternType //// -inline ExternType::ExternType(ExternKind kind) : kind(kind) {} - -//// FuncType //// -// static -inline bool FuncType::classof(const ExternType* type) { - return type->kind == skind; -} - -inline FuncType::FuncType(ValueTypes params, ValueTypes results) - : ExternType(ExternKind::Func), params(params), results(results) {} - -//// TableType //// -// static -inline bool TableType::classof(const ExternType* type) { - return type->kind == skind; -} - -inline TableType::TableType(ValueType element, Limits limits) - : ExternType(ExternKind::Table), element(element), limits(limits) { - // Always set max. - if (!limits.has_max) { - this->limits.max = std::numeric_limits<u32>::max(); - } -} - -//// MemoryType //// -// static -inline bool MemoryType::classof(const ExternType* type) { - return type->kind == skind; -} - -inline MemoryType::MemoryType(Limits limits) - : ExternType(ExternKind::Memory), limits(limits) { - // Always set max. - if (!limits.has_max) { - this->limits.max = limits.is_64 ? WABT_MAX_PAGES64 : WABT_MAX_PAGES32; - } -} - -//// GlobalType //// -// static -inline bool GlobalType::classof(const ExternType* type) { - return type->kind == skind; -} - -inline GlobalType::GlobalType(ValueType type, Mutability mut) - : ExternType(ExternKind::Global), type(type), mut(mut) {} - -//// TagType //// -// static -inline bool TagType::classof(const ExternType* type) { - return type->kind == skind; -} - -inline TagType::TagType(TagAttr attr, const ValueTypes& signature) - : ExternType(ExternKind::Tag), attr(attr), signature(signature) {} - -//// ImportType //// -inline ImportType::ImportType(std::string module, - std::string name, - std::unique_ptr<ExternType> type) - : module(module), name(name), type(std::move(type)) {} - -inline ImportType::ImportType(const ImportType& other) - : module(other.module), name(other.name), type(other.type->Clone()) {} - -inline ImportType& ImportType::operator=(const ImportType& other) { - if (this != &other) { - module = other.module; - name = other.name; - type = other.type->Clone(); - } - return *this; -} - -//// ExportType //// -inline ExportType::ExportType(std::string name, - std::unique_ptr<ExternType> type) - : name(name), type(std::move(type)) {} - -inline ExportType::ExportType(const ExportType& other) - : name(other.name), type(other.type->Clone()) {} - -inline ExportType& ExportType::operator=(const ExportType& other) { - if (this != &other) { - name = other.name; - type = other.type->Clone(); - } - return *this; -} - -//// Frame //// -inline Frame::Frame(Ref func, - u32 values, - u32 exceptions, - u32 offset, - Instance* inst, - Module* mod) - : func(func), - values(values), - exceptions(exceptions), - offset(offset), - inst(inst), - mod(mod) {} - -//// FreeList //// -template <> -inline bool FreeList<Ref>::IsUsed(Index index) const { - return (list_[index].index & refFreeBit) == 0; -} - -template <> -inline FreeList<Ref>::~FreeList<Ref>() {} - -template <> -template <typename... Args> -auto FreeList<Ref>::New(Args&&... args) -> Index { - if (free_head_ == 0) { - list_.push_back(Ref(std::forward<Args>(args)...)); - return list_.size() - 1; - } - - Index index = free_head_ - 1; - - assert(!IsUsed(index)); - assert(free_items_ > 0); - - free_head_ = list_[index].index & (refFreeBit - 1); - list_[index] = Ref(std::forward<Args>(args)...); - free_items_--; - return index; -} - -template <> -inline void FreeList<Ref>::Delete(Index index) { - assert(IsUsed(index)); - - list_[index].index = free_head_ | refFreeBit; - free_head_ = index + 1; - free_items_++; -} - -template <typename T> -bool FreeList<T>::IsUsed(Index index) const { - return (reinterpret_cast<uintptr_t>(list_[index]) & ptrFreeBit) == 0; -} - -template <typename T> -FreeList<T>::~FreeList<T>() { - for (auto object : list_) { - if ((reinterpret_cast<uintptr_t>(object) & ptrFreeBit) == 0) { - delete object; - } - } -} - -template <typename T> -template <typename... Args> -auto FreeList<T>::New(Args&&... args) -> Index { - if (free_head_ == 0) { - list_.push_back(T(std::forward<Args>(args)...)); - return list_.size() - 1; - } - - Index index = free_head_ - 1; - - assert(!IsUsed(index)); - assert(free_items_ > 0); - - free_head_ = reinterpret_cast<uintptr_t>(list_[index]) >> ptrFreeShift; - list_[index] = T(std::forward<Args>(args)...); - free_items_--; - return index; -} - -template <typename T> -void FreeList<T>::Delete(Index index) { - assert(IsUsed(index)); - - delete list_[index]; - list_[index] = reinterpret_cast<T>((free_head_ << ptrFreeShift) | ptrFreeBit); - free_head_ = index + 1; - free_items_++; -} - -template <typename T> -const T& FreeList<T>::Get(Index index) const { - assert(IsUsed(index)); - return list_[index]; -} - -template <typename T> -T& FreeList<T>::Get(Index index) { - assert(IsUsed(index)); - return list_[index]; -} - -template <typename T> -auto FreeList<T>::size() const -> Index { - return list_.size(); -} - -template <typename T> -auto FreeList<T>::count() const -> Index { - return list_.size() - free_items_; -} - -//// RefPtr //// -template <typename T> -RefPtr<T>::RefPtr() : obj_(nullptr), store_(nullptr), root_index_(0) {} - -template <typename T> -RefPtr<T>::RefPtr(Store& store, Ref ref) { -#ifndef NDEBUG - if (!store.Is<T>(ref)) { - ObjectKind ref_kind; - if (ref == Ref::Null) { - ref_kind = ObjectKind::Null; - } else { - ref_kind = store.objects_.Get(ref.index)->kind(); - } - fprintf(stderr, "Invalid conversion from Ref (%s) to RefPtr<%s>!\n", - GetName(ref_kind), T::GetTypeName()); - abort(); - } -#endif - root_index_ = store.NewRoot(ref); - obj_ = static_cast<T*>(store.objects_.Get(ref.index)); - store_ = &store; -} - -template <typename T> -RefPtr<T>::RefPtr(const RefPtr& other) - : obj_(other.obj_), store_(other.store_) { - root_index_ = store_ ? store_->CopyRoot(other.root_index_) : 0; -} - -template <typename T> -RefPtr<T>& RefPtr<T>::operator=(const RefPtr& other) { - obj_ = other.obj_; - store_ = other.store_; - root_index_ = store_ ? store_->CopyRoot(other.root_index_) : 0; - return *this; -} - -template <typename T> -RefPtr<T>::RefPtr(RefPtr&& other) - : obj_(other.obj_), store_(other.store_), root_index_(other.root_index_) { - other.obj_ = nullptr; - other.store_ = nullptr; - other.root_index_ = 0; -} - -template <typename T> -RefPtr<T>& RefPtr<T>::operator=(RefPtr&& other) { - obj_ = other.obj_; - store_ = other.store_; - root_index_ = other.root_index_; - other.obj_ = nullptr; - other.store_ = nullptr; - other.root_index_ = 0; - return *this; -} - -template <typename T> -RefPtr<T>::~RefPtr() { - reset(); -} - -template <typename T> -template <typename U> -RefPtr<T>::RefPtr(const RefPtr<U>& other) - : obj_(other.obj_), store_(other.store_) { - root_index_ = store_ ? store_->CopyRoot(other.root_index_) : 0; -} - -template <typename T> -template <typename U> -RefPtr<T>& RefPtr<T>::operator=(const RefPtr<U>& other) { - obj_ = other.obj_; - store_ = other.store_; - root_index_ = store_ ? store_->CopyRoot(other.root_index_) : 0; - return *this; -} - -template <typename T> -template <typename U> -RefPtr<T>::RefPtr(RefPtr&& other) - : obj_(other.obj_), store_(other.store_), root_index_(other.root_index_) { - other.obj_ = nullptr; - other.store_ = nullptr; - other.root_index_ = 0; -} - -template <typename T> -template <typename U> -RefPtr<T>& RefPtr<T>::operator=(RefPtr&& other) { - obj_ = other.obj_; - store_ = other.store_; - root_index_ = other.root_index_; - other.obj_ = nullptr; - other.store_ = nullptr; - other.root_index_ = 0; - return *this; -} - -template <typename T> -template <typename U> -RefPtr<U> RefPtr<T>::As() { - static_assert(std::is_base_of<T, U>::value, "T must be base class of U"); - assert(store_->Is<U>(obj_->self())); - RefPtr<U> result; - result.obj_ = static_cast<U*>(obj_); - result.store_ = store_; - result.root_index_ = store_->CopyRoot(root_index_); - return result; -} - -template <typename T> -bool RefPtr<T>::empty() const { - return obj_ == nullptr; -} - -template <typename T> -void RefPtr<T>::reset() { - if (obj_) { - store_->DeleteRoot(root_index_); - obj_ = nullptr; - root_index_ = 0; - store_ = nullptr; - } -} - -template <typename T> -T* RefPtr<T>::get() const { - return obj_; -} - -template <typename T> -T* RefPtr<T>::operator->() const { - return obj_; -} - -template <typename T> -T& RefPtr<T>::operator*() const { - return *obj_; -} - -template <typename T> -RefPtr<T>::operator bool() const { - return obj_ != nullptr; -} - -template <typename T> -Ref RefPtr<T>::ref() const { - return store_ ? store_->roots_.Get(root_index_) : Ref::Null; -} - -template <typename T> -Store* RefPtr<T>::store() const { - return store_; -} - -template <typename U, typename V> -bool operator==(const RefPtr<U>& lhs, const RefPtr<V>& rhs) { - return lhs.obj_->self() == rhs.obj_->self(); -} - -template <typename U, typename V> -bool operator!=(const RefPtr<U>& lhs, const RefPtr<V>& rhs) { - return lhs.obj_->self() != rhs.obj_->self(); -} - -//// ValueType //// -inline bool IsReference(ValueType type) { return type.IsRef(); } -template <> inline bool HasType<s32>(ValueType type) { return type == ValueType::I32; } -template <> inline bool HasType<u32>(ValueType type) { return type == ValueType::I32; } -template <> inline bool HasType<s64>(ValueType type) { return type == ValueType::I64; } -template <> inline bool HasType<u64>(ValueType type) { return type == ValueType::I64; } -template <> inline bool HasType<f32>(ValueType type) { return type == ValueType::F32; } -template <> inline bool HasType<f64>(ValueType type) { return type == ValueType::F64; } -template <> inline bool HasType<Ref>(ValueType type) { return IsReference(type); } - -template <typename T> -void RequireType(ValueType type) { - assert(HasType<T>(type)); -} - -inline bool TypesMatch(ValueType expected, ValueType actual) { - // Currently there is no subtyping, so expected and actual must match - // exactly. In the future this may be expanded. - return expected == actual; -} - -//// Value //// -inline Value WABT_VECTORCALL Value::Make(s32 val) { Value res; res.i32_ = val; res.SetType(ValueType::I32); return res; } -inline Value WABT_VECTORCALL Value::Make(u32 val) { Value res; res.i32_ = val; res.SetType(ValueType::I32); return res; } -inline Value WABT_VECTORCALL Value::Make(s64 val) { Value res; res.i64_ = val; res.SetType(ValueType::I64); return res; } -inline Value WABT_VECTORCALL Value::Make(u64 val) { Value res; res.i64_ = val; res.SetType(ValueType::I64); return res; } -inline Value WABT_VECTORCALL Value::Make(f32 val) { Value res; res.f32_ = val; res.SetType(ValueType::F32); return res; } -inline Value WABT_VECTORCALL Value::Make(f64 val) { Value res; res.f64_ = val; res.SetType(ValueType::F64); return res; } -inline Value WABT_VECTORCALL Value::Make(v128 val) { Value res; res.v128_ = val; res.SetType(ValueType::V128); return res; } -inline Value WABT_VECTORCALL Value::Make(Ref val) { Value res; res.ref_ = val; res.SetType(ValueType::ExternRef); return res; } -template <typename T, u8 L> -Value WABT_VECTORCALL Value::Make(Simd<T, L> val) { - Value res; - res.v128_ = Bitcast<v128>(val); - res.SetType(ValueType::V128); - return res; -} - -template <> inline s8 WABT_VECTORCALL Value::Get<s8>() const { CheckType(ValueType::I32); return i32_; } -template <> inline u8 WABT_VECTORCALL Value::Get<u8>() const { CheckType(ValueType::I32); return i32_; } -template <> inline s16 WABT_VECTORCALL Value::Get<s16>() const { CheckType(ValueType::I32); return i32_; } -template <> inline u16 WABT_VECTORCALL Value::Get<u16>() const { CheckType(ValueType::I32); return i32_; } -template <> inline s32 WABT_VECTORCALL Value::Get<s32>() const { CheckType(ValueType::I32); return i32_; } -template <> inline u32 WABT_VECTORCALL Value::Get<u32>() const { CheckType(ValueType::I32); return i32_; } -template <> inline s64 WABT_VECTORCALL Value::Get<s64>() const { CheckType(ValueType::I64); return i64_; } -template <> inline u64 WABT_VECTORCALL Value::Get<u64>() const { CheckType(ValueType::I64); return i64_; } -template <> inline f32 WABT_VECTORCALL Value::Get<f32>() const { CheckType(ValueType::F32); return f32_; } -template <> inline f64 WABT_VECTORCALL Value::Get<f64>() const { CheckType(ValueType::F64); return f64_; } -template <> inline v128 WABT_VECTORCALL Value::Get<v128>() const { CheckType(ValueType::V128); return v128_; } -template <> inline Ref WABT_VECTORCALL Value::Get<Ref>() const { CheckType(ValueType::ExternRef); return ref_; } - -template <> inline s8x16 WABT_VECTORCALL Value::Get<s8x16>() const { CheckType(ValueType::V128); return Bitcast<s8x16>(v128_); } -template <> inline u8x16 WABT_VECTORCALL Value::Get<u8x16>() const { CheckType(ValueType::V128); return Bitcast<u8x16>(v128_); } -template <> inline s16x8 WABT_VECTORCALL Value::Get<s16x8>() const { CheckType(ValueType::V128); return Bitcast<s16x8>(v128_); } -template <> inline u16x8 WABT_VECTORCALL Value::Get<u16x8>() const { CheckType(ValueType::V128); return Bitcast<u16x8>(v128_); } -template <> inline s32x4 WABT_VECTORCALL Value::Get<s32x4>() const { CheckType(ValueType::V128); return Bitcast<s32x4>(v128_); } -template <> inline u32x4 WABT_VECTORCALL Value::Get<u32x4>() const { CheckType(ValueType::V128); return Bitcast<u32x4>(v128_); } -template <> inline s64x2 WABT_VECTORCALL Value::Get<s64x2>() const { CheckType(ValueType::V128); return Bitcast<s64x2>(v128_); } -template <> inline u64x2 WABT_VECTORCALL Value::Get<u64x2>() const { CheckType(ValueType::V128); return Bitcast<u64x2>(v128_); } -template <> inline f32x4 WABT_VECTORCALL Value::Get<f32x4>() const { CheckType(ValueType::V128); return Bitcast<f32x4>(v128_); } -template <> inline f64x2 WABT_VECTORCALL Value::Get<f64x2>() const { CheckType(ValueType::V128); return Bitcast<f64x2>(v128_); } - -template <> inline void WABT_VECTORCALL Value::Set<s32>(s32 val) { i32_ = val; SetType(ValueType::I32); } -template <> inline void WABT_VECTORCALL Value::Set<u32>(u32 val) { i32_ = val; SetType(ValueType::I32); } -template <> inline void WABT_VECTORCALL Value::Set<s64>(s64 val) { i64_ = val; SetType(ValueType::I64); } -template <> inline void WABT_VECTORCALL Value::Set<u64>(u64 val) { i64_ = val; SetType(ValueType::I64); } -template <> inline void WABT_VECTORCALL Value::Set<f32>(f32 val) { f32_ = val; SetType(ValueType::F32); } -template <> inline void WABT_VECTORCALL Value::Set<f64>(f64 val) { f64_ = val; SetType(ValueType::F64); } -template <> inline void WABT_VECTORCALL Value::Set<v128>(v128 val) { v128_ = val; SetType(ValueType::V128); } -template <> inline void WABT_VECTORCALL Value::Set<Ref>(Ref val) { ref_ = val; SetType(ValueType::ExternRef); } - -//// Store //// -inline bool Store::IsValid(Ref ref) const { - return objects_.IsUsed(ref.index) && objects_.Get(ref.index); -} - -template <typename T> -bool Store::Is(Ref ref) const { - return objects_.IsUsed(ref.index) && isa<T>(objects_.Get(ref.index)); -} - -template <typename T> -Result Store::Get(Ref ref, RefPtr<T>* out) { - if (Is<T>(ref)) { - *out = RefPtr<T>(*this, ref); - return Result::Ok; - } - return Result::Error; -} - -template <typename T> -RefPtr<T> Store::UnsafeGet(Ref ref) { - return RefPtr<T>(*this, ref); -} - -template <typename T, typename... Args> -RefPtr<T> Store::Alloc(Args&&... args) { - Ref ref{objects_.New(new T(std::forward<Args>(args)...))}; - RefPtr<T> ptr{*this, ref}; - ptr->self_ = ref; - return ptr; -} - -inline Store::ObjectList::Index Store::object_count() const { - return objects_.count(); -} - -inline const Features& Store::features() const { - return features_; -} - -inline std::set<Thread*>& Store::threads() { - return threads_; -} - -//// Object //// -// static -inline bool Object::classof(const Object* obj) { - return true; -} - -inline Object::Object(ObjectKind kind) : kind_(kind) {} - -inline ObjectKind Object::kind() const { - return kind_; -} - -inline Ref Object::self() const { - return self_; -} - -inline void* Object::host_info() const { - return host_info_; -} - -inline void Object::set_host_info(void* host_info) { - host_info_ = host_info; -} - -inline Finalizer Object::get_finalizer() const { - return finalizer_; -} - -inline void Object::set_finalizer(Finalizer finalizer) { - finalizer_ = finalizer; -} - -//// Foreign //// -// static -inline bool Foreign::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline Foreign::Ptr Foreign::New(Store& store, void* ptr) { - return store.Alloc<Foreign>(store, ptr); -} - -inline void* Foreign::ptr() { - return ptr_; -} - -//// Trap //// -// static -inline bool Trap::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline Trap::Ptr Trap::New(Store& store, - const std::string& msg, - const std::vector<Frame>& trace) { - return store.Alloc<Trap>(store, msg, trace); -} - -inline std::string Trap::message() const { - return message_; -} - -//// Exception //// -// static -inline bool Exception::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline Exception::Ptr Exception::New(Store& store, Ref tag, Values& args) { - return store.Alloc<Exception>(store, tag, args); -} - -inline Ref Exception::tag() const { - return tag_; -} - -inline Values& Exception::args() { - return args_; -} - -//// Extern //// -// static -inline bool Extern::classof(const Object* obj) { - switch (obj->kind()) { - case ObjectKind::DefinedFunc: - case ObjectKind::HostFunc: - case ObjectKind::Table: - case ObjectKind::Memory: - case ObjectKind::Global: - case ObjectKind::Tag: - return true; - default: - return false; - } -} - -inline Extern::Extern(ObjectKind kind) : Object(kind) {} - -//// Func //// -// static -inline bool Func::classof(const Object* obj) { - switch (obj->kind()) { - case ObjectKind::DefinedFunc: - case ObjectKind::HostFunc: - return true; - default: - return false; - } -} - -inline const ExternType& Func::extern_type() { - return type_; -} - -inline const FuncType& Func::type() const { - return type_; -} - -//// DefinedFunc //// -// static -inline bool DefinedFunc::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline DefinedFunc::Ptr DefinedFunc::New(Store& store, - Ref instance, - FuncDesc desc) { - return store.Alloc<DefinedFunc>(store, instance, desc); -} - -inline Ref DefinedFunc::instance() const { - return instance_; -} - -inline const FuncDesc& DefinedFunc::desc() const { - return desc_; -} - -//// HostFunc //// -// static -inline bool HostFunc::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline HostFunc::Ptr HostFunc::New(Store& store, FuncType type, Callback cb) { - return store.Alloc<HostFunc>(store, type, cb); -} - -//// Table //// -// static -inline bool Table::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline Table::Ptr Table::New(Store& store, TableType type) { - return store.Alloc<Table>(store, type); -} - -inline const ExternType& Table::extern_type() { - return type_; -} - -inline const TableType& Table::type() const { - return type_; -} - -inline const RefVec& Table::elements() const { - return elements_; -} - -inline u32 Table::size() const { - return static_cast<u32>(elements_.size()); -} - -//// Memory //// -// static -inline bool Memory::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline Memory::Ptr Memory::New(interp::Store& store, MemoryType type) { - return store.Alloc<Memory>(store, type); -} - -inline bool Memory::IsValidAccess(u64 offset, u64 addend, u64 size) const { - // FIXME: make this faster. - return offset <= data_.size() && addend <= data_.size() && - size <= data_.size() && offset + addend + size <= data_.size(); -} - -inline bool Memory::IsValidAtomicAccess(u64 offset, - u64 addend, - u64 size) const { - return IsValidAccess(offset, addend, size) && - ((offset + addend) & (size - 1)) == 0; -} - -template <typename T> -Result Memory::Load(u64 offset, u64 addend, T* out) const { - if (!IsValidAccess(offset, addend, sizeof(T))) { - return Result::Error; - } - wabt::MemcpyEndianAware(out, data_.data(), sizeof(T), data_.size(), 0, - offset + addend, sizeof(T)); - return Result::Ok; -} - -template <typename T> -T WABT_VECTORCALL Memory::UnsafeLoad(u64 offset, u64 addend) const { - assert(IsValidAccess(offset, addend, sizeof(T))); - T val; - wabt::MemcpyEndianAware(&val, data_.data(), sizeof(T), data_.size(), 0, - offset + addend, sizeof(T)); - return val; -} - -template <typename T> -Result WABT_VECTORCALL Memory::Store(u64 offset, u64 addend, T val) { - if (!IsValidAccess(offset, addend, sizeof(T))) { - return Result::Error; - } - wabt::MemcpyEndianAware(data_.data(), &val, data_.size(), sizeof(T), - offset + addend, 0, sizeof(T)); - return Result::Ok; -} - -template <typename T> -Result Memory::AtomicLoad(u64 offset, u64 addend, T* out) const { - if (!IsValidAtomicAccess(offset, addend, sizeof(T))) { - return Result::Error; - } - wabt::MemcpyEndianAware(out, data_.data(), sizeof(T), data_.size(), 0, - offset + addend, sizeof(T)); - return Result::Ok; -} - -template <typename T> -Result Memory::AtomicStore(u64 offset, u64 addend, T val) { - if (!IsValidAtomicAccess(offset, addend, sizeof(T))) { - return Result::Error; - } - wabt::MemcpyEndianAware(data_.data(), &val, data_.size(), sizeof(T), - offset + addend, 0, sizeof(T)); - return Result::Ok; -} - -template <typename T, typename F> -Result Memory::AtomicRmw(u64 offset, u64 addend, T rhs, F&& func, T* out) { - T lhs; - CHECK_RESULT(AtomicLoad(offset, addend, &lhs)); - CHECK_RESULT(AtomicStore(offset, addend, func(lhs, rhs))); - *out = lhs; - return Result::Ok; -} - -template <typename T> -Result Memory::AtomicRmwCmpxchg(u64 offset, - u64 addend, - T expect, - T replace, - T* out) { - T read; - CHECK_RESULT(AtomicLoad(offset, addend, &read)); - if (read == expect) { - CHECK_RESULT(AtomicStore(offset, addend, replace)); - } - *out = read; - return Result::Ok; -} - -inline u8* Memory::UnsafeData() { - return data_.data(); -} - -inline u64 Memory::ByteSize() const { - return data_.size(); -} - -inline u64 Memory::PageSize() const { - return pages_; -} - -inline const ExternType& Memory::extern_type() { - return type_; -} - -inline const MemoryType& Memory::type() const { - return type_; -} - -//// Global //// -// static -inline bool Global::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline Global::Ptr Global::New(Store& store, GlobalType type, Value value) { - return store.Alloc<Global>(store, type, value); -} - -inline Value Global::Get() const { - return value_; -} - -template <typename T> -Result Global::Get(T* out) const { - if (HasType<T>(type_.type)) { - *out = value_.Get<T>(); - return Result::Ok; - } - return Result::Error; -} - -template <typename T> -T WABT_VECTORCALL Global::UnsafeGet() const { - RequireType<T>(type_.type); - return value_.Get<T>(); -} - -template <typename T> -Result WABT_VECTORCALL Global::Set(T val) { - if (type_.mut == Mutability::Var && HasType<T>(type_.type)) { - value_.Set(val); - return Result::Ok; - } - return Result::Error; -} - -inline const ExternType& Global::extern_type() { - return type_; -} - -inline const GlobalType& Global::type() const { - return type_; -} - -//// Tag //// -// static -inline bool Tag::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline Tag::Ptr Tag::New(Store& store, TagType type) { - return store.Alloc<Tag>(store, type); -} - -inline const ExternType& Tag::extern_type() { - return type_; -} - -inline const TagType& Tag::type() const { - return type_; -} - -//// ElemSegment //// -inline void ElemSegment::Drop() { - elements_.clear(); -} - -inline const ElemDesc& ElemSegment::desc() const { - return *desc_; -} - -inline const RefVec& ElemSegment::elements() const { - return elements_; -} - -inline u32 ElemSegment::size() const { - return elements_.size(); -} - -//// DataSegment //// -inline void DataSegment::Drop() { - size_ = 0; -} - -inline const DataDesc& DataSegment::desc() const { - return *desc_; -} - -inline u64 DataSegment::size() const { - return size_; -} - -//// Module //// -// static -inline bool Module::classof(const Object* obj) { - return obj->kind() == skind; -} - -// static -inline Module::Ptr Module::New(Store& store, ModuleDesc desc) { - return store.Alloc<Module>(store, std::move(desc)); -} - -inline const ModuleDesc& Module::desc() const { - return desc_; -} - -inline const std::vector<ImportType>& Module::import_types() const { - return import_types_; -} - -inline const std::vector<ExportType>& Module::export_types() const { - return export_types_; -} - -//// Instance //// -// static -inline bool Instance::classof(const Object* obj) { - return obj->kind() == skind; -} - -inline Ref Instance::module() const { - return module_; -} - -inline const RefVec& Instance::imports() const { - return imports_; -} - -inline const RefVec& Instance::funcs() const { - return funcs_; -} - -inline const RefVec& Instance::tables() const { - return tables_; -} - -inline const RefVec& Instance::memories() const { - return memories_; -} - -inline const RefVec& Instance::globals() const { - return globals_; -} - -inline const RefVec& Instance::tags() const { - return tags_; -} - -inline const RefVec& Instance::exports() const { - return exports_; -} - -inline const std::vector<ElemSegment>& Instance::elems() const { - return elems_; -} - -inline std::vector<ElemSegment>& Instance::elems() { - return elems_; -} - -inline const std::vector<DataSegment>& Instance::datas() const { - return datas_; -} - -inline std::vector<DataSegment>& Instance::datas() { - return datas_; -} - -//// Thread //// -inline Store& Thread::store() { - return store_; -} - -} // namespace interp -} // namespace wabt diff --git a/src/interp/interp-math.h b/src/interp/interp-math.h deleted file mode 100644 index 444a5ee5..00000000 --- a/src/interp/interp-math.h +++ /dev/null @@ -1,412 +0,0 @@ -/* - * Copyright 2020 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_INTERP_MATH_H_ -#define WABT_INTERP_MATH_H_ - -#include <cmath> -#include <limits> -#include <string> -#include <type_traits> - -#if COMPILER_IS_MSVC -#include <emmintrin.h> -#include <immintrin.h> -#endif - -#include "src/common.h" -#include "src/interp/interp.h" - -namespace wabt { -namespace interp { - -template < - typename T, - typename std::enable_if<!std::is_floating_point<T>::value, int>::type = 0> -bool WABT_VECTORCALL IsNaN(T val) { - return false; -} - -template < - typename T, - typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0> -bool WABT_VECTORCALL IsNaN(T val) { - return std::isnan(val); -} - -template < - typename T, - typename std::enable_if<!std::is_floating_point<T>::value, int>::type = 0> -T WABT_VECTORCALL CanonNaN(T val) { - return val; -} - -template < - typename T, - typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0> -T WABT_VECTORCALL CanonNaN(T val) { - if (WABT_UNLIKELY(std::isnan(val))) { - return std::numeric_limits<f32>::quiet_NaN(); - } - return val; -} - -template <typename T> T ShiftMask(T val) { return val & (sizeof(T)*8-1); } - -template <typename T> bool WABT_VECTORCALL IntEqz(T val) { return val == 0; } -template <typename T> bool WABT_VECTORCALL Eq(T lhs, T rhs) { return lhs == rhs; } -template <typename T> bool WABT_VECTORCALL Ne(T lhs, T rhs) { return lhs != rhs; } -template <typename T> bool WABT_VECTORCALL Lt(T lhs, T rhs) { return lhs < rhs; } -template <typename T> bool WABT_VECTORCALL Le(T lhs, T rhs) { return lhs <= rhs; } -template <typename T> bool WABT_VECTORCALL Gt(T lhs, T rhs) { return lhs > rhs; } -template <typename T> bool WABT_VECTORCALL Ge(T lhs, T rhs) { return lhs >= rhs; } -template <typename T> T WABT_VECTORCALL IntClz(T val) { return Clz(val); } -template <typename T> T WABT_VECTORCALL IntCtz(T val) { return Ctz(val); } -template <typename T> T WABT_VECTORCALL IntPopcnt(T val) { return Popcount(val); } -template <typename T> T WABT_VECTORCALL IntNot(T val) { return ~val; } -template <typename T> T WABT_VECTORCALL IntNeg(T val) { return ~val + 1; } -template <typename T> T WABT_VECTORCALL Add(T lhs, T rhs) { return CanonNaN(lhs + rhs); } -template <typename T> T WABT_VECTORCALL Sub(T lhs, T rhs) { return CanonNaN(lhs - rhs); } -template <typename T> T WABT_VECTORCALL IntAnd(T lhs, T rhs) { return lhs & rhs; } -template <typename T> T WABT_VECTORCALL IntOr(T lhs, T rhs) { return lhs | rhs; } -template <typename T> T WABT_VECTORCALL IntXor(T lhs, T rhs) { return lhs ^ rhs; } -template <typename T> T WABT_VECTORCALL IntShl(T lhs, T rhs) { return lhs << ShiftMask(rhs); } -template <typename T> T WABT_VECTORCALL IntShr(T lhs, T rhs) { return lhs >> ShiftMask(rhs); } -template <typename T> T WABT_VECTORCALL IntMin(T lhs, T rhs) { return std::min(lhs, rhs); } -template <typename T> T WABT_VECTORCALL IntMax(T lhs, T rhs) { return std::max(lhs, rhs); } -template <typename T> T WABT_VECTORCALL IntAndNot(T lhs, T rhs) { return lhs & ~rhs; } -template <typename T> T WABT_VECTORCALL IntAvgr(T lhs, T rhs) { return (lhs + rhs + 1) / 2; } -template <typename T> T WABT_VECTORCALL Xchg(T lhs, T rhs) { return rhs; } - -// This is a wrapping absolute value function, so a negative number that is not -// representable as a positive number will be unchanged (e.g. abs(-128) = 128). -// -// Note that std::abs() does not have this behavior (e.g. abs(-128) is UB). -// Similarly, using unary minus is also UB. -template <typename T> -T WABT_VECTORCALL IntAbs(T val) { - static_assert(std::is_unsigned<T>::value, "T must be unsigned."); - const auto signbit = T(-1) << (sizeof(T) * 8 - 1); - return (val & signbit) ? ~val + 1 : val; -} - -// Because of the integer promotion rules [1], any value of a type T which is -// smaller than `int` will be converted to an `int`, as long as `int` can hold -// any value of type T. -// -// So type `u16` will be promoted to `int`, since all values can be stored in -// an int. Unfortunately, the product of two `u16` values cannot always be -// stored in an `int` (e.g. 65535 * 65535). This triggers an error in UBSan. -// -// As a result, we make sure to promote the type ahead of time for `u16`. Note -// that this isn't a problem for any other unsigned types. -// -// [1]; https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion -template <typename T> struct PromoteMul { using type = T; }; -template <> struct PromoteMul<u16> { using type = u32; }; - -template <typename T> -T WABT_VECTORCALL Mul(T lhs, T rhs) { - using U = typename PromoteMul<T>::type; - return CanonNaN(U(lhs) * U(rhs)); -} - -template <typename T> struct Mask { using Type = T; }; -template <> struct Mask<f32> { using Type = u32; }; -template <> struct Mask<f64> { using Type = u64; }; - -template <typename T> typename Mask<T>::Type WABT_VECTORCALL EqMask(T lhs, T rhs) { return lhs == rhs ? -1 : 0; } -template <typename T> typename Mask<T>::Type WABT_VECTORCALL NeMask(T lhs, T rhs) { return lhs != rhs ? -1 : 0; } -template <typename T> typename Mask<T>::Type WABT_VECTORCALL LtMask(T lhs, T rhs) { return lhs < rhs ? -1 : 0; } -template <typename T> typename Mask<T>::Type WABT_VECTORCALL LeMask(T lhs, T rhs) { return lhs <= rhs ? -1 : 0; } -template <typename T> typename Mask<T>::Type WABT_VECTORCALL GtMask(T lhs, T rhs) { return lhs > rhs ? -1 : 0; } -template <typename T> typename Mask<T>::Type WABT_VECTORCALL GeMask(T lhs, T rhs) { return lhs >= rhs ? -1 : 0; } - -template <typename T> -T WABT_VECTORCALL IntRotl(T lhs, T rhs) { - return (lhs << ShiftMask(rhs)) | (lhs >> ShiftMask<T>(0 - rhs)); -} - -template <typename T> -T WABT_VECTORCALL IntRotr(T lhs, T rhs) { - return (lhs >> ShiftMask(rhs)) | (lhs << ShiftMask<T>(0 - rhs)); -} - -// i{32,64}.{div,rem}_s are special-cased because they trap when dividing the -// max signed value by -1. The modulo operation on x86 uses the same -// instruction to generate the quotient and the remainder. -template <typename T, - typename std::enable_if<std::is_signed<T>::value, int>::type = 0> -bool IsNormalDivRem(T lhs, T rhs) { - return !(lhs == std::numeric_limits<T>::min() && rhs == -1); -} - -template <typename T, - typename std::enable_if<!std::is_signed<T>::value, int>::type = 0> -bool IsNormalDivRem(T lhs, T rhs) { - return true; -} - -template <typename T> -RunResult WABT_VECTORCALL IntDiv(T lhs, T rhs, T* out, std::string* out_msg) { - if (WABT_UNLIKELY(rhs == 0)) { - *out_msg = "integer divide by zero"; - return RunResult::Trap; - } - if (WABT_LIKELY(IsNormalDivRem(lhs, rhs))) { - *out = lhs / rhs; - return RunResult::Ok; - } else { - *out_msg = "integer overflow"; - return RunResult::Trap; - } -} - -template <typename T> -RunResult WABT_VECTORCALL IntRem(T lhs, T rhs, T* out, std::string* out_msg) { - if (WABT_UNLIKELY(rhs == 0)) { - *out_msg = "integer divide by zero"; - return RunResult::Trap; - } - if (WABT_LIKELY(IsNormalDivRem(lhs, rhs))) { - *out = lhs % rhs; - } else { - *out = 0; - } - return RunResult::Ok; -} - -#if COMPILER_IS_MSVC -template <typename T> T WABT_VECTORCALL FloatAbs(T val); -template <typename T> T WABT_VECTORCALL FloatCopysign(T lhs, T rhs); - -// Don't use std::{abs,copysign} directly on MSVC, since that seems to lose -// the NaN tag. -template <> -inline f32 WABT_VECTORCALL FloatAbs(f32 val) { - return _mm_cvtss_f32(_mm_and_ps( - _mm_set1_ps(val), _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)))); -} - -template <> -inline f64 WABT_VECTORCALL FloatAbs(f64 val) { - return _mm_cvtsd_f64( - _mm_and_pd(_mm_set1_pd(val), - _mm_castsi128_pd(_mm_set1_epi64x(0x7fffffffffffffffull)))); -} - -template <> -inline f32 WABT_VECTORCALL FloatCopysign(f32 lhs, f32 rhs) { - return _mm_cvtss_f32( - _mm_or_ps(_mm_and_ps(_mm_set1_ps(lhs), - _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff))), - _mm_and_ps(_mm_set1_ps(rhs), - _mm_castsi128_ps(_mm_set1_epi32(0x80000000))))); -} - -template <> -inline f64 WABT_VECTORCALL FloatCopysign(f64 lhs, f64 rhs) { - return _mm_cvtsd_f64(_mm_or_pd( - _mm_and_pd(_mm_set1_pd(lhs), - _mm_castsi128_pd(_mm_set1_epi64x(0x7fffffffffffffffull))), - _mm_and_pd(_mm_set1_pd(rhs), - _mm_castsi128_pd(_mm_set1_epi64x(0x8000000000000000ull))))); -} - -#else -template <typename T> -T WABT_VECTORCALL FloatAbs(T val) { - return std::abs(val); -} - -template <typename T> -T WABT_VECTORCALL FloatCopysign(T lhs, T rhs) { - return std::copysign(lhs, rhs); -} -#endif - -#if COMPILER_IS_MSVC -#else -#endif - -template <typename T> T WABT_VECTORCALL FloatNeg(T val) { return -val; } -template <typename T> T WABT_VECTORCALL FloatCeil(T val) { return CanonNaN(std::ceil(val)); } -template <typename T> T WABT_VECTORCALL FloatFloor(T val) { return CanonNaN(std::floor(val)); } -template <typename T> T WABT_VECTORCALL FloatTrunc(T val) { return CanonNaN(std::trunc(val)); } -template <typename T> T WABT_VECTORCALL FloatNearest(T val) { return CanonNaN(std::nearbyint(val)); } -template <typename T> T WABT_VECTORCALL FloatSqrt(T val) { return CanonNaN(std::sqrt(val)); } - -template <typename T> -T WABT_VECTORCALL FloatDiv(T lhs, T rhs) { - // IEE754 specifies what should happen when dividing a float by zero, but - // C/C++ says it is undefined behavior. - if (WABT_UNLIKELY(rhs == 0)) { - return std::isnan(lhs) || lhs == 0 - ? std::numeric_limits<T>::quiet_NaN() - : ((std::signbit(lhs) ^ std::signbit(rhs)) - ? -std::numeric_limits<T>::infinity() - : std::numeric_limits<T>::infinity()); - } - return CanonNaN(lhs / rhs); -} - -template <typename T> -T WABT_VECTORCALL FloatMin(T lhs, T rhs) { - if (WABT_UNLIKELY(std::isnan(lhs) || std::isnan(rhs))) { - return std::numeric_limits<T>::quiet_NaN(); - } else if (WABT_UNLIKELY(lhs == 0 && rhs == 0)) { - return std::signbit(lhs) ? lhs : rhs; - } else { - return std::min(lhs, rhs); - } -} - -template <typename T> -T WABT_VECTORCALL FloatPMin(T lhs, T rhs) { - return std::min(lhs, rhs); -} - -template <typename T> -T WABT_VECTORCALL FloatMax(T lhs, T rhs) { - if (WABT_UNLIKELY(std::isnan(lhs) || std::isnan(rhs))) { - return std::numeric_limits<T>::quiet_NaN(); - } else if (WABT_UNLIKELY(lhs == 0 && rhs == 0)) { - return std::signbit(lhs) ? rhs : lhs; - } else { - return std::max(lhs, rhs); - } -} - -template <typename T> -T WABT_VECTORCALL FloatPMax(T lhs, T rhs) { - return std::max(lhs, rhs); -} - -template <typename R, typename T> bool WABT_VECTORCALL CanConvert(T val) { return true; } -template <> inline bool WABT_VECTORCALL CanConvert<s32, f32>(f32 val) { return val >= -2147483648.f && val < 2147483648.f; } -template <> inline bool WABT_VECTORCALL CanConvert<s32, f64>(f64 val) { return val > -2147483649. && val < 2147483648.; } -template <> inline bool WABT_VECTORCALL CanConvert<u32, f32>(f32 val) { return val > -1.f && val < 4294967296.f; } -template <> inline bool WABT_VECTORCALL CanConvert<u32, f64>(f64 val) { return val > -1. && val < 4294967296.; } -template <> inline bool WABT_VECTORCALL CanConvert<s64, f32>(f32 val) { return val >= -9223372036854775808.f && val < 9223372036854775808.f; } -template <> inline bool WABT_VECTORCALL CanConvert<s64, f64>(f64 val) { return val >= -9223372036854775808. && val < 9223372036854775808.; } -template <> inline bool WABT_VECTORCALL CanConvert<u64, f32>(f32 val) { return val > -1.f && val < 18446744073709551616.f; } -template <> inline bool WABT_VECTORCALL CanConvert<u64, f64>(f64 val) { return val > -1. && val < 18446744073709551616.; } - -template <typename R, typename T> -R WABT_VECTORCALL Convert(T val) { - assert((CanConvert<R, T>(val))); - return static_cast<R>(val); -} - -template <> -inline f32 WABT_VECTORCALL Convert(f64 val) { - // The WebAssembly rounding mode means that these values (which are > F32_MAX) - // should be rounded to F32_MAX and not set to infinity. Unfortunately, UBSAN - // complains that the value is not representable as a float, so we'll special - // case them. - const f64 kMin = 3.4028234663852886e38; - const f64 kMax = 3.4028235677973366e38; - if (WABT_LIKELY(val >= -kMin && val <= kMin)) { - return val; - } else if (WABT_UNLIKELY(val > kMin && val < kMax)) { - return std::numeric_limits<f32>::max(); - } else if (WABT_UNLIKELY(val > -kMax && val < -kMin)) { - return -std::numeric_limits<f32>::max(); - } else if (WABT_UNLIKELY(std::isnan(val))) { - return std::numeric_limits<f32>::quiet_NaN(); - } else { - return std::copysign(std::numeric_limits<f32>::infinity(), val); - } -} - -template <> -inline f32 WABT_VECTORCALL Convert(u64 val) { - return wabt_convert_uint64_to_float(val); -} - -template <> -inline f64 WABT_VECTORCALL Convert(u64 val) { - return wabt_convert_uint64_to_double(val); -} - -template <> -inline f32 WABT_VECTORCALL Convert(s64 val) { - return wabt_convert_int64_to_float(val); -} - -template <> -inline f64 WABT_VECTORCALL Convert(s64 val) { - return wabt_convert_int64_to_double(val); -} - -template <typename T, int N> -T WABT_VECTORCALL IntExtend(T val) { - // Hacker's delight 2.6 - sign extension - auto bit = T{1} << N; - auto mask = (bit << 1) - 1; - return ((val & mask) ^ bit) - bit; -} - -template <typename R, typename T> -R WABT_VECTORCALL IntTruncSat(T val) { - if (WABT_UNLIKELY(std::isnan(val))) { - return 0; - } else if (WABT_UNLIKELY(!CanConvert<R>(val))) { - return std::signbit(val) ? std::numeric_limits<R>::min() - : std::numeric_limits<R>::max(); - } else { - return static_cast<R>(val); - } -} - -template <typename T> struct SatPromote; -template <> struct SatPromote<s8> { using type = s32; }; -template <> struct SatPromote<s16> { using type = s32; }; -template <> struct SatPromote<u8> { using type = s32; }; -template <> struct SatPromote<u16> { using type = s32; }; - -template <typename R, typename T> -R WABT_VECTORCALL Saturate(T val) { - static_assert(sizeof(R) < sizeof(T), "Incorrect types for Saturate"); - const T min = std::numeric_limits<R>::min(); - const T max = std::numeric_limits<R>::max(); - return val > max ? max : val < min ? min : val; -} - -template <typename T, typename U = typename SatPromote<T>::type> -T WABT_VECTORCALL IntAddSat(T lhs, T rhs) { - return Saturate<T, U>(lhs + rhs); -} - -template <typename T, typename U = typename SatPromote<T>::type> -T WABT_VECTORCALL IntSubSat(T lhs, T rhs) { - return Saturate<T, U>(lhs - rhs); -} - -template <typename T> -T WABT_VECTORCALL SaturatingRoundingQMul(T lhs, T rhs) { - constexpr int size_in_bits = sizeof(T) * 8; - int round_const = 1 << (size_in_bits - 2); - int64_t product = lhs * rhs; - product += round_const; - product >>= (size_in_bits - 1); - return Saturate<T, int64_t>(product); -} - -} // namespace interp -} // namespace wabt - -#endif // WABT_INTERP_MATH_H_ diff --git a/src/interp/interp-util.cc b/src/interp/interp-util.cc index b4f53ba9..5267f4ae 100644 --- a/src/interp/interp-util.cc +++ b/src/interp/interp-util.cc @@ -14,11 +14,11 @@ * limitations under the License. */ -#include "src/interp/interp-util.h" +#include "wabt/interp/interp-util.h" #include <cinttypes> -#include "src/stream.h" +#include "wabt/stream.h" namespace wabt { namespace interp { diff --git a/src/interp/interp-util.h b/src/interp/interp-util.h deleted file mode 100644 index fabe1ced..00000000 --- a/src/interp/interp-util.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2020 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_INTERP_UTIL_H_ -#define WABT_INTERP_UTIL_H_ - -#include <string> -#include <string_view> -#include <vector> - -#include "src/interp/interp.h" - -namespace wabt { - -class Stream; - -namespace interp { - -std::string TypedValueToString(const TypedValue&); - -void WriteValue(Stream* stream, const TypedValue&); - -void WriteValues(Stream* stream, const ValueTypes&, const Values&); - -void WriteTrap(Stream* stream, const char* desc, const Trap::Ptr&); - -void WriteCall(Stream* stream, - std::string_view name, - const FuncType& func_type, - const Values& params, - const Values& results, - const Trap::Ptr& trap); - -} // namespace interp -} // namespace wabt - -#endif // WABT_INTERP_UTIL_H_ diff --git a/src/interp/interp-wasi.cc b/src/interp/interp-wasi.cc index 61b6f71d..3f8f310b 100644 --- a/src/interp/interp-wasi.cc +++ b/src/interp/interp-wasi.cc @@ -28,8 +28,8 @@ * https://github.com/WebAssembly/wasi-libc/blob/master/libc-bottom-half/headers/public/wasi/api.h */ -#include "src/interp/interp-wasi.h" -#include "src/interp/interp-util.h" +#include "wabt/interp/interp-wasi.h" +#include "wabt/interp/interp-util.h" #ifdef WITH_WASI diff --git a/src/interp/interp-wasi.h b/src/interp/interp-wasi.h deleted file mode 100644 index 465d176c..00000000 --- a/src/interp/interp-wasi.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2020 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_INTERP_WASI_H_ -#define WABT_INTERP_WASI_H_ - -#include "src/common.h" -#include "src/error.h" -#include "src/interp/interp.h" - -#ifdef WITH_WASI - -struct uvwasi_s; - -namespace wabt { -namespace interp { - -Result WasiBindImports(const Module::Ptr& module, - RefVec& imports, - Stream* err_stream, - Stream* trace_stream); - -Result WasiRunStart(const Instance::Ptr& instance, - uvwasi_s* uvwasi, - Stream* stream, - Stream* trace_stream); - -} // namespace interp -} // namespace wabt - -#endif - -#endif /* WABT_INTERP_WASI_H_ */ diff --git a/src/interp/interp-wasm-c-api.cc b/src/interp/interp-wasm-c-api.cc index 14bfa83b..fe5be6c5 100644 --- a/src/interp/interp-wasm-c-api.cc +++ b/src/interp/interp-wasm-c-api.cc @@ -16,12 +16,12 @@ #include <wasm.h> -#include "src/binary-reader.h" -#include "src/cast.h" -#include "src/error-formatter.h" -#include "src/interp/binary-reader-interp.h" -#include "src/interp/interp-util.h" -#include "src/interp/interp.h" +#include "wabt/binary-reader.h" +#include "wabt/cast.h" +#include "wabt/error-formatter.h" +#include "wabt/interp/binary-reader-interp.h" +#include "wabt/interp/interp-util.h" +#include "wabt/interp/interp.h" using namespace wabt; using namespace wabt::interp; diff --git a/src/interp/interp.cc b/src/interp/interp.cc index 161724b1..e78cb76b 100644 --- a/src/interp/interp.cc +++ b/src/interp/interp.cc @@ -14,14 +14,14 @@ * limitations under the License. */ -#include "src/interp/interp.h" +#include "wabt/interp/interp.h" #include <algorithm> #include <cassert> #include <cinttypes> -#include "src/interp/interp-math.h" -#include "src/make-unique.h" +#include "wabt/interp/interp-math.h" +#include "wabt/make-unique.h" namespace wabt { namespace interp { diff --git a/src/interp/interp.h b/src/interp/interp.h deleted file mode 100644 index df170102..00000000 --- a/src/interp/interp.h +++ /dev/null @@ -1,1275 +0,0 @@ -/* - * Copyright 2020 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_INTERP_H_ -#define WABT_INTERP_H_ - -#include <cstdint> -#include <functional> -#include <memory> -#include <set> -#include <string> -#include <string_view> -#include <type_traits> -#include <vector> - -#include "src/cast.h" -#include "src/common.h" -#include "src/feature.h" -#include "src/opcode.h" -#include "src/result.h" - -#include "src/interp/istream.h" - -namespace wabt { -namespace interp { - -class Store; -class Object; -class Trap; -class DataSegment; -class ElemSegment; -class Module; -class Instance; -class Thread; -template <typename T> -class RefPtr; - -using s8 = int8_t; -using u8 = uint8_t; -using s16 = int16_t; -using u16 = uint16_t; -using s32 = int32_t; -using u32 = uint32_t; -using Index = uint32_t; -using s64 = int64_t; -using u64 = uint64_t; -using f32 = float; -using f64 = double; - -using Buffer = std::vector<u8>; - -using ValueType = wabt::Type; -using ValueTypes = std::vector<ValueType>; - -template <typename T> -bool HasType(ValueType); -template <typename T> -void RequireType(ValueType); -bool IsReference(ValueType); -bool TypesMatch(ValueType expected, ValueType actual); - -using ExternKind = ExternalKind; -enum class Mutability { Const, Var }; -enum class TagAttr { Exception }; -using SegmentMode = SegmentKind; -enum class ElemKind { RefNull, RefFunc }; - -enum class ObjectKind { - Null, - Foreign, - Trap, - Exception, - DefinedFunc, - HostFunc, - Table, - Memory, - Global, - Tag, - Module, - Instance, - - First = Null, - Last = Instance, -}; - -static const int kCommandTypeCount = WABT_ENUM_COUNT(ObjectKind); - -const char* GetName(Mutability); -const std::string GetName(ValueType); -const char* GetName(ExternKind); -const char* GetName(ObjectKind); - -struct Ref { - static const Ref Null; - - Ref() = default; - explicit Ref(size_t index); - - friend bool operator==(Ref, Ref); - friend bool operator!=(Ref, Ref); - - size_t index; -}; -using RefVec = std::vector<Ref>; - -template <typename T, u8 L> -struct Simd { - using LaneType = T; - static const u8 lanes = L; - - T v[L]; - - inline T& operator[](u8 idx) { -#if WABT_BIG_ENDIAN - idx = (~idx) & (L - 1); -#endif - return v[idx]; - } - inline T operator[](u8 idx) const { -#if WABT_BIG_ENDIAN - idx = (~idx) & (L - 1); -#endif - return v[idx]; - } -}; -using s8x16 = Simd<s8, 16>; -using u8x16 = Simd<u8, 16>; -using s16x8 = Simd<s16, 8>; -using u16x8 = Simd<u16, 8>; -using s32x4 = Simd<s32, 4>; -using u32x4 = Simd<u32, 4>; -using s64x2 = Simd<s64, 2>; -using u64x2 = Simd<u64, 2>; -using f32x4 = Simd<f32, 4>; -using f64x2 = Simd<f64, 2>; - -// Used for load extend instructions. -using s8x8 = Simd<s8, 8>; -using u8x8 = Simd<u8, 8>; -using s16x4 = Simd<s16, 4>; -using u16x4 = Simd<u16, 4>; -using s32x2 = Simd<s32, 2>; -using u32x2 = Simd<u32, 2>; - -//// Types //// - -bool CanGrow(const Limits&, u32 old_size, u32 delta, u32* new_size); -Result Match(const Limits& expected, - const Limits& actual, - std::string* out_msg); - -struct ExternType { - explicit ExternType(ExternKind); - virtual ~ExternType() {} - virtual std::unique_ptr<ExternType> Clone() const = 0; - - ExternKind kind; -}; - -struct FuncType : ExternType { - static const ExternKind skind = ExternKind::Func; - static bool classof(const ExternType* type); - - explicit FuncType(ValueTypes params, ValueTypes results); - - std::unique_ptr<ExternType> Clone() const override; - - friend Result Match(const FuncType& expected, - const FuncType& actual, - std::string* out_msg); - - ValueTypes params; - ValueTypes results; -}; - -struct TableType : ExternType { - static const ExternKind skind = ExternKind::Table; - static bool classof(const ExternType* type); - - explicit TableType(ValueType, Limits); - - std::unique_ptr<ExternType> Clone() const override; - - friend Result Match(const TableType& expected, - const TableType& actual, - std::string* out_msg); - - ValueType element; - Limits limits; -}; - -struct MemoryType : ExternType { - static const ExternKind skind = ExternKind::Memory; - static bool classof(const ExternType* type); - - explicit MemoryType(Limits); - - std::unique_ptr<ExternType> Clone() const override; - - friend Result Match(const MemoryType& expected, - const MemoryType& actual, - std::string* out_msg); - - Limits limits; -}; - -struct GlobalType : ExternType { - static const ExternKind skind = ExternKind::Global; - static bool classof(const ExternType* type); - - explicit GlobalType(ValueType, Mutability); - - std::unique_ptr<ExternType> Clone() const override; - - friend Result Match(const GlobalType& expected, - const GlobalType& actual, - std::string* out_msg); - - ValueType type; - Mutability mut; -}; - -struct TagType : ExternType { - static const ExternKind skind = ExternKind::Tag; - static bool classof(const ExternType* type); - - explicit TagType(TagAttr, const ValueTypes&); - - std::unique_ptr<ExternType> Clone() const override; - - friend Result Match(const TagType& expected, - const TagType& actual, - std::string* out_msg); - - TagAttr attr; - ValueTypes signature; -}; - -struct ImportType { - explicit ImportType(std::string module, - std::string name, - std::unique_ptr<ExternType>); - ImportType(const ImportType&); - ImportType& operator=(const ImportType&); - - std::string module; - std::string name; - std::unique_ptr<ExternType> type; -}; - -struct ExportType { - explicit ExportType(std::string name, std::unique_ptr<ExternType>); - ExportType(const ExportType&); - ExportType& operator=(const ExportType&); - - std::string name; - std::unique_ptr<ExternType> type; -}; - -//// Structure //// - -struct ImportDesc { - ImportType type; -}; - -struct LocalDesc { - ValueType type; - u32 count; - // One past the last local index that has this type. For example, a vector of - // LocalDesc might look like: - // - // {{I32, 2, 2}, {I64, 3, 5}, {F32, 1, 6}, ...} - // - // This makes it possible to use a binary search to find the type of a local - // at a given index. - u32 end; -}; - -// Metadata for representing exception handlers associated with a function's -// code. This is needed to look up exceptions from call frames from interpreter -// instructions. -struct CatchDesc { - Index tag_index; - u32 offset; -}; - -// Handlers for a catch-less `try` or `try-catch` block are included in the -// Catch kind. `try-delegate` instructions create a Delegate handler. -enum class HandlerKind { Catch, Delegate }; - -struct HandlerDesc { - HandlerKind kind; - u32 try_start_offset; - u32 try_end_offset; - std::vector<CatchDesc> catches; - union { - u32 catch_all_offset; - u32 delegate_handler_index; - }; - // Local stack heights at the handler site that need to be restored. - u32 values; - u32 exceptions; -}; - -struct FuncDesc { - // Includes params. - ValueType GetLocalType(Index) const; - - FuncType type; - std::vector<LocalDesc> locals; - u32 code_offset; // Istream offset. - std::vector<HandlerDesc> handlers; -}; - -struct TableDesc { - TableType type; -}; - -struct MemoryDesc { - MemoryType type; -}; - -struct GlobalDesc { - GlobalType type; - FuncDesc init_func; -}; - -struct TagDesc { - TagType type; -}; - -struct ExportDesc { - ExportType type; - Index index; -}; - -struct StartDesc { - Index func_index; -}; - -struct DataDesc { - Buffer data; - SegmentMode mode; - Index memory_index; - FuncDesc init_func; -}; - -struct ElemExpr { - ElemKind kind; - Index index; -}; - -struct ElemDesc { - std::vector<ElemExpr> elements; - ValueType type; - SegmentMode mode; - Index table_index; - FuncDesc init_func; -}; - -struct ModuleDesc { - std::vector<FuncType> func_types; - std::vector<ImportDesc> imports; - std::vector<FuncDesc> funcs; - std::vector<TableDesc> tables; - std::vector<MemoryDesc> memories; - std::vector<GlobalDesc> globals; - std::vector<TagDesc> tags; - std::vector<ExportDesc> exports; - std::vector<StartDesc> starts; - std::vector<ElemDesc> elems; - std::vector<DataDesc> datas; - Istream istream; -}; - -//// Runtime //// - -struct Frame { - explicit Frame(Ref func, - u32 values, - u32 exceptions, - u32 offset, - Instance*, - Module*); - - void Mark(Store&); - - Ref func; - u32 values; // Height of the value stack at this activation. - u32 exceptions; // Height of the exception stack at this activation. - u32 offset; // Istream offset; either the return PC, or the current PC. - - // Cached for convenience. Both are null if func is a HostFunc. - Instance* inst; - Module* mod; -}; - -template <typename T> -class FreeList { - public: - using Index = size_t; - - ~FreeList(); - - template <typename... Args> - Index New(Args&&...); - void Delete(Index); - - bool IsUsed(Index) const; - - const T& Get(Index) const; - T& Get(Index); - - Index size() const; // 1 greater than the maximum index. - Index count() const; // The number of used elements. - - private: - // As for Refs, the free bit is 0x80..0. This bit is never - // set for valid Refs, since it would mean more objects - // are allocated than the total amount of memory. - static const Index refFreeBit = (SIZE_MAX >> 1) + 1; - - // As for Objects, the free bit is 0x1. This bit is never - // set for valid Objects, since pointers are aligned to at - // least four bytes. - static const Index ptrFreeBit = 1; - static const int ptrFreeShift = 1; - - std::vector<T> list_; - // If free_head_ is zero, there is no free slots in list_, - // otherwise free_head_ - 1 represents the first free slot. - Index free_head_ = 0; - Index free_items_ = 0; -}; - -class Store { - public: - using ObjectList = FreeList<Object*>; - using RootList = FreeList<Ref>; - - explicit Store(const Features& = Features{}); - - Store(const Store&) = delete; - Store& operator=(const Store&) = delete; - Store& operator=(const Store&&) = delete; - - bool IsValid(Ref) const; - bool HasValueType(Ref, ValueType) const; - template <typename T> - bool Is(Ref) const; - - template <typename T, typename... Args> - RefPtr<T> Alloc(Args&&...); - template <typename T> - Result Get(Ref, RefPtr<T>* out); - template <typename T> - RefPtr<T> UnsafeGet(Ref); - - RootList::Index NewRoot(Ref); - RootList::Index CopyRoot(RootList::Index); - void DeleteRoot(RootList::Index); - - void Collect(); - void Mark(Ref); - void Mark(const RefVec&); - - ObjectList::Index object_count() const; - - const Features& features() const; - void setFeatures(const Features& features) { features_ = features; } - - std::set<Thread*>& threads(); - - private: - template <typename T> - friend class RefPtr; - - struct GCContext { - int call_depth = 0; - std::vector<bool> marks; - std::vector<size_t> untraced_objects; - }; - - static const int max_call_depth = 10; - - Features features_; - GCContext gc_context_; - // This set contains the currently active Thread objects. - std::set<Thread*> threads_; - ObjectList objects_; - RootList roots_; -}; - -template <typename T> -class RefPtr { - public: - RefPtr(); - RefPtr(Store&, Ref); - RefPtr(const RefPtr&); - RefPtr& operator=(const RefPtr&); - RefPtr(RefPtr&&); - RefPtr& operator=(RefPtr&&); - ~RefPtr(); - - template <typename U> - RefPtr(const RefPtr<U>&); - template <typename U> - RefPtr& operator=(const RefPtr<U>&); - template <typename U> - RefPtr(RefPtr&&); - template <typename U> - RefPtr& operator=(RefPtr&&); - - template <typename U> - RefPtr<U> As(); - - bool empty() const; - void reset(); - - T* get() const; - T* operator->() const; - T& operator*() const; - explicit operator bool() const; - - Ref ref() const; - Store* store() const; - - template <typename U, typename V> - friend bool operator==(const RefPtr<U>& lhs, const RefPtr<V>& rhs); - template <typename U, typename V> - friend bool operator!=(const RefPtr<U>& lhs, const RefPtr<V>& rhs); - - private: - template <typename U> - friend class RefPtr; - - T* obj_; - Store* store_; - Store::RootList::Index root_index_; -}; - -struct Value { - static Value WABT_VECTORCALL Make(s32); - static Value WABT_VECTORCALL Make(u32); - static Value WABT_VECTORCALL Make(s64); - static Value WABT_VECTORCALL Make(u64); - static Value WABT_VECTORCALL Make(f32); - static Value WABT_VECTORCALL Make(f64); - static Value WABT_VECTORCALL Make(v128); - static Value WABT_VECTORCALL Make(Ref); - template <typename T, u8 L> - static Value WABT_VECTORCALL Make(Simd<T, L>); - - template <typename T> - T WABT_VECTORCALL Get() const; - template <typename T> - void WABT_VECTORCALL Set(T); - - private: - union { - u32 i32_; - u64 i64_; - f32 f32_; - f64 f64_; - v128 v128_; - Ref ref_; - }; - - public: -#ifndef NDEBUG - Value() : v128_(0, 0, 0, 0), type(ValueType::Any) {} - void SetType(ValueType t) { type = t; } - void CheckType(ValueType t) const { - // Sadly we must allow Any here, since locals may be uninitialized. - // Alternatively we could modify InterpAlloca to set the type. - assert(t == type || type == ValueType::Any); - } - ValueType type; -#else - Value() : v128_(0, 0, 0, 0) {} - void SetType(ValueType) {} - void CheckType(ValueType) const {} -#endif -}; -using Values = std::vector<Value>; - -struct TypedValue { - ValueType type; - Value value; -}; -using TypedValues = std::vector<TypedValue>; - -using Finalizer = std::function<void(Object*)>; - -class Object { - public: - static bool classof(const Object* obj); - static const char* GetTypeName() { return "Object"; } - using Ptr = RefPtr<Object>; - - Object(const Object&) = delete; - Object& operator=(const Object&) = delete; - - virtual ~Object(); - - ObjectKind kind() const; - Ref self() const; - - void* host_info() const; - void set_host_info(void*); - - Finalizer get_finalizer() const; - void set_finalizer(Finalizer); - - protected: - friend Store; - explicit Object(ObjectKind); - virtual void Mark(Store&) {} - - ObjectKind kind_; - Finalizer finalizer_ = nullptr; - void* host_info_ = nullptr; - Ref self_ = Ref::Null; -}; - -class Foreign : public Object { - public: - static const ObjectKind skind = ObjectKind::Foreign; - static bool classof(const Object* obj); - static const char* GetTypeName() { return "Foreign"; } - using Ptr = RefPtr<Foreign>; - - static Foreign::Ptr New(Store&, void*); - - void* ptr(); - - private: - friend Store; - explicit Foreign(Store&, void*); - void Mark(Store&) override; - - void* ptr_; -}; - -class Trap : public Object { - public: - static const ObjectKind skind = ObjectKind::Trap; - static bool classof(const Object* obj); - using Ptr = RefPtr<Trap>; - - static Trap::Ptr New(Store&, - const std::string& msg, - const std::vector<Frame>& trace = std::vector<Frame>()); - - std::string message() const; - - private: - friend Store; - explicit Trap(Store&, - const std::string& msg, - const std::vector<Frame>& trace = std::vector<Frame>()); - void Mark(Store&) override; - - std::string message_; - std::vector<Frame> trace_; -}; - -class Exception : public Object { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::Exception; - static const char* GetTypeName() { return "Exception"; } - using Ptr = RefPtr<Exception>; - - static Exception::Ptr New(Store&, Ref tag, Values& args); - - Ref tag() const; - Values& args(); - - private: - friend Store; - explicit Exception(Store&, Ref, Values&); - void Mark(Store&) override; - - Ref tag_; - Values args_; -}; - -class Extern : public Object { - public: - static bool classof(const Object* obj); - static const char* GetTypeName() { return "Foreign"; } - using Ptr = RefPtr<Extern>; - - virtual Result Match(Store&, const ImportType&, Trap::Ptr* out_trap) = 0; - virtual const ExternType& extern_type() = 0; - - protected: - friend Store; - explicit Extern(ObjectKind); - - template <typename T> - Result MatchImpl(Store&, - const ImportType&, - const T& actual, - Trap::Ptr* out_trap); -}; - -class Func : public Extern { - public: - static bool classof(const Object* obj); - using Ptr = RefPtr<Func>; - - Result Call(Thread& thread, - const Values& params, - Values& results, - Trap::Ptr* out_trap); - - // Convenience function that creates new Thread. - Result Call(Store&, - const Values& params, - Values& results, - Trap::Ptr* out_trap, - Stream* = nullptr); - - const ExternType& extern_type() override; - const FuncType& type() const; - - protected: - explicit Func(ObjectKind, FuncType); - virtual Result DoCall(Thread& thread, - const Values& params, - Values& results, - Trap::Ptr* out_trap) = 0; - - FuncType type_; -}; - -class DefinedFunc : public Func { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::DefinedFunc; - static const char* GetTypeName() { return "DefinedFunc"; } - using Ptr = RefPtr<DefinedFunc>; - - static DefinedFunc::Ptr New(Store&, Ref instance, FuncDesc); - - Result Match(Store&, const ImportType&, Trap::Ptr* out_trap) override; - - Ref instance() const; - const FuncDesc& desc() const; - - protected: - Result DoCall(Thread& thread, - const Values& params, - Values& results, - Trap::Ptr* out_trap) override; - - private: - friend Store; - explicit DefinedFunc(Store&, Ref instance, FuncDesc); - void Mark(Store&) override; - - Ref instance_; - FuncDesc desc_; -}; - -class HostFunc : public Func { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::HostFunc; - static const char* GetTypeName() { return "HostFunc"; } - using Ptr = RefPtr<HostFunc>; - - using Callback = std::function<Result(Thread& thread, - const Values& params, - Values& results, - Trap::Ptr* out_trap)>; - - static HostFunc::Ptr New(Store&, FuncType, Callback); - - Result Match(Store&, const ImportType&, Trap::Ptr* out_trap) override; - - protected: - Result DoCall(Thread& thread, - const Values& params, - Values& results, - Trap::Ptr* out_trap) override; - - private: - friend Store; - friend Thread; - explicit HostFunc(Store&, FuncType, Callback); - void Mark(Store&) override; - - Callback callback_; -}; - -class Table : public Extern { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::Table; - static const char* GetTypeName() { return "Table"; } - using Ptr = RefPtr<Table>; - - static Table::Ptr New(Store&, TableType); - - Result Match(Store&, const ImportType&, Trap::Ptr* out_trap) override; - - bool IsValidRange(u32 offset, u32 size) const; - - Result Get(u32 offset, Ref* out) const; - Result Set(Store&, u32 offset, Ref); - Result Grow(Store&, u32 count, Ref); - Result Fill(Store&, u32 offset, Ref, u32 size); - Result Init(Store&, - u32 dst_offset, - const ElemSegment&, - u32 src_offset, - u32 size); - static Result Copy(Store&, - Table& dst, - u32 dst_offset, - const Table& src, - u32 src_offset, - u32 size); - - // Unsafe API. - Ref UnsafeGet(u32 offset) const; - - const ExternType& extern_type() override; - const TableType& type() const; - const RefVec& elements() const; - u32 size() const; - - private: - friend Store; - explicit Table(Store&, TableType); - void Mark(Store&) override; - - TableType type_; - RefVec elements_; -}; - -class Memory : public Extern { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::Memory; - static const char* GetTypeName() { return "Memory"; } - using Ptr = RefPtr<Memory>; - - static Memory::Ptr New(Store&, MemoryType); - - Result Match(Store&, const ImportType&, Trap::Ptr* out_trap) override; - - bool IsValidAccess(u64 offset, u64 addend, u64 size) const; - bool IsValidAtomicAccess(u64 offset, u64 addend, u64 size) const; - - template <typename T> - Result Load(u64 offset, u64 addend, T* out) const; - template <typename T> - Result WABT_VECTORCALL Store(u64 offset, u64 addend, T); - Result Grow(u64 pages); - Result Fill(u64 offset, u8 value, u64 size); - Result Init(u64 dst_offset, const DataSegment&, u64 src_offset, u64 size); - static Result Copy(Memory& dst, - u64 dst_offset, - const Memory& src, - u64 src_offset, - u64 size); - - // Fake atomics; just checks alignment. - template <typename T> - Result AtomicLoad(u64 offset, u64 addend, T* out) const; - template <typename T> - Result AtomicStore(u64 offset, u64 addend, T); - template <typename T, typename F> - Result AtomicRmw(u64 offset, u64 addend, T, F&& func, T* out); - template <typename T> - Result AtomicRmwCmpxchg(u64 offset, u64 addend, T expect, T replace, T* out); - - u64 ByteSize() const; - u64 PageSize() const; - - // Unsafe API. - template <typename T> - T WABT_VECTORCALL UnsafeLoad(u64 offset, u64 addend) const; - u8* UnsafeData(); - - const ExternType& extern_type() override; - const MemoryType& type() const; - - private: - friend class Store; - explicit Memory(class Store&, MemoryType); - void Mark(class Store&) override; - - MemoryType type_; - Buffer data_; - u64 pages_; -}; - -class Global : public Extern { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::Global; - static const char* GetTypeName() { return "Global"; } - using Ptr = RefPtr<Global>; - - static Global::Ptr New(Store&, GlobalType, Value); - - Result Match(Store&, const ImportType&, Trap::Ptr* out_trap) override; - - Value Get() const; - template <typename T> - Result Get(T* out) const; - template <typename T> - Result WABT_VECTORCALL Set(T); - Result Set(Store&, Ref); - - template <typename T> - T WABT_VECTORCALL UnsafeGet() const; - void UnsafeSet(Value); - - const ExternType& extern_type() override; - const GlobalType& type() const; - - private: - friend Store; - explicit Global(Store&, GlobalType, Value); - void Mark(Store&) override; - - GlobalType type_; - Value value_; -}; - -class Tag : public Extern { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::Tag; - static const char* GetTypeName() { return "Tag"; } - using Ptr = RefPtr<Tag>; - - static Tag::Ptr New(Store&, TagType); - - Result Match(Store&, const ImportType&, Trap::Ptr* out_trap) override; - - const ExternType& extern_type() override; - const TagType& type() const; - - private: - friend Store; - explicit Tag(Store&, TagType); - void Mark(Store&) override; - - TagType type_; -}; - -class ElemSegment { - public: - explicit ElemSegment(const ElemDesc*, RefPtr<Instance>&); - - bool IsValidRange(u32 offset, u32 size) const; - void Drop(); - - const ElemDesc& desc() const; - const RefVec& elements() const; - u32 size() const; - - private: - friend Instance; - void Mark(Store&); - - const ElemDesc* desc_; // Borrowed from the Module. - RefVec elements_; -}; - -class DataSegment { - public: - explicit DataSegment(const DataDesc*); - - bool IsValidRange(u64 offset, u64 size) const; - void Drop(); - - const DataDesc& desc() const; - u64 size() const; - - private: - const DataDesc* desc_; // Borrowed from the Module. - u64 size_; -}; - -class Module : public Object { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::Module; - static const char* GetTypeName() { return "Module"; } - using Ptr = RefPtr<Module>; - - static Module::Ptr New(Store&, ModuleDesc); - - const ModuleDesc& desc() const; - const std::vector<ImportType>& import_types() const; - const std::vector<ExportType>& export_types() const; - - private: - friend Store; - friend Instance; - explicit Module(Store&, ModuleDesc); - void Mark(Store&) override; - - ModuleDesc desc_; - std::vector<ImportType> import_types_; - std::vector<ExportType> export_types_; -}; - -class Instance : public Object { - public: - static bool classof(const Object* obj); - static const ObjectKind skind = ObjectKind::Instance; - static const char* GetTypeName() { return "Instance"; } - using Ptr = RefPtr<Instance>; - - static Instance::Ptr Instantiate(Store&, - Ref module, - const RefVec& imports, - Trap::Ptr* out_trap); - - Ref module() const; - const RefVec& imports() const; - const RefVec& funcs() const; - const RefVec& tables() const; - const RefVec& memories() const; - const RefVec& globals() const; - const RefVec& tags() const; - const RefVec& exports() const; - const std::vector<ElemSegment>& elems() const; - std::vector<ElemSegment>& elems(); - const std::vector<DataSegment>& datas() const; - std::vector<DataSegment>& datas(); - - private: - friend Store; - friend ElemSegment; - friend DataSegment; - explicit Instance(Store&, Ref module); - void Mark(Store&) override; - - Result CallInitFunc(Store&, - const Ref func_ref, - Value* result, - Trap::Ptr* out_trap); - - Ref module_; - RefVec imports_; - RefVec funcs_; - RefVec tables_; - RefVec memories_; - RefVec globals_; - RefVec tags_; - RefVec exports_; - std::vector<ElemSegment> elems_; - std::vector<DataSegment> datas_; -}; - -enum class RunResult { - Ok, - Return, - Trap, - Exception, -}; - -class Thread { - public: - struct Options { - static const u32 kDefaultValueStackSize = 64 * 1024 / sizeof(Value); - static const u32 kDefaultCallStackSize = 64 * 1024 / sizeof(Frame); - - u32 value_stack_size = kDefaultValueStackSize; - u32 call_stack_size = kDefaultCallStackSize; - Stream* trace_stream = nullptr; - }; - - Thread(Store& store, Stream* trace_stream = nullptr); - ~Thread(); - - RunResult Run(Trap::Ptr* out_trap); - RunResult Run(int num_instructions, Trap::Ptr* out_trap); - RunResult Step(Trap::Ptr* out_trap); - - Store& store(); - void Mark(); - - Instance* GetCallerInstance(); - - private: - friend Store; - friend DefinedFunc; - - struct TraceSource; - - RunResult PushCall(Ref func, u32 offset, Trap::Ptr* out_trap); - RunResult PushCall(const DefinedFunc&, Trap::Ptr* out_trap); - RunResult PushCall(const HostFunc&, Trap::Ptr* out_trap); - RunResult PopCall(); - RunResult DoCall(const Func::Ptr&, Trap::Ptr* out_trap); - RunResult DoReturnCall(const Func::Ptr&, Trap::Ptr* out_trap); - - void PushValues(const ValueTypes&, const Values&); - void PopValues(const ValueTypes&, Values*); - - Value& Pick(Index); - - template <typename T> - T WABT_VECTORCALL Pop(); - Value Pop(); - u64 PopPtr(const Memory::Ptr& memory); - - template <typename T> - void WABT_VECTORCALL Push(T); - void Push(Value); - void Push(Ref); - - template <typename R, typename T> - using UnopFunc = R WABT_VECTORCALL(T); - template <typename R, typename T> - using UnopTrapFunc = RunResult WABT_VECTORCALL(T, R*, std::string*); - template <typename R, typename T> - using BinopFunc = R WABT_VECTORCALL(T, T); - template <typename R, typename T> - using BinopTrapFunc = RunResult WABT_VECTORCALL(T, T, R*, std::string*); - - template <typename R, typename T> - RunResult DoUnop(UnopFunc<R, T>); - template <typename R, typename T> - RunResult DoUnop(UnopTrapFunc<R, T>, Trap::Ptr* out_trap); - template <typename R, typename T> - RunResult DoBinop(BinopFunc<R, T>); - template <typename R, typename T> - RunResult DoBinop(BinopTrapFunc<R, T>, Trap::Ptr* out_trap); - - template <typename R, typename T> - RunResult DoConvert(Trap::Ptr* out_trap); - template <typename R, typename T> - RunResult DoReinterpret(); - - template <typename T> - RunResult Load(Instr, T* out, Trap::Ptr* out_trap); - template <typename T, typename V = T> - RunResult DoLoad(Instr, Trap::Ptr* out_trap); - template <typename T, typename V = T> - RunResult DoStore(Instr, Trap::Ptr* out_trap); - - RunResult DoMemoryInit(Instr, Trap::Ptr* out_trap); - RunResult DoDataDrop(Instr); - RunResult DoMemoryCopy(Instr, Trap::Ptr* out_trap); - RunResult DoMemoryFill(Instr, Trap::Ptr* out_trap); - - RunResult DoTableInit(Instr, Trap::Ptr* out_trap); - RunResult DoElemDrop(Instr); - RunResult DoTableCopy(Instr, Trap::Ptr* out_trap); - RunResult DoTableGet(Instr, Trap::Ptr* out_trap); - RunResult DoTableSet(Instr, Trap::Ptr* out_trap); - RunResult DoTableGrow(Instr, Trap::Ptr* out_trap); - RunResult DoTableSize(Instr); - RunResult DoTableFill(Instr, Trap::Ptr* out_trap); - - template <typename R, typename T> - RunResult DoSimdSplat(); - template <typename R, typename T> - RunResult DoSimdExtract(Instr); - template <typename R, typename T> - RunResult DoSimdReplace(Instr); - - template <typename R, typename T> - RunResult DoSimdUnop(UnopFunc<R, T>); - // Like DoSimdUnop but zeroes top half. - template <typename R, typename T> - RunResult DoSimdUnopZero(UnopFunc<R, T>); - template <typename R, typename T> - RunResult DoSimdBinop(BinopFunc<R, T>); - RunResult DoSimdBitSelect(); - template <typename S, u8 count> - RunResult DoSimdIsTrue(); - template <typename S> - RunResult DoSimdBitmask(); - template <typename R, typename T> - RunResult DoSimdShift(BinopFunc<R, T>); - template <typename S> - RunResult DoSimdLoadSplat(Instr, Trap::Ptr* out_trap); - template <typename S> - RunResult DoSimdLoadLane(Instr, Trap::Ptr* out_trap); - template <typename S> - RunResult DoSimdStoreLane(Instr, Trap::Ptr* out_trap); - template <typename S, typename T> - RunResult DoSimdLoadZero(Instr, Trap::Ptr* out_trap); - RunResult DoSimdSwizzle(); - RunResult DoSimdShuffle(Instr); - template <typename S, typename T> - RunResult DoSimdNarrow(); - template <typename S, typename T, bool low> - RunResult DoSimdConvert(); - template <typename S, typename T> - RunResult DoSimdDot(); - template <typename S, typename T> - RunResult DoSimdLoadExtend(Instr, Trap::Ptr* out_trap); - template <typename S, typename T> - RunResult DoSimdExtaddPairwise(); - template <typename S, typename T, bool low> - RunResult DoSimdExtmul(); - - template <typename T, typename V = T> - RunResult DoAtomicLoad(Instr, Trap::Ptr* out_trap); - template <typename T, typename V = T> - RunResult DoAtomicStore(Instr, Trap::Ptr* out_trap); - template <typename R, typename T> - RunResult DoAtomicRmw(BinopFunc<T, T>, Instr, Trap::Ptr* out_trap); - template <typename T, typename V = T> - RunResult DoAtomicRmwCmpxchg(Instr, Trap::Ptr* out_trap); - - RunResult DoThrow(Exception::Ptr exn_ref); - - RunResult StepInternal(Trap::Ptr* out_trap); - - std::vector<Frame> frames_; - std::vector<Value> values_; - std::vector<u32> refs_; // Index into values_. - - // Exception handling requires tracking a separate stack of caught - // exceptions for catch blocks. - RefVec exceptions_; - - // Cached for convenience. - Store& store_; - Instance* inst_ = nullptr; - Module* mod_ = nullptr; - - // Tracing. - Stream* trace_stream_; - std::unique_ptr<TraceSource> trace_source_; -}; - -struct Thread::TraceSource : Istream::TraceSource { - public: - explicit TraceSource(Thread*); - std::string Header(Istream::Offset) override; - std::string Pick(Index, Instr) override; - - private: - ValueType GetLocalType(Index); - ValueType GetGlobalType(Index); - ValueType GetTableElementType(Index); - - Thread* thread_; -}; - -} // namespace interp -} // namespace wabt - -#include "src/interp/interp-inl.h" - -#endif // WABT_INTERP_H_ diff --git a/src/interp/istream.cc b/src/interp/istream.cc index 7ef27688..bea32105 100644 --- a/src/interp/istream.cc +++ b/src/interp/istream.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/interp/istream.h" +#include "wabt/interp/istream.h" #include <cinttypes> diff --git a/src/interp/istream.h b/src/interp/istream.h deleted file mode 100644 index d671e14b..00000000 --- a/src/interp/istream.h +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2020 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_INTERP_ISTREAM_H_ -#define WABT_INTERP_ISTREAM_H_ - -#include <cstdint> -#include <string> -#include <vector> - -#include "src/common.h" -#include "src/opcode.h" -#include "src/stream.h" - -namespace wabt { -namespace interp { - -using u8 = uint8_t; -using u16 = uint16_t; -using u32 = uint32_t; -using u64 = uint64_t; -using f32 = float; -using f64 = double; - -using Buffer = std::vector<u8>; - -using ValueType = wabt::Type; - -// Group instructions based on their immediates their operands. This way we can -// simplify instruction decoding, disassembling, and tracing. There is an -// example of an instruction that uses this encoding on the right. -enum class InstrKind { - Imm_0_Op_0, // Nop - Imm_0_Op_1, // i32.eqz - Imm_0_Op_2, // i32.add - Imm_0_Op_3, // select - Imm_Jump_Op_0, // br - Imm_Jump_Op_1, // br_if - Imm_Index_Op_0, // global.get - Imm_Index_Op_1, // global.set - Imm_Index_Op_2, // table.set - Imm_Index_Op_3, // memory.fill - Imm_Index_Op_N, // call - Imm_Index_Index_Op_3, // memory.init - Imm_Index_Index_Op_N, // call_indirect - Imm_Index_Offset_Op_1, // i32.load - Imm_Index_Offset_Op_2, // i32.store - Imm_Index_Offset_Op_3, // i32.atomic.rmw.cmpxchg - Imm_Index_Offset_Lane_Op_2, // v128.load8_lane - Imm_I32_Op_0, // i32.const - Imm_I64_Op_0, // i64.const - Imm_F32_Op_0, // f32.const - Imm_F64_Op_0, // f64.const - Imm_I32_I32_Op_0, // drop_keep - Imm_I8_Op_1, // i32x4.extract_lane - Imm_I8_Op_2, // i32x4.replace_lane - Imm_V128_Op_0, // v128.const - Imm_V128_Op_2, // i8x16.shuffle -}; - -struct Instr { - Opcode op; - InstrKind kind; - union { - u8 imm_u8; - u32 imm_u32; - f32 imm_f32; - u64 imm_u64; - f64 imm_f64; - v128 imm_v128; - struct { - u32 fst, snd; - } imm_u32x2; - struct { - u32 fst, snd; - u8 idx; - } imm_u32x2_u8; - }; -}; - -class Istream { - public: - using SerializedOpcode = u32; // TODO: change to u16 - using Offset = u32; - static const Offset kInvalidOffset = ~0; - // Each br_table entry is made up of three instructions: - // - // interp_drop_keep $drop $keep - // interp_catch_drop $catches - // br $label - // - // Each opcode is a SerializedOpcode, and each immediate is a u32. - static const Offset kBrTableEntrySize = - sizeof(SerializedOpcode) * 3 + 4 * sizeof(u32); - - // Emit API. - void Emit(u32); - void Emit(Opcode::Enum); - void Emit(Opcode::Enum, u8); - void Emit(Opcode::Enum, u32); - void Emit(Opcode::Enum, u64); - void Emit(Opcode::Enum, v128); - void Emit(Opcode::Enum, u32, u32); - void Emit(Opcode::Enum, u32, u32, u8); - void EmitDropKeep(u32 drop, u32 keep); - void EmitCatchDrop(u32 drop); - - Offset EmitFixupU32(); - void ResolveFixupU32(Offset); - - Offset end() const; - - // Read API. - Instr Read(Offset*) const; - - // Disassemble/Trace API. - // TODO separate out disassembly/tracing? - struct TraceSource { - virtual ~TraceSource() {} - // Whatever content should go before the instruction on each line, e.g. the - // call stack size, value stack size, and istream offset. - virtual std::string Header(Offset) = 0; - virtual std::string Pick(Index, Instr) = 0; - }; - - struct DisassemblySource : TraceSource { - std::string Header(Offset) override; - std::string Pick(Index, Instr) override; - }; - - void Disassemble(Stream*) const; - Offset Disassemble(Stream*, Offset) const; - void Disassemble(Stream*, Offset from, Offset to) const; - - Offset Trace(Stream*, Offset, TraceSource*) const; - - private: - template <typename T> - void WABT_VECTORCALL EmitAt(Offset, T val); - template <typename T> - void WABT_VECTORCALL EmitInternal(T val); - - template <typename T> - T WABT_VECTORCALL ReadAt(Offset*) const; - - Buffer data_; -}; - -} // namespace interp -} // namespace wabt - -#endif // WABT_INTERP_ISTREAM_H_ diff --git a/src/interp/wasi_api.def b/src/interp/wasi_api.def deleted file mode 100644 index 008e9fd6..00000000 --- a/src/interp/wasi_api.def +++ /dev/null @@ -1,28 +0,0 @@ -WASI_FUNC(proc_exit) -WASI_FUNC(fd_read) -WASI_FUNC(fd_pread) -WASI_FUNC(fd_write) -WASI_FUNC(fd_pwrite) -WASI_FUNC(fd_close) -WASI_FUNC(fd_seek) -WASI_FUNC(fd_prestat_get) -WASI_FUNC(fd_prestat_dir_name) -WASI_FUNC(fd_fdstat_get) -WASI_FUNC(fd_fdstat_set_flags) -WASI_FUNC(fd_filestat_get) -WASI_FUNC(fd_readdir) -WASI_FUNC(environ_sizes_get) -WASI_FUNC(environ_get) -WASI_FUNC(args_sizes_get) -WASI_FUNC(args_get) -WASI_FUNC(path_open) -WASI_FUNC(path_filestat_get) -WASI_FUNC(path_symlink) -WASI_FUNC(path_unlink_file) -WASI_FUNC(path_remove_directory) -WASI_FUNC(path_create_directory) -WASI_FUNC(path_readlink) -WASI_FUNC(path_rename) -WASI_FUNC(clock_time_get) -WASI_FUNC(poll_oneoff) -WASI_FUNC(random_get) diff --git a/src/intrusive-list.h b/src/intrusive-list.h deleted file mode 100644 index 74161561..00000000 --- a/src/intrusive-list.h +++ /dev/null @@ -1,633 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_INTRUSIVE_LIST_H_ -#define WABT_INTRUSIVE_LIST_H_ - -#include <cassert> -#include <iterator> -#include <memory> - -#include "src/make-unique.h" - -// This uses a similar interface as std::list, but is missing the following -// features: -// -// * Add "extract_" functions that remove an element from the list and return -// it. -// * Only supports move-only operations -// * No allocator support -// * No initializer lists -// * Asserts instead of exceptions -// * Some functions are not implemented (merge, remove, remove_if, reverse, -// unique, sort, non-member comparison operators) - -namespace wabt { - -template <typename T> -class intrusive_list; - -template <typename T> -class intrusive_list_base { - private: - friend class intrusive_list<T>; - - mutable T* next_ = nullptr; - mutable T* prev_ = nullptr; -}; - -template <typename T> -class intrusive_list { - public: - // types: - typedef T value_type; - typedef value_type& reference; - typedef const value_type& const_reference; - class iterator; - class const_iterator; - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; - typedef std::reverse_iterator<iterator> reverse_iterator; - typedef std::reverse_iterator<const_iterator> const_reverse_iterator; - - // construct/copy/destroy: - intrusive_list(); - explicit intrusive_list(std::unique_ptr<T> node); - explicit intrusive_list(T&& node); - intrusive_list(const intrusive_list&) = delete; - intrusive_list(intrusive_list&&); - ~intrusive_list(); - intrusive_list& operator=(const intrusive_list& other) = delete; - intrusive_list& operator=(intrusive_list&& other); - - // iterators: - iterator begin() noexcept; - const_iterator begin() const noexcept; - iterator end() noexcept; - const_iterator end() const noexcept; - - reverse_iterator rbegin() noexcept; - const_reverse_iterator rbegin() const noexcept; - reverse_iterator rend() noexcept; - const_reverse_iterator rend() const noexcept; - - const_iterator cbegin() const noexcept; - const_iterator cend() const noexcept; - const_reverse_iterator crbegin() const noexcept; - const_reverse_iterator crend() const noexcept; - - // capacity: - size_type size() const noexcept; - bool empty() const noexcept; - - // element access: - reference front(); - const_reference front() const; - reference back(); - const_reference back() const; - - // modifiers: - template <class... Args> - void emplace_front(Args&&... args); - template <class... Args> - void emplace_back(Args&&... args); - void push_front(std::unique_ptr<T> node); - void push_front(T&& node); - void push_back(std::unique_ptr<T> node); - void push_back(T&& node); - void pop_front(); - void pop_back(); - std::unique_ptr<T> extract_front(); - std::unique_ptr<T> extract_back(); - - template <class... Args> - iterator emplace(iterator pos, Args&&... args); - iterator insert(iterator pos, std::unique_ptr<T> node); - iterator insert(iterator pos, T&& node); - std::unique_ptr<T> extract(iterator it); - - iterator erase(iterator pos); - iterator erase(iterator first, iterator last); - void swap(intrusive_list&); - void clear() noexcept; - - void splice(iterator pos, intrusive_list& node); - void splice(iterator pos, intrusive_list&& node); - void splice(iterator pos, intrusive_list& node, iterator it); - void splice(iterator pos, - intrusive_list& node, - iterator first, - iterator last); - - private: - T* first_ = nullptr; - T* last_ = nullptr; - size_t size_ = 0; -}; - -/// iterator -template <typename T> -class intrusive_list<T>::iterator { - public: - typedef std::ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - typedef T value_type; - typedef T* pointer; - typedef T& reference; - - iterator(const intrusive_list<T>& list, T* node) - : list_(&list), node_(node) {} - - reference operator*() const { - assert(node_); - return *node_; - } - - pointer operator->() const { - assert(node_); - return node_; - } - - iterator& operator++() { - assert(node_); - node_ = node_->next_; - return *this; - } - - iterator operator++(int) { - iterator tmp = *this; - operator++(); - return tmp; - } - - iterator& operator--() { - node_ = node_ ? node_->prev_ : list_->last_; - return *this; - } - - iterator operator--(int) { - iterator tmp = *this; - operator--(); - return tmp; - } - - bool operator==(iterator rhs) const { - assert(list_ == rhs.list_); - return node_ == rhs.node_; - } - - bool operator!=(iterator rhs) const { - assert(list_ == rhs.list_); - return node_ != rhs.node_; - } - - private: - friend class const_iterator; - - const intrusive_list<T>* list_; - T* node_; -}; - -/// const_iterator -template <typename T> -class intrusive_list<T>::const_iterator { - public: - typedef std::ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - typedef T value_type; - typedef const T* pointer; - typedef const T& reference; - - const_iterator(const intrusive_list<T>& list, T* node) - : list_(&list), node_(node) {} - - const_iterator(const iterator& other) - : list_(other.list_), node_(other.node_) {} - - reference operator*() const { - assert(node_); - return *node_; - } - - pointer operator->() const { - assert(node_); - return node_; - } - - const_iterator& operator++() { - assert(node_); - node_ = node_->next_; - return *this; - } - - const_iterator operator++(int) { - const_iterator tmp = *this; - operator++(); - return tmp; - } - - const_iterator& operator--() { - node_ = node_ ? node_->prev_ : list_->last_; - return *this; - } - - const_iterator operator--(int) { - const_iterator tmp = *this; - operator--(); - return tmp; - } - - bool operator==(const_iterator rhs) const { - assert(list_ == rhs.list_); - return node_ == rhs.node_; - } - - bool operator!=(const_iterator rhs) const { - assert(list_ == rhs.list_); - return node_ != rhs.node_; - } - - private: - const intrusive_list<T>* list_; - T* node_; -}; - -template <typename T> -inline intrusive_list<T>::intrusive_list() {} - -template <typename T> -inline intrusive_list<T>::intrusive_list(std::unique_ptr<T> node) { - push_back(std::move(node)); -} - -template <typename T> -inline intrusive_list<T>::intrusive_list(T&& node) { - push_back(std::move(node)); -} - -template <typename T> -inline intrusive_list<T>::intrusive_list(intrusive_list&& other) - : first_(other.first_), last_(other.last_), size_(other.size_) { - other.first_ = other.last_ = nullptr; - other.size_ = 0; -} - -template <typename T> -inline intrusive_list<T>::~intrusive_list() { - clear(); -} - -template <typename T> -inline intrusive_list<T>& intrusive_list<T>::operator=( - intrusive_list<T>&& other) { - clear(); - first_ = other.first_; - last_ = other.last_; - size_ = other.size_; - other.first_ = other.last_ = nullptr; - other.size_ = 0; - return *this; -} - -template <typename T> -inline typename intrusive_list<T>::iterator -intrusive_list<T>::begin() noexcept { - return iterator(*this, first_); -} - -template <typename T> -inline typename intrusive_list<T>::const_iterator intrusive_list<T>::begin() - const noexcept { - return const_iterator(*this, first_); -} - -template <typename T> -inline typename intrusive_list<T>::iterator intrusive_list<T>::end() noexcept { - return iterator(*this, nullptr); -} - -template <typename T> -inline typename intrusive_list<T>::const_iterator intrusive_list<T>::end() - const noexcept { - return const_iterator(*this, nullptr); -} - -template <typename T> -inline typename intrusive_list<T>::reverse_iterator -intrusive_list<T>::rbegin() noexcept { - return reverse_iterator(iterator(*this, nullptr)); -} - -template <typename T> -inline typename intrusive_list<T>::const_reverse_iterator -intrusive_list<T>::rbegin() const noexcept { - return const_reverse_iterator(const_iterator(*this, nullptr)); -} - -template <typename T> -inline typename intrusive_list<T>::reverse_iterator -intrusive_list<T>::rend() noexcept { - return reverse_iterator(iterator(*this, first_)); -} - -template <typename T> -inline typename intrusive_list<T>::const_reverse_iterator -intrusive_list<T>::rend() const noexcept { - return const_reverse_iterator(const_iterator(*this, first_)); -} - -template <typename T> -inline typename intrusive_list<T>::const_iterator intrusive_list<T>::cbegin() - const noexcept { - return const_iterator(*this, first_); -} - -template <typename T> -inline typename intrusive_list<T>::const_iterator intrusive_list<T>::cend() - const noexcept { - return const_iterator(*this, nullptr); -} - -template <typename T> -inline typename intrusive_list<T>::const_reverse_iterator -intrusive_list<T>::crbegin() const noexcept { - return const_reverse_iterator(const_iterator(*this, nullptr)); -} - -template <typename T> -inline typename intrusive_list<T>::const_reverse_iterator -intrusive_list<T>::crend() const noexcept { - return const_reverse_iterator(const_iterator(*this, first_)); -} - -template <typename T> -inline typename intrusive_list<T>::size_type intrusive_list<T>::size() - const noexcept { - return size_; -} - -template <typename T> -inline bool intrusive_list<T>::empty() const noexcept { - return size_ == 0; -} - -template <typename T> -inline typename intrusive_list<T>::reference intrusive_list<T>::front() { - assert(!empty()); - return *first_; -} - -template <typename T> -inline typename intrusive_list<T>::const_reference intrusive_list<T>::front() - const { - assert(!empty()); - return *first_; -} - -template <typename T> -inline typename intrusive_list<T>::reference intrusive_list<T>::back() { - assert(!empty()); - return *last_; -} - -template <typename T> -inline typename intrusive_list<T>::const_reference intrusive_list<T>::back() - const { - assert(!empty()); - return *last_; -} - -template <typename T> -template <class... Args> -inline void intrusive_list<T>::emplace_front(Args&&... args) { - push_front(MakeUnique<T>(std::forward<Args>(args)...)); -} - -template <typename T> -template <class... Args> -inline void intrusive_list<T>::emplace_back(Args&&... args) { - push_back(MakeUnique<T>(std::forward<Args>(args)...)); -} - -template <typename T> -inline void intrusive_list<T>::push_front(std::unique_ptr<T> node) { - assert(node->prev_ == nullptr && node->next_ == nullptr); - - T* node_p = node.release(); - if (first_) { - node_p->next_ = first_; - first_->prev_ = node_p; - } else { - last_ = node_p; - } - first_ = node_p; - size_++; -} - -template <typename T> -inline void intrusive_list<T>::push_front(T&& node) { - push_front(MakeUnique<T>(std::move(node))); -} - -template <typename T> -inline void intrusive_list<T>::push_back(std::unique_ptr<T> node) { - assert(node->prev_ == nullptr && node->next_ == nullptr); - - T* node_p = node.release(); - if (last_) { - node_p->prev_ = last_; - last_->next_ = node_p; - } else { - first_ = node_p; - } - last_ = node_p; - size_++; -} - -template <typename T> -inline void intrusive_list<T>::push_back(T&& node) { - push_back(MakeUnique<T>(std::move(node))); -} - -template <typename T> -inline void intrusive_list<T>::pop_front() { - extract_front(); -} - -template <typename T> -inline void intrusive_list<T>::pop_back() { - extract_back(); -} - -template <typename T> -inline std::unique_ptr<T> intrusive_list<T>::extract_front() { - assert(!empty()); - T* node = first_; - if (first_ == last_) { - first_ = last_ = nullptr; - } else { - first_ = first_->next_; - first_->prev_ = nullptr; - } - node->next_ = node->prev_ = nullptr; - size_--; - return std::unique_ptr<T>(node); -} - -template <typename T> -inline std::unique_ptr<T> intrusive_list<T>::extract_back() { - assert(!empty()); - T* node = last_; - if (first_ == last_) { - first_ = last_ = nullptr; - } else { - last_ = last_->prev_; - last_->next_ = nullptr; - } - node->next_ = node->prev_ = nullptr; - size_--; - return std::unique_ptr<T>(node); -} - -template <typename T> -template <class... Args> -inline typename intrusive_list<T>::iterator intrusive_list<T>::emplace( - iterator pos, - Args&&... args) { - return insert(pos, MakeUnique<T>(std::forward<Args>(args)...)); -} - -template <typename T> -inline typename intrusive_list<T>::iterator intrusive_list<T>::insert( - iterator pos, - std::unique_ptr<T> node) { - assert(node->prev_ == nullptr && node->next_ == nullptr); - - T* node_p; - if (pos == end()) { - push_back(std::move(node)); - node_p = &back(); - } else { - node_p = node.release(); - node_p->prev_ = pos->prev_; - node_p->next_ = &*pos; - if (pos->prev_) { - pos->prev_->next_ = node_p; - } else { - first_ = node_p; - } - pos->prev_ = node_p; - size_++; - } - return iterator(*this, node_p); -} - -template <typename T> -inline typename intrusive_list<T>::iterator intrusive_list<T>::insert( - iterator pos, - T&& node) { - return insert(pos, MakeUnique<T>(std::move(node))); -} - -template <typename T> -inline std::unique_ptr<T> intrusive_list<T>::extract(iterator pos) { - assert(!empty()); - assert(pos != end()); - T* node = &*pos; - if (first_ == last_) { - first_ = last_ = nullptr; - } else { - if (node->prev_) { - node->prev_->next_ = node->next_; - } else { - first_ = node->next_; - } - - if (node->next_) { - node->next_->prev_ = node->prev_; - } else { - last_ = node->prev_; - } - } - node->next_ = node->prev_ = nullptr; - size_--; - return std::unique_ptr<T>(node); -} - -template <typename T> -inline typename intrusive_list<T>::iterator intrusive_list<T>::erase( - iterator pos) { - iterator next = std::next(pos); - extract(pos); - return next; -} - -template <typename T> -inline typename intrusive_list<T>::iterator intrusive_list<T>::erase( - iterator first, - iterator last) { - while (first != last) - first = erase(first); - return first; -} - -template <typename T> -inline void intrusive_list<T>::swap(intrusive_list& other) { - std::swap(first_, other.first_); - std::swap(last_, other.last_); - std::swap(size_, other.size_); -} - -template <typename T> -inline void intrusive_list<T>::clear() noexcept { - for (T* iter = first_; iter;) { - T* next = iter->next_; - delete iter; - iter = next; - } - first_ = last_ = nullptr; - size_ = 0; -} - -template <typename T> -inline void intrusive_list<T>::splice(iterator pos, intrusive_list& other) { - splice(pos, other, other.begin(), other.end()); -} - -template <typename T> -inline void intrusive_list<T>::splice(iterator pos, intrusive_list&& other) { - splice(pos, other, other.begin(), other.end()); -} - -template <typename T> -inline void intrusive_list<T>::splice(iterator pos, - intrusive_list& other, - iterator it) { - insert(pos, other.extract(it)); -} - -template <typename T> -inline void intrusive_list<T>::splice(iterator pos, - intrusive_list& other, - iterator first, - iterator last) { - while (first != last) - insert(pos, other.extract(first++)); -} - -} // namespace wabt - -#endif // WABT_INTRUSIVE_LIST_H_ diff --git a/src/ir-util.cc b/src/ir-util.cc index 099ee8c3..ee9262cc 100644 --- a/src/ir-util.cc +++ b/src/ir-util.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/ir-util.h" +#include "wabt/ir-util.h" #include <algorithm> #include <array> @@ -27,16 +27,16 @@ #include <string> #include <vector> -#include "src/cast.h" -#include "src/common.h" -#include "src/expr-visitor.h" -#include "src/ir-util.h" -#include "src/ir.h" -#include "src/literal.h" -#include "src/stream.h" +#include "wabt/cast.h" +#include "wabt/common.h" +#include "wabt/expr-visitor.h" +#include "wabt/ir-util.h" +#include "wabt/ir.h" +#include "wabt/literal.h" +#include "wabt/stream.h" #define WABT_TRACING 0 -#include "src/tracing.h" +#include "wabt/tracing.h" using namespace wabt; diff --git a/src/ir-util.h b/src/ir-util.h deleted file mode 100644 index db9cf5b4..00000000 --- a/src/ir-util.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_IR_UTIL_H_ -#define WABT_IR_UTIL_H_ - -#include "src/common.h" -#include "src/ir.h" - -namespace wabt { - -struct Label { - Label(LabelType label_type, - const std::string& name, - const TypeVector& param_types, - const TypeVector& result_types) - : name(name), - label_type(label_type), - param_types(param_types), - result_types(result_types) {} - - std::string name; - LabelType label_type; - TypeVector param_types; - TypeVector result_types; -}; - -struct ModuleContext { - ModuleContext(const Module& module) : module(module) {} - - Index GetLabelStackSize() const { return label_stack_.size(); } - const Label* GetLabel(const Var& var) const; - Index GetLabelArity(const Var& var) const; - void SetTopLabelType(LabelType label_type) { - label_stack_.back().label_type = label_type; - } - - Index GetFuncParamCount(const Var& var) const; - Index GetFuncResultCount(const Var& var) const; - - void BeginBlock(LabelType label_type, const Block& block); - void EndBlock(); - void BeginFunc(const Func& func); - void EndFunc(); - - struct Arities { - Index nargs; - Index nreturns; - bool unreachable; - Arities(Index na, Index nr, bool ur = false) - : nargs(na), nreturns(nr), unreachable(ur) {} - }; - Arities GetExprArity(const Expr& expr) const; - - const Module& module; - - private: - const Func* current_func_ = nullptr; - std::vector<Label> label_stack_; -}; - -} // namespace wabt - -#endif /* WABT_IR_UTIL_H_ */ @@ -14,13 +14,13 @@ * limitations under the License. */ -#include "src/ir.h" +#include "wabt/ir.h" #include <cassert> #include <cstddef> #include <numeric> -#include "src/cast.h" +#include "wabt/cast.h" namespace { diff --git a/src/ir.h b/src/ir.h deleted file mode 100644 index 09c57a7f..00000000 --- a/src/ir.h +++ /dev/null @@ -1,1435 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_IR_H_ -#define WABT_IR_H_ - -#include <cassert> -#include <cstddef> -#include <cstdint> -#include <memory> -#include <string> -#include <string_view> -#include <type_traits> -#include <vector> - -#include "src/binding-hash.h" -#include "src/common.h" -#include "src/intrusive-list.h" -#include "src/opcode.h" - -namespace wabt { - -struct Module; - -enum class VarType { - Index, - Name, -}; - -struct Var { - explicit Var(); - explicit Var(Index index, const Location& loc); - explicit Var(std::string_view name, const Location& loc); - Var(Var&&); - Var(const Var&); - Var& operator=(const Var&); - Var& operator=(Var&&); - ~Var(); - - VarType type() const { return type_; } - bool is_index() const { return type_ == VarType::Index; } - bool is_name() const { return type_ == VarType::Name; } - - Index index() const { - assert(is_index()); - return index_; - } - const std::string& name() const { - assert(is_name()); - return name_; - } - - void set_index(Index); - void set_name(std::string&&); - void set_name(std::string_view); - - Location loc; - - private: - void Destroy(); - - VarType type_; - union { - Index index_; - std::string name_; - }; -}; -typedef std::vector<Var> VarVector; - -struct Const { - static constexpr uintptr_t kRefNullBits = ~uintptr_t(0); - - Const() : Const(Type::I32, uint32_t(0)) {} - - static Const I32(uint32_t val = 0, const Location& loc = Location()) { - return Const(Type::I32, val, loc); - } - static Const I64(uint64_t val = 0, const Location& loc = Location()) { - return Const(Type::I64, val, loc); - } - static Const F32(uint32_t val = 0, const Location& loc = Location()) { - return Const(Type::F32, val, loc); - } - static Const F64(uint64_t val = 0, const Location& loc = Location()) { - return Const(Type::F64, val, loc); - } - static Const V128(v128 val, const Location& loc = Location()) { - return Const(Type::V128, val, loc); - } - - Type type() const { return type_; } - Type lane_type() const { - assert(type_ == Type::V128); - return lane_type_; - } - - int lane_count() const { - switch (lane_type()) { - case Type::I8: return 16; - case Type::I16: return 8; - case Type::I32: return 4; - case Type::I64: return 2; - case Type::F32: return 4; - case Type::F64: return 2; - default: WABT_UNREACHABLE; - } - } - - uint32_t u32() const { return data_.u32(0); } - uint64_t u64() const { return data_.u64(0); } - uint32_t f32_bits() const { return data_.f32_bits(0); } - uint64_t f64_bits() const { return data_.f64_bits(0); } - uintptr_t ref_bits() const { return data_.To<uintptr_t>(0); } - v128 vec128() const { return data_; } - - template <typename T> - T v128_lane(int lane) const { - return data_.To<T>(lane); - } - - void set_u32(uint32_t x) { From(Type::I32, x); } - void set_u64(uint64_t x) { From(Type::I64, x); } - void set_f32(uint32_t x) { From(Type::F32, x); } - void set_f64(uint64_t x) { From(Type::F64, x); } - - void set_v128_u8(int lane, uint8_t x) { set_v128_lane(lane, Type::I8, x); } - void set_v128_u16(int lane, uint16_t x) { set_v128_lane(lane, Type::I16, x); } - void set_v128_u32(int lane, uint32_t x) { set_v128_lane(lane, Type::I32, x); } - void set_v128_u64(int lane, uint64_t x) { set_v128_lane(lane, Type::I64, x); } - void set_v128_f32(int lane, uint32_t x) { set_v128_lane(lane, Type::F32, x); } - void set_v128_f64(int lane, uint64_t x) { set_v128_lane(lane, Type::F64, x); } - - // Only used for expectations. (e.g. wast assertions) - void set_f32(ExpectedNan nan) { - set_f32(0); - set_expected_nan(0, nan); - } - void set_f64(ExpectedNan nan) { - set_f64(0); - set_expected_nan(0, nan); - } - void set_funcref() { From<uintptr_t>(Type::FuncRef, 0); } - void set_externref(uintptr_t x) { From(Type::ExternRef, x); } - void set_null(Type type) { From<uintptr_t>(type, kRefNullBits); } - - bool is_expected_nan(int lane = 0) const { - return expected_nan(lane) != ExpectedNan::None; - } - - ExpectedNan expected_nan(int lane = 0) const { - return lane < 4 ? nan_[lane] : ExpectedNan::None; - } - - void set_expected_nan(int lane, ExpectedNan nan) { - if (lane < 4) { - nan_[lane] = nan; - } - } - - // v128 support - Location loc; - - private: - template <typename T> - void set_v128_lane(int lane, Type lane_type, T x) { - lane_type_ = lane_type; - From(Type::V128, x, lane); - set_expected_nan(lane, ExpectedNan::None); - } - - template <typename T> - Const(Type type, T data, const Location& loc = Location()) : loc(loc) { - From<T>(type, data); - } - - template <typename T> - void From(Type type, T data, int lane = 0) { - static_assert(sizeof(T) <= sizeof(data_), "Invalid cast!"); - assert((lane + 1) * sizeof(T) <= sizeof(data_)); - type_ = type; - data_.From<T>(lane, data); - set_expected_nan(lane, ExpectedNan::None); - } - - Type type_; - Type lane_type_; // Only valid if type_ == Type::V128. - v128 data_; - ExpectedNan nan_[4]; -}; -typedef std::vector<Const> ConstVector; - -struct FuncSignature { - TypeVector param_types; - TypeVector result_types; - - // Some types can have names, for example (ref $foo) has type $foo. - // So to use this type we need to translate its name into - // a proper index from the module type section. - // This is the mapping from parameter/result index to its name. - std::unordered_map<uint32_t, std::string> param_type_names; - std::unordered_map<uint32_t, std::string> result_type_names; - - Index GetNumParams() const { return param_types.size(); } - Index GetNumResults() const { return result_types.size(); } - Type GetParamType(Index index) const { return param_types[index]; } - Type GetResultType(Index index) const { return result_types[index]; } - - bool operator==(const FuncSignature&) const; -}; - -enum class TypeEntryKind { - Func, - Struct, - Array, -}; - -class TypeEntry { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(TypeEntry); - - virtual ~TypeEntry() = default; - - TypeEntryKind kind() const { return kind_; } - - Location loc; - std::string name; - - protected: - explicit TypeEntry(TypeEntryKind kind, - std::string_view name = std::string_view(), - const Location& loc = Location()) - : loc(loc), name(name), kind_(kind) {} - - TypeEntryKind kind_; -}; - -class FuncType : public TypeEntry { - public: - static bool classof(const TypeEntry* entry) { - return entry->kind() == TypeEntryKind::Func; - } - - explicit FuncType(std::string_view name = std::string_view()) - : TypeEntry(TypeEntryKind::Func, name) {} - - Index GetNumParams() const { return sig.GetNumParams(); } - Index GetNumResults() const { return sig.GetNumResults(); } - Type GetParamType(Index index) const { return sig.GetParamType(index); } - Type GetResultType(Index index) const { return sig.GetResultType(index); } - - FuncSignature sig; -}; - -struct Field { - std::string name; - Type type = Type::Void; - bool mutable_ = false; -}; - -class StructType : public TypeEntry { - public: - static bool classof(const TypeEntry* entry) { - return entry->kind() == TypeEntryKind::Struct; - } - - explicit StructType(std::string_view name = std::string_view()) - : TypeEntry(TypeEntryKind::Struct) {} - - std::vector<Field> fields; -}; - -class ArrayType : public TypeEntry { - public: - static bool classof(const TypeEntry* entry) { - return entry->kind() == TypeEntryKind::Array; - } - - explicit ArrayType(std::string_view name = std::string_view()) - : TypeEntry(TypeEntryKind::Array) {} - - Field field; -}; - -struct FuncDeclaration { - Index GetNumParams() const { return sig.GetNumParams(); } - Index GetNumResults() const { return sig.GetNumResults(); } - Type GetParamType(Index index) const { return sig.GetParamType(index); } - Type GetResultType(Index index) const { return sig.GetResultType(index); } - - bool has_func_type = false; - Var type_var; - FuncSignature sig; -}; - -enum class ExprType { - AtomicLoad, - AtomicRmw, - AtomicRmwCmpxchg, - AtomicStore, - AtomicNotify, - AtomicFence, - AtomicWait, - Binary, - Block, - Br, - BrIf, - BrTable, - Call, - CallIndirect, - CallRef, - CodeMetadata, - Compare, - Const, - Convert, - Drop, - GlobalGet, - GlobalSet, - If, - Load, - LocalGet, - LocalSet, - LocalTee, - Loop, - MemoryCopy, - DataDrop, - MemoryFill, - MemoryGrow, - MemoryInit, - MemorySize, - Nop, - RefIsNull, - RefFunc, - RefNull, - Rethrow, - Return, - ReturnCall, - ReturnCallIndirect, - Select, - SimdLaneOp, - SimdLoadLane, - SimdStoreLane, - SimdShuffleOp, - LoadSplat, - LoadZero, - Store, - TableCopy, - ElemDrop, - TableInit, - TableGet, - TableGrow, - TableSize, - TableSet, - TableFill, - Ternary, - Throw, - Try, - Unary, - Unreachable, - - First = AtomicLoad, - Last = Unreachable -}; - -const char* GetExprTypeName(ExprType type); - -class Expr; -typedef intrusive_list<Expr> ExprList; - -typedef FuncDeclaration BlockDeclaration; - -struct Block { - Block() = default; - explicit Block(ExprList exprs) : exprs(std::move(exprs)) {} - - std::string label; - BlockDeclaration decl; - ExprList exprs; - Location end_loc; -}; - -struct Catch { - explicit Catch(const Location& loc = Location()) : loc(loc) {} - explicit Catch(const Var& var, const Location& loc = Location()) - : loc(loc), var(var) {} - Location loc; - Var var; - ExprList exprs; - bool IsCatchAll() const { - return var.is_index() && var.index() == kInvalidIndex; - } -}; -typedef std::vector<Catch> CatchVector; - -enum class TryKind { Plain, Catch, Delegate }; - -class Expr : public intrusive_list_base<Expr> { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(Expr); - Expr() = delete; - virtual ~Expr() = default; - - ExprType type() const { return type_; } - - Location loc; - - protected: - explicit Expr(ExprType type, const Location& loc = Location()) - : loc(loc), type_(type) {} - - ExprType type_; -}; - -const char* GetExprTypeName(const Expr& expr); - -template <ExprType TypeEnum> -class ExprMixin : public Expr { - public: - static bool classof(const Expr* expr) { return expr->type() == TypeEnum; } - - explicit ExprMixin(const Location& loc = Location()) : Expr(TypeEnum, loc) {} -}; - -template <ExprType TypeEnum> -class MemoryExpr : public ExprMixin<TypeEnum> { - public: - MemoryExpr(Var memidx, const Location& loc = Location()) - : ExprMixin<TypeEnum>(loc), memidx(memidx) {} - - Var memidx; -}; - -template <ExprType TypeEnum> -class MemoryBinaryExpr : public ExprMixin<TypeEnum> { - public: - MemoryBinaryExpr(Var srcmemidx, - Var destmemidx, - const Location& loc = Location()) - : ExprMixin<TypeEnum>(loc), - srcmemidx(srcmemidx), - destmemidx(destmemidx) {} - - Var srcmemidx; - Var destmemidx; -}; - -typedef ExprMixin<ExprType::Drop> DropExpr; -typedef ExprMixin<ExprType::Nop> NopExpr; -typedef ExprMixin<ExprType::Return> ReturnExpr; -typedef ExprMixin<ExprType::Unreachable> UnreachableExpr; - -typedef MemoryExpr<ExprType::MemoryGrow> MemoryGrowExpr; -typedef MemoryExpr<ExprType::MemorySize> MemorySizeExpr; -typedef MemoryExpr<ExprType::MemoryFill> MemoryFillExpr; - -typedef MemoryBinaryExpr<ExprType::MemoryCopy> MemoryCopyExpr; - -template <ExprType TypeEnum> -class RefTypeExpr : public ExprMixin<TypeEnum> { - public: - RefTypeExpr(Type type, const Location& loc = Location()) - : ExprMixin<TypeEnum>(loc), type(type) {} - - Type type; -}; - -typedef RefTypeExpr<ExprType::RefNull> RefNullExpr; -typedef ExprMixin<ExprType::RefIsNull> RefIsNullExpr; - -template <ExprType TypeEnum> -class OpcodeExpr : public ExprMixin<TypeEnum> { - public: - OpcodeExpr(Opcode opcode, const Location& loc = Location()) - : ExprMixin<TypeEnum>(loc), opcode(opcode) {} - - Opcode opcode; -}; - -typedef OpcodeExpr<ExprType::Binary> BinaryExpr; -typedef OpcodeExpr<ExprType::Compare> CompareExpr; -typedef OpcodeExpr<ExprType::Convert> ConvertExpr; -typedef OpcodeExpr<ExprType::Unary> UnaryExpr; -typedef OpcodeExpr<ExprType::Ternary> TernaryExpr; - -class SimdLaneOpExpr : public ExprMixin<ExprType::SimdLaneOp> { - public: - SimdLaneOpExpr(Opcode opcode, uint64_t val, const Location& loc = Location()) - : ExprMixin<ExprType::SimdLaneOp>(loc), opcode(opcode), val(val) {} - - Opcode opcode; - uint64_t val; -}; - -class SimdLoadLaneExpr : public MemoryExpr<ExprType::SimdLoadLane> { - public: - SimdLoadLaneExpr(Opcode opcode, - Var memidx, - Address align, - Address offset, - uint64_t val, - const Location& loc = Location()) - : MemoryExpr<ExprType::SimdLoadLane>(memidx, loc), - opcode(opcode), - align(align), - offset(offset), - val(val) {} - - Opcode opcode; - Address align; - Address offset; - uint64_t val; -}; - -class SimdStoreLaneExpr : public MemoryExpr<ExprType::SimdStoreLane> { - public: - SimdStoreLaneExpr(Opcode opcode, - Var memidx, - Address align, - Address offset, - uint64_t val, - const Location& loc = Location()) - : MemoryExpr<ExprType::SimdStoreLane>(memidx, loc), - opcode(opcode), - align(align), - offset(offset), - val(val) {} - - Opcode opcode; - Address align; - Address offset; - uint64_t val; -}; - -class SimdShuffleOpExpr : public ExprMixin<ExprType::SimdShuffleOp> { - public: - SimdShuffleOpExpr(Opcode opcode, v128 val, const Location& loc = Location()) - : ExprMixin<ExprType::SimdShuffleOp>(loc), opcode(opcode), val(val) {} - - Opcode opcode; - v128 val; -}; - -template <ExprType TypeEnum> -class VarExpr : public ExprMixin<TypeEnum> { - public: - VarExpr(const Var& var, const Location& loc = Location()) - : ExprMixin<TypeEnum>(loc), var(var) {} - - Var var; -}; - -template <ExprType TypeEnum> -class MemoryVarExpr : public MemoryExpr<TypeEnum> { - public: - MemoryVarExpr(const Var& var, Var memidx, const Location& loc = Location()) - : MemoryExpr<TypeEnum>(memidx, loc), var(var) {} - - Var var; -}; - -typedef VarExpr<ExprType::Br> BrExpr; -typedef VarExpr<ExprType::BrIf> BrIfExpr; -typedef VarExpr<ExprType::Call> CallExpr; -typedef VarExpr<ExprType::RefFunc> RefFuncExpr; -typedef VarExpr<ExprType::GlobalGet> GlobalGetExpr; -typedef VarExpr<ExprType::GlobalSet> GlobalSetExpr; -typedef VarExpr<ExprType::LocalGet> LocalGetExpr; -typedef VarExpr<ExprType::LocalSet> LocalSetExpr; -typedef VarExpr<ExprType::LocalTee> LocalTeeExpr; -typedef VarExpr<ExprType::ReturnCall> ReturnCallExpr; -typedef VarExpr<ExprType::Throw> ThrowExpr; -typedef VarExpr<ExprType::Rethrow> RethrowExpr; - -typedef VarExpr<ExprType::DataDrop> DataDropExpr; -typedef VarExpr<ExprType::ElemDrop> ElemDropExpr; -typedef VarExpr<ExprType::TableGet> TableGetExpr; -typedef VarExpr<ExprType::TableSet> TableSetExpr; -typedef VarExpr<ExprType::TableGrow> TableGrowExpr; -typedef VarExpr<ExprType::TableSize> TableSizeExpr; -typedef VarExpr<ExprType::TableFill> TableFillExpr; - -typedef MemoryVarExpr<ExprType::MemoryInit> MemoryInitExpr; - -class SelectExpr : public ExprMixin<ExprType::Select> { - public: - SelectExpr(TypeVector type, const Location& loc = Location()) - : ExprMixin<ExprType::Select>(loc), result_type(type) {} - TypeVector result_type; -}; - -class TableInitExpr : public ExprMixin<ExprType::TableInit> { - public: - TableInitExpr(const Var& segment_index, - const Var& table_index, - const Location& loc = Location()) - : ExprMixin<ExprType::TableInit>(loc), - segment_index(segment_index), - table_index(table_index) {} - - Var segment_index; - Var table_index; -}; - -class TableCopyExpr : public ExprMixin<ExprType::TableCopy> { - public: - TableCopyExpr(const Var& dst, - const Var& src, - const Location& loc = Location()) - : ExprMixin<ExprType::TableCopy>(loc), dst_table(dst), src_table(src) {} - - Var dst_table; - Var src_table; -}; - -class CallIndirectExpr : public ExprMixin<ExprType::CallIndirect> { - public: - explicit CallIndirectExpr(const Location& loc = Location()) - : ExprMixin<ExprType::CallIndirect>(loc) {} - - FuncDeclaration decl; - Var table; -}; - -class CodeMetadataExpr : public ExprMixin<ExprType::CodeMetadata> { - public: - explicit CodeMetadataExpr(std::string_view name, - std::vector<uint8_t> data, - const Location& loc = Location()) - : ExprMixin<ExprType::CodeMetadata>(loc), - name(std::move(name)), - data(std::move(data)) {} - - std::string_view name; - std::vector<uint8_t> data; -}; - -class ReturnCallIndirectExpr : public ExprMixin<ExprType::ReturnCallIndirect> { - public: - explicit ReturnCallIndirectExpr(const Location& loc = Location()) - : ExprMixin<ExprType::ReturnCallIndirect>(loc) {} - - FuncDeclaration decl; - Var table; -}; - -class CallRefExpr : public ExprMixin<ExprType::CallRef> { - public: - explicit CallRefExpr(const Location& loc = Location()) - : ExprMixin<ExprType::CallRef>(loc) {} - - // This field is setup only during Validate phase, - // so keep that in mind when you use it. - Var function_type_index; -}; - -template <ExprType TypeEnum> -class BlockExprBase : public ExprMixin<TypeEnum> { - public: - explicit BlockExprBase(const Location& loc = Location()) - : ExprMixin<TypeEnum>(loc) {} - - Block block; -}; - -typedef BlockExprBase<ExprType::Block> BlockExpr; -typedef BlockExprBase<ExprType::Loop> LoopExpr; - -class IfExpr : public ExprMixin<ExprType::If> { - public: - explicit IfExpr(const Location& loc = Location()) - : ExprMixin<ExprType::If>(loc) {} - - Block true_; - ExprList false_; - Location false_end_loc; -}; - -class TryExpr : public ExprMixin<ExprType::Try> { - public: - explicit TryExpr(const Location& loc = Location()) - : ExprMixin<ExprType::Try>(loc), kind(TryKind::Plain) {} - - TryKind kind; - Block block; - CatchVector catches; - Var delegate_target; -}; - -class BrTableExpr : public ExprMixin<ExprType::BrTable> { - public: - BrTableExpr(const Location& loc = Location()) - : ExprMixin<ExprType::BrTable>(loc) {} - - VarVector targets; - Var default_target; -}; - -class ConstExpr : public ExprMixin<ExprType::Const> { - public: - ConstExpr(const Const& c, const Location& loc = Location()) - : ExprMixin<ExprType::Const>(loc), const_(c) {} - - Const const_; -}; - -// TODO(binji): Rename this, it is used for more than loads/stores now. -template <ExprType TypeEnum> -class LoadStoreExpr : public MemoryExpr<TypeEnum> { - public: - LoadStoreExpr(Opcode opcode, - Var memidx, - Address align, - Address offset, - const Location& loc = Location()) - : MemoryExpr<TypeEnum>(memidx, loc), - opcode(opcode), - align(align), - offset(offset) {} - - Opcode opcode; - Address align; - Address offset; -}; - -typedef LoadStoreExpr<ExprType::Load> LoadExpr; -typedef LoadStoreExpr<ExprType::Store> StoreExpr; - -typedef LoadStoreExpr<ExprType::AtomicLoad> AtomicLoadExpr; -typedef LoadStoreExpr<ExprType::AtomicStore> AtomicStoreExpr; -typedef LoadStoreExpr<ExprType::AtomicRmw> AtomicRmwExpr; -typedef LoadStoreExpr<ExprType::AtomicRmwCmpxchg> AtomicRmwCmpxchgExpr; -typedef LoadStoreExpr<ExprType::AtomicWait> AtomicWaitExpr; -typedef LoadStoreExpr<ExprType::AtomicNotify> AtomicNotifyExpr; -typedef LoadStoreExpr<ExprType::LoadSplat> LoadSplatExpr; -typedef LoadStoreExpr<ExprType::LoadZero> LoadZeroExpr; - -class AtomicFenceExpr : public ExprMixin<ExprType::AtomicFence> { - public: - explicit AtomicFenceExpr(uint32_t consistency_model, - const Location& loc = Location()) - : ExprMixin<ExprType::AtomicFence>(loc), - consistency_model(consistency_model) {} - - uint32_t consistency_model; -}; - -struct Tag { - explicit Tag(std::string_view name) : name(name) {} - - std::string name; - FuncDeclaration decl; -}; - -class LocalTypes { - public: - typedef std::pair<Type, Index> Decl; - typedef std::vector<Decl> Decls; - - struct const_iterator { - const_iterator(Decls::const_iterator decl, Index index) - : decl(decl), index(index) {} - Type operator*() const { return decl->first; } - const_iterator& operator++(); - const_iterator operator++(int); - - Decls::const_iterator decl; - Index index; - }; - - void Set(const TypeVector&); - - const Decls& decls() const { return decls_; } - - void AppendDecl(Type type, Index count) { - if (count != 0) { - decls_.emplace_back(type, count); - } - } - - Index size() const; - Type operator[](Index) const; - - const_iterator begin() const { return {decls_.begin(), 0}; } - const_iterator end() const { return {decls_.end(), 0}; } - - private: - Decls decls_; -}; - -inline LocalTypes::const_iterator& LocalTypes::const_iterator::operator++() { - ++index; - if (index >= decl->second) { - ++decl; - index = 0; - } - return *this; -} - -inline LocalTypes::const_iterator LocalTypes::const_iterator::operator++(int) { - const_iterator result = *this; - operator++(); - return result; -} - -inline bool operator==(const LocalTypes::const_iterator& lhs, - const LocalTypes::const_iterator& rhs) { - return lhs.decl == rhs.decl && lhs.index == rhs.index; -} - -inline bool operator!=(const LocalTypes::const_iterator& lhs, - const LocalTypes::const_iterator& rhs) { - return !operator==(lhs, rhs); -} - -struct Func { - explicit Func(std::string_view name) : name(name) {} - - Type GetParamType(Index index) const { return decl.GetParamType(index); } - Type GetResultType(Index index) const { return decl.GetResultType(index); } - Type GetLocalType(Index index) const; - Type GetLocalType(const Var& var) const; - Index GetNumParams() const { return decl.GetNumParams(); } - Index GetNumLocals() const { return local_types.size(); } - Index GetNumParamsAndLocals() const { - return GetNumParams() + GetNumLocals(); - } - Index GetNumResults() const { return decl.GetNumResults(); } - Index GetLocalIndex(const Var&) const; - - std::string name; - FuncDeclaration decl; - LocalTypes local_types; - BindingHash bindings; - ExprList exprs; - Location loc; -}; - -struct Global { - explicit Global(std::string_view name) : name(name) {} - - std::string name; - Type type = Type::Void; - bool mutable_ = false; - ExprList init_expr; -}; - -struct Table { - explicit Table(std::string_view name) - : name(name), elem_type(Type::FuncRef) {} - - std::string name; - Limits elem_limits; - Type elem_type; -}; - -typedef std::vector<ExprList> ExprListVector; - -struct ElemSegment { - explicit ElemSegment(std::string_view name) : name(name) {} - uint8_t GetFlags(const Module*) const; - - SegmentKind kind = SegmentKind::Active; - std::string name; - Var table_var; - Type elem_type; - ExprList offset; - ExprListVector elem_exprs; -}; - -struct Memory { - explicit Memory(std::string_view name) : name(name) {} - - std::string name; - Limits page_limits; -}; - -struct DataSegment { - explicit DataSegment(std::string_view name) : name(name) {} - uint8_t GetFlags(const Module*) const; - - SegmentKind kind = SegmentKind::Active; - std::string name; - Var memory_var; - ExprList offset; - std::vector<uint8_t> data; -}; - -class Import { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(Import); - Import() = delete; - virtual ~Import() = default; - - ExternalKind kind() const { return kind_; } - - std::string module_name; - std::string field_name; - - protected: - Import(ExternalKind kind) : kind_(kind) {} - - ExternalKind kind_; -}; - -template <ExternalKind TypeEnum> -class ImportMixin : public Import { - public: - static bool classof(const Import* import) { - return import->kind() == TypeEnum; - } - - ImportMixin() : Import(TypeEnum) {} -}; - -class FuncImport : public ImportMixin<ExternalKind::Func> { - public: - explicit FuncImport(std::string_view name = std::string_view()) - : ImportMixin<ExternalKind::Func>(), func(name) {} - - Func func; -}; - -class TableImport : public ImportMixin<ExternalKind::Table> { - public: - explicit TableImport(std::string_view name = std::string_view()) - : ImportMixin<ExternalKind::Table>(), table(name) {} - - Table table; -}; - -class MemoryImport : public ImportMixin<ExternalKind::Memory> { - public: - explicit MemoryImport(std::string_view name = std::string_view()) - : ImportMixin<ExternalKind::Memory>(), memory(name) {} - - Memory memory; -}; - -class GlobalImport : public ImportMixin<ExternalKind::Global> { - public: - explicit GlobalImport(std::string_view name = std::string_view()) - : ImportMixin<ExternalKind::Global>(), global(name) {} - - Global global; -}; - -class TagImport : public ImportMixin<ExternalKind::Tag> { - public: - explicit TagImport(std::string_view name = std::string_view()) - : ImportMixin<ExternalKind::Tag>(), tag(name) {} - - Tag tag; -}; - -struct Export { - std::string name; - ExternalKind kind; - Var var; -}; - -enum class ModuleFieldType { - Func, - Global, - Import, - Export, - Type, - Table, - ElemSegment, - Memory, - DataSegment, - Start, - Tag -}; - -class ModuleField : public intrusive_list_base<ModuleField> { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(ModuleField); - ModuleField() = delete; - virtual ~ModuleField() = default; - - ModuleFieldType type() const { return type_; } - - Location loc; - - protected: - ModuleField(ModuleFieldType type, const Location& loc) - : loc(loc), type_(type) {} - - ModuleFieldType type_; -}; - -typedef intrusive_list<ModuleField> ModuleFieldList; - -template <ModuleFieldType TypeEnum> -class ModuleFieldMixin : public ModuleField { - public: - static bool classof(const ModuleField* field) { - return field->type() == TypeEnum; - } - - explicit ModuleFieldMixin(const Location& loc) : ModuleField(TypeEnum, loc) {} -}; - -class FuncModuleField : public ModuleFieldMixin<ModuleFieldType::Func> { - public: - explicit FuncModuleField(const Location& loc = Location(), - std::string_view name = std::string_view()) - : ModuleFieldMixin<ModuleFieldType::Func>(loc), func(name) {} - - Func func; -}; - -class GlobalModuleField : public ModuleFieldMixin<ModuleFieldType::Global> { - public: - explicit GlobalModuleField(const Location& loc = Location(), - std::string_view name = std::string_view()) - : ModuleFieldMixin<ModuleFieldType::Global>(loc), global(name) {} - - Global global; -}; - -class ImportModuleField : public ModuleFieldMixin<ModuleFieldType::Import> { - public: - explicit ImportModuleField(const Location& loc = Location()) - : ModuleFieldMixin<ModuleFieldType::Import>(loc) {} - explicit ImportModuleField(std::unique_ptr<Import> import, - const Location& loc = Location()) - : ModuleFieldMixin<ModuleFieldType::Import>(loc), - import(std::move(import)) {} - - std::unique_ptr<Import> import; -}; - -class ExportModuleField : public ModuleFieldMixin<ModuleFieldType::Export> { - public: - explicit ExportModuleField(const Location& loc = Location()) - : ModuleFieldMixin<ModuleFieldType::Export>(loc) {} - - Export export_; -}; - -class TypeModuleField : public ModuleFieldMixin<ModuleFieldType::Type> { - public: - explicit TypeModuleField(const Location& loc = Location()) - : ModuleFieldMixin<ModuleFieldType::Type>(loc) {} - - std::unique_ptr<TypeEntry> type; -}; - -class TableModuleField : public ModuleFieldMixin<ModuleFieldType::Table> { - public: - explicit TableModuleField(const Location& loc = Location(), - std::string_view name = std::string_view()) - : ModuleFieldMixin<ModuleFieldType::Table>(loc), table(name) {} - - Table table; -}; - -class ElemSegmentModuleField - : public ModuleFieldMixin<ModuleFieldType::ElemSegment> { - public: - explicit ElemSegmentModuleField(const Location& loc = Location(), - std::string_view name = std::string_view()) - : ModuleFieldMixin<ModuleFieldType::ElemSegment>(loc), - elem_segment(name) {} - - ElemSegment elem_segment; -}; - -class MemoryModuleField : public ModuleFieldMixin<ModuleFieldType::Memory> { - public: - explicit MemoryModuleField(const Location& loc = Location(), - std::string_view name = std::string_view()) - : ModuleFieldMixin<ModuleFieldType::Memory>(loc), memory(name) {} - - Memory memory; -}; - -class DataSegmentModuleField - : public ModuleFieldMixin<ModuleFieldType::DataSegment> { - public: - explicit DataSegmentModuleField(const Location& loc = Location(), - std::string_view name = std::string_view()) - : ModuleFieldMixin<ModuleFieldType::DataSegment>(loc), - data_segment(name) {} - - DataSegment data_segment; -}; - -class TagModuleField : public ModuleFieldMixin<ModuleFieldType::Tag> { - public: - explicit TagModuleField(const Location& loc = Location(), - std::string_view name = std::string_view()) - : ModuleFieldMixin<ModuleFieldType::Tag>(loc), tag(name) {} - - Tag tag; -}; - -class StartModuleField : public ModuleFieldMixin<ModuleFieldType::Start> { - public: - explicit StartModuleField(Var start = Var(), const Location& loc = Location()) - : ModuleFieldMixin<ModuleFieldType::Start>(loc), start(start) {} - - Var start; -}; - -struct Module { - Index GetFuncTypeIndex(const Var&) const; - Index GetFuncTypeIndex(const FuncDeclaration&) const; - Index GetFuncTypeIndex(const FuncSignature&) const; - const FuncType* GetFuncType(const Var&) const; - FuncType* GetFuncType(const Var&); - Index GetFuncIndex(const Var&) const; - const Func* GetFunc(const Var&) const; - Func* GetFunc(const Var&); - Index GetTableIndex(const Var&) const; - const Table* GetTable(const Var&) const; - Table* GetTable(const Var&); - Index GetMemoryIndex(const Var&) const; - const Memory* GetMemory(const Var&) const; - Memory* GetMemory(const Var&); - Index GetGlobalIndex(const Var&) const; - const Global* GetGlobal(const Var&) const; - Global* GetGlobal(const Var&); - const Export* GetExport(std::string_view) const; - Tag* GetTag(const Var&) const; - Index GetTagIndex(const Var&) const; - const DataSegment* GetDataSegment(const Var&) const; - DataSegment* GetDataSegment(const Var&); - Index GetDataSegmentIndex(const Var&) const; - const ElemSegment* GetElemSegment(const Var&) const; - ElemSegment* GetElemSegment(const Var&); - Index GetElemSegmentIndex(const Var&) const; - - bool IsImport(ExternalKind kind, const Var&) const; - bool IsImport(const Export& export_) const { - return IsImport(export_.kind, export_.var); - } - - // TODO(binji): move this into a builder class? - void AppendField(std::unique_ptr<DataSegmentModuleField>); - void AppendField(std::unique_ptr<ElemSegmentModuleField>); - void AppendField(std::unique_ptr<TagModuleField>); - void AppendField(std::unique_ptr<ExportModuleField>); - void AppendField(std::unique_ptr<FuncModuleField>); - void AppendField(std::unique_ptr<TypeModuleField>); - void AppendField(std::unique_ptr<GlobalModuleField>); - void AppendField(std::unique_ptr<ImportModuleField>); - void AppendField(std::unique_ptr<MemoryModuleField>); - void AppendField(std::unique_ptr<StartModuleField>); - void AppendField(std::unique_ptr<TableModuleField>); - void AppendField(std::unique_ptr<ModuleField>); - void AppendFields(ModuleFieldList*); - - Location loc; - std::string name; - ModuleFieldList fields; - - Index num_tag_imports = 0; - Index num_func_imports = 0; - Index num_table_imports = 0; - Index num_memory_imports = 0; - Index num_global_imports = 0; - - // Cached for convenience; the pointers are shared with values that are - // stored in either ModuleField or Import. - std::vector<Tag*> tags; - std::vector<Func*> funcs; - std::vector<Global*> globals; - std::vector<Import*> imports; - std::vector<Export*> exports; - std::vector<TypeEntry*> types; - std::vector<Table*> tables; - std::vector<ElemSegment*> elem_segments; - std::vector<Memory*> memories; - std::vector<DataSegment*> data_segments; - std::vector<Var*> starts; - - BindingHash tag_bindings; - BindingHash func_bindings; - BindingHash global_bindings; - BindingHash export_bindings; - BindingHash type_bindings; - BindingHash table_bindings; - BindingHash memory_bindings; - BindingHash data_segment_bindings; - BindingHash elem_segment_bindings; -}; - -enum class ScriptModuleType { - Text, - Binary, - Quoted, -}; - -// A ScriptModule is a module that may not yet be decoded. This allows for text -// and binary parsing errors to be deferred until validation time. -class ScriptModule { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(ScriptModule); - ScriptModule() = delete; - virtual ~ScriptModule() = default; - - ScriptModuleType type() const { return type_; } - virtual const Location& location() const = 0; - - protected: - explicit ScriptModule(ScriptModuleType type) : type_(type) {} - - ScriptModuleType type_; -}; - -template <ScriptModuleType TypeEnum> -class ScriptModuleMixin : public ScriptModule { - public: - static bool classof(const ScriptModule* script_module) { - return script_module->type() == TypeEnum; - } - - ScriptModuleMixin() : ScriptModule(TypeEnum) {} -}; - -class TextScriptModule : public ScriptModuleMixin<ScriptModuleType::Text> { - public: - const Location& location() const override { return module.loc; } - - Module module; -}; - -template <ScriptModuleType TypeEnum> -class DataScriptModule : public ScriptModuleMixin<TypeEnum> { - public: - const Location& location() const override { return loc; } - - Location loc; - std::string name; - std::vector<uint8_t> data; -}; - -typedef DataScriptModule<ScriptModuleType::Binary> BinaryScriptModule; -typedef DataScriptModule<ScriptModuleType::Quoted> QuotedScriptModule; - -enum class ActionType { - Invoke, - Get, -}; - -class Action { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(Action); - Action() = delete; - virtual ~Action() = default; - - ActionType type() const { return type_; } - - Location loc; - Var module_var; - std::string name; - - protected: - explicit Action(ActionType type, const Location& loc = Location()) - : loc(loc), type_(type) {} - - ActionType type_; -}; - -typedef std::unique_ptr<Action> ActionPtr; - -template <ActionType TypeEnum> -class ActionMixin : public Action { - public: - static bool classof(const Action* action) { - return action->type() == TypeEnum; - } - - explicit ActionMixin(const Location& loc = Location()) - : Action(TypeEnum, loc) {} -}; - -class GetAction : public ActionMixin<ActionType::Get> { - public: - explicit GetAction(const Location& loc = Location()) - : ActionMixin<ActionType::Get>(loc) {} -}; - -class InvokeAction : public ActionMixin<ActionType::Invoke> { - public: - explicit InvokeAction(const Location& loc = Location()) - : ActionMixin<ActionType::Invoke>(loc) {} - - ConstVector args; -}; - -enum class CommandType { - Module, - ScriptModule, - Action, - Register, - AssertMalformed, - AssertInvalid, - AssertUnlinkable, - AssertUninstantiable, - AssertReturn, - AssertTrap, - AssertExhaustion, - AssertException, - - First = Module, - Last = AssertException, -}; -static const int kCommandTypeCount = WABT_ENUM_COUNT(CommandType); - -class Command { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(Command); - Command() = delete; - virtual ~Command() = default; - - CommandType type; - - protected: - explicit Command(CommandType type) : type(type) {} -}; - -template <CommandType TypeEnum> -class CommandMixin : public Command { - public: - static bool classof(const Command* cmd) { return cmd->type == TypeEnum; } - CommandMixin() : Command(TypeEnum) {} -}; - -class ModuleCommand : public CommandMixin<CommandType::Module> { - public: - Module module; -}; - -class ScriptModuleCommand : public CommandMixin<CommandType::ScriptModule> { - public: - // Both the module and the script_module need to be stored since the module - // has the parsed information about the module, but the script_module has the - // original contents (binary or quoted). - Module module; - std::unique_ptr<ScriptModule> script_module; -}; - -template <CommandType TypeEnum> -class ActionCommandBase : public CommandMixin<TypeEnum> { - public: - ActionPtr action; -}; - -typedef ActionCommandBase<CommandType::Action> ActionCommand; - -class RegisterCommand : public CommandMixin<CommandType::Register> { - public: - RegisterCommand(std::string_view module_name, const Var& var) - : module_name(module_name), var(var) {} - - std::string module_name; - Var var; -}; - -class AssertReturnCommand : public CommandMixin<CommandType::AssertReturn> { - public: - ActionPtr action; - ConstVector expected; -}; - -template <CommandType TypeEnum> -class AssertTrapCommandBase : public CommandMixin<TypeEnum> { - public: - ActionPtr action; - std::string text; -}; - -typedef AssertTrapCommandBase<CommandType::AssertTrap> AssertTrapCommand; -typedef AssertTrapCommandBase<CommandType::AssertExhaustion> - AssertExhaustionCommand; - -template <CommandType TypeEnum> -class AssertModuleCommand : public CommandMixin<TypeEnum> { - public: - std::unique_ptr<ScriptModule> module; - std::string text; -}; - -typedef AssertModuleCommand<CommandType::AssertMalformed> - AssertMalformedCommand; -typedef AssertModuleCommand<CommandType::AssertInvalid> AssertInvalidCommand; -typedef AssertModuleCommand<CommandType::AssertUnlinkable> - AssertUnlinkableCommand; -typedef AssertModuleCommand<CommandType::AssertUninstantiable> - AssertUninstantiableCommand; - -class AssertExceptionCommand - : public CommandMixin<CommandType::AssertException> { - public: - ActionPtr action; -}; - -typedef std::unique_ptr<Command> CommandPtr; -typedef std::vector<CommandPtr> CommandPtrVector; - -struct Script { - WABT_DISALLOW_COPY_AND_ASSIGN(Script); - Script() = default; - - const Module* GetFirstModule() const; - Module* GetFirstModule(); - const Module* GetModule(const Var&) const; - - CommandPtrVector commands; - BindingHash module_bindings; -}; - -void MakeTypeBindingReverseMapping( - size_t num_types, - const BindingHash& bindings, - std::vector<std::string>* out_reverse_mapping); - -} // namespace wabt - -#endif /* WABT_IR_H_ */ diff --git a/src/leb128.cc b/src/leb128.cc index 6d15e2f3..29b20f61 100644 --- a/src/leb128.cc +++ b/src/leb128.cc @@ -14,11 +14,11 @@ * limitations under the License. */ -#include "src/leb128.h" +#include "wabt/leb128.h" #include <type_traits> -#include "src/stream.h" +#include "wabt/stream.h" #define MAX_U32_LEB128_BYTES 5 #define MAX_U64_LEB128_BYTES 10 diff --git a/src/leb128.h b/src/leb128.h deleted file mode 100644 index 56f803cc..00000000 --- a/src/leb128.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_LEB128_H_ -#define WABT_LEB128_H_ - -#include <cstdint> - -#include "src/common.h" - -namespace wabt { - -class Stream; - -// Returns the length of the leb128. -Offset U32Leb128Length(uint32_t value); - -void WriteU32Leb128(Stream* stream, uint32_t value, const char* desc); -void WriteS32Leb128(Stream* stream, uint32_t value, const char* desc); -void WriteU64Leb128(Stream* stream, uint64_t value, const char* desc); -void WriteS64Leb128(Stream* stream, uint64_t value, const char* desc); -void WriteFixedS32Leb128(Stream* stream, uint32_t value, const char* desc); -void WriteFixedU32Leb128(Stream* stream, uint32_t value, const char* desc); - -Offset WriteU32Leb128At(Stream* stream, - Offset offset, - uint32_t value, - const char* desc); - -Offset WriteFixedU32Leb128At(Stream* stream, - Offset offset, - uint32_t value, - const char* desc); - -Offset WriteU32Leb128Raw(uint8_t* data, uint8_t* end, uint32_t value); -Offset WriteFixedU32Leb128Raw(uint8_t* data, uint8_t* end, uint32_t value); - -// Convenience functions for writing enums as LEB128s. -template <typename T> -void WriteU32Leb128(Stream* stream, T value, const char* desc) { - WriteU32Leb128(stream, static_cast<uint32_t>(value), desc); -} - -template <typename T> -void WriteS32Leb128(Stream* stream, T value, const char* desc) { - WriteS32Leb128(stream, static_cast<uint32_t>(value), desc); -} - -// Returns the length of the leb128. -size_t ReadU32Leb128(const uint8_t* p, const uint8_t* end, uint32_t* out_value); -size_t ReadU64Leb128(const uint8_t* p, const uint8_t* end, uint64_t* out_value); -size_t ReadS32Leb128(const uint8_t* p, const uint8_t* end, uint32_t* out_value); -size_t ReadS64Leb128(const uint8_t* p, const uint8_t* end, uint64_t* out_value); - -} // namespace wabt - -#endif // WABT_LEB128_H_ diff --git a/src/lexer-source-line-finder.cc b/src/lexer-source-line-finder.cc index 833cb900..4d407e9d 100644 --- a/src/lexer-source-line-finder.cc +++ b/src/lexer-source-line-finder.cc @@ -14,11 +14,11 @@ * limitations under the License. */ -#include "src/lexer-source-line-finder.h" +#include "wabt/lexer-source-line-finder.h" #include <algorithm> -#include "src/lexer-source.h" +#include "wabt/lexer-source.h" namespace wabt { diff --git a/src/lexer-source-line-finder.h b/src/lexer-source-line-finder.h deleted file mode 100644 index baf87b4e..00000000 --- a/src/lexer-source-line-finder.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_LEXER_SOURCE_LINE_FINDER_H_ -#define WABT_LEXER_SOURCE_LINE_FINDER_H_ - -#include <memory> -#include <string> -#include <vector> - -#include "src/common.h" -#include "src/lexer-source.h" -#include "src/range.h" - -namespace wabt { - -class LexerSourceLineFinder { - public: - struct SourceLine { - std::string line; - int column_offset; - }; - - explicit LexerSourceLineFinder(std::unique_ptr<LexerSource>); - - Result GetSourceLine(const Location& loc, - Offset max_line_length, - SourceLine* out_source_line); - Result GetLineOffsets(int line, OffsetRange* out_offsets); - - private: - static OffsetRange ClampSourceLineOffsets(OffsetRange line_offset_range, - ColumnRange column_range, - Offset max_line_length); - - bool IsLineCached(int line) const; - OffsetRange GetCachedLine(int line) const; - - std::unique_ptr<LexerSource> source_; - std::vector<OffsetRange> line_ranges_; - Offset next_line_start_; - bool last_cr_; // Last read character was a '\r' (carriage return). - bool eof_; -}; - -} // namespace wabt - -#endif // WABT_LEXER_SOURCE_LINE_FINDER_H_ diff --git a/src/lexer-source.cc b/src/lexer-source.cc index 896a52e9..eff56e25 100644 --- a/src/lexer-source.cc +++ b/src/lexer-source.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/lexer-source.h" +#include "wabt/lexer-source.h" #include <algorithm> diff --git a/src/lexer-source.h b/src/lexer-source.h deleted file mode 100644 index d49d5c6e..00000000 --- a/src/lexer-source.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_LEXER_SOURCE_H_ -#define WABT_LEXER_SOURCE_H_ - -#include <cstddef> -#include <memory> -#include <string> -#include <vector> - -#include "src/common.h" -#include "src/range.h" - -namespace wabt { - -class LexerSource { - public: - LexerSource(const void* data, Offset size); - - std::unique_ptr<LexerSource> Clone(); - Result Tell(Offset* out_offset); - size_t Fill(void* dest, size_t size); - Result ReadRange(OffsetRange, std::vector<char>* out_data); - Result Seek(Offset offset); - - WABT_DISALLOW_COPY_AND_ASSIGN(LexerSource); - - const void* data() { return data_; } - Offset size() { return size_; } - - private: - const void* data_; - Offset size_; - Offset read_offset_; -}; - -} // namespace wabt - -#endif // WABT_LEXER_SOURCE_H_ diff --git a/src/literal.cc b/src/literal.cc index 615d8cb5..e1a79958 100644 --- a/src/literal.cc +++ b/src/literal.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/literal.h" +#include "wabt/literal.h" #include <cassert> #include <cerrno> diff --git a/src/literal.h b/src/literal.h deleted file mode 100644 index ff5b2550..00000000 --- a/src/literal.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_LITERAL_H_ -#define WABT_LITERAL_H_ - -#include <cstdint> - -#include "src/common.h" - -namespace wabt { - -// These functions all return Result::Ok on success and Result::Error on -// failure. -// -// NOTE: the functions are written for use with wast-lexer, assuming that the -// literal has already matched the patterns defined there. As a result, the -// only validation that is done is for overflow, not for otherwise bogus input. - -enum class LiteralType { - Int, - Float, - Hexfloat, - Infinity, - Nan, -}; - -enum class ParseIntType { - UnsignedOnly = 0, - SignedAndUnsigned = 1, -}; - -/* Size of char buffer required to hold hex representation of a float/double */ -#define WABT_MAX_FLOAT_HEX 20 -#define WABT_MAX_DOUBLE_HEX 40 - -Result ParseHexdigit(char c, uint32_t* out); -Result ParseInt8(const char* s, - const char* end, - uint8_t* out, - ParseIntType parse_type); -Result ParseInt16(const char* s, - const char* end, - uint16_t* out, - ParseIntType parse_type); -Result ParseInt32(const char* s, - const char* end, - uint32_t* out, - ParseIntType parse_type); -Result ParseInt64(const char* s, - const char* end, - uint64_t* out, - ParseIntType parse_type); -Result ParseUint64(const char* s, const char* end, uint64_t* out); -Result ParseUint128(const char* s, const char* end, v128* out); -Result ParseFloat(LiteralType literal_type, - const char* s, - const char* end, - uint32_t* out_bits); -Result ParseDouble(LiteralType literal_type, - const char* s, - const char* end, - uint64_t* out_bits); - -// Same as above but taking a string_view -inline Result ParseInt8(std::string_view v, - uint8_t* out, - ParseIntType parse_type) { - return ParseInt8(v.data(), v.data() + v.size(), out, parse_type); -} - -inline Result ParseInt16(std::string_view v, - uint16_t* out, - ParseIntType parse_type) { - return ParseInt16(v.data(), v.data() + v.size(), out, parse_type); -} - -inline Result ParseInt32(std::string_view v, - uint32_t* out, - ParseIntType parse_type) { - return ParseInt32(v.data(), v.data() + v.size(), out, parse_type); -} - -inline Result ParseInt64(std::string_view v, - uint64_t* out, - ParseIntType parse_type) { - return ParseInt64(v.data(), v.data() + v.size(), out, parse_type); -} - -inline Result ParseUint64(std::string_view v, uint64_t* out) { - return ParseUint64(v.data(), v.data() + v.size(), out); -} - -inline Result ParseUint128(std::string_view v, v128* out) { - return ParseUint128(v.data(), v.data() + v.size(), out); -} - -inline Result ParseFloat(LiteralType literal_type, - std::string_view v, - uint32_t* out_bits) { - return ParseFloat(literal_type, v.data(), v.data() + v.size(), out_bits); -} - -inline Result ParseDouble(LiteralType literal_type, - std::string_view v, - uint64_t* out_bits) { - return ParseDouble(literal_type, v.data(), v.data() + v.size(), out_bits); -} - -void WriteFloatHex(char* buffer, size_t size, uint32_t bits); -void WriteDoubleHex(char* buffer, size_t size, uint64_t bits); -void WriteUint128(char* buffer, size_t size, v128 bits); - -} // namespace wabt - -#endif /* WABT_LITERAL_H_ */ diff --git a/src/make-unique.h b/src/make-unique.h deleted file mode 100644 index 46d3ac14..00000000 --- a/src/make-unique.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_MAKE_UNIQUE_H_ -#define WABT_MAKE_UNIQUE_H_ - -#include <memory> - -namespace wabt { - -// This is named MakeUnique instead of make_unique because make_unique has the -// potential to conflict with std::make_unique if it is defined. -// -// On gcc/clang, we currently compile with c++11, which doesn't define -// std::make_unique, but on MSVC the newest C++ version is always used, which -// includes std::make_unique. If an argument from the std namespace is used, it -// will cause ADL to find std::make_unique, and an unqualified call to -// make_unique will be ambiguous. We can work around this by fully qualifying -// the call (i.e. wabt::make_unique), but it's simpler to just use a different -// name. It's also more consistent with other names in the wabt namespace, -// which use CamelCase. -template <typename T, typename... Args> -std::unique_ptr<T> MakeUnique(Args&&... args) { - return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); -} - -} // namespace wabt - -#endif // WABT_MAKE_UNIQUE_H_ diff --git a/src/opcode-code-table.c b/src/opcode-code-table.c index c3e06d03..b9b32a1a 100644 --- a/src/opcode-code-table.c +++ b/src/opcode-code-table.c @@ -14,9 +14,9 @@ * limitations under the License. */ -#include "src/opcode-code-table.h" +#include "wabt/opcode-code-table.h" -#include "config.h" +#include "wabt/config.h" #include <stdint.h> @@ -24,7 +24,7 @@ typedef enum WabtOpcodeEnum { #define WABT_OPCODE(rtype, type1, type2, type3, mem_size, prefix, code, Name, \ text, decomp) \ Name, -#include "opcode.def" +#include "wabt/opcode.def" #undef WABT_OPCODE Invalid, } WabtOpcodeEnum; @@ -36,6 +36,6 @@ uint32_t WabtOpcodeCodeTable[WABT_OPCODE_CODE_TABLE_SIZE] = { #define WABT_OPCODE(rtype, type1, type2, type3, mem_size, prefix, code, Name, \ text, decomp) \ [(prefix << 8) + code] = Name, -#include "opcode.def" +#include "wabt/opcode.def" #undef WABT_OPCODE }; diff --git a/src/opcode-code-table.h b/src/opcode-code-table.h deleted file mode 100644 index 3adb478d..00000000 --- a/src/opcode-code-table.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2018 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_OPCODE_CODE_TABLE_H_ -#define WABT_OPCODE_CODE_TABLE_H_ - -#include <stdint.h> -#include <stdlib.h> - -#ifdef __cplusplus -extern "C" { -#endif - -#define WABT_OPCODE_CODE_TABLE_SIZE 65536 - -/* This structure is defined in C because C++ doesn't (yet) allow you to use - * designated array initializers, i.e. [10] = {foo}. - */ -extern uint32_t WabtOpcodeCodeTable[WABT_OPCODE_CODE_TABLE_SIZE]; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* WABT_OPCODE_CODE_TABLE_H_ */ diff --git a/src/opcode.cc b/src/opcode.cc index cfa23f1d..c948ab21 100644 --- a/src/opcode.cc +++ b/src/opcode.cc @@ -14,9 +14,9 @@ * limitations under the License. */ -#include "src/opcode.h" +#include "wabt/opcode.h" -#include "src/feature.h" +#include "wabt/feature.h" namespace wabt { @@ -26,7 +26,7 @@ Opcode::Info Opcode::infos_[] = { text, decomp) \ {text, decomp, Type::rtype, {Type::type1, Type::type2, Type::type3}, \ mem_size, prefix, code, PrefixCode(prefix, code)}, -#include "src/opcode.def" +#include "wabt/opcode.def" #undef WABT_OPCODE {"<invalid>", "", Type::Void, {Type::Void, Type::Void, Type::Void}, 0, 0, 0, 0}, @@ -35,7 +35,7 @@ Opcode::Info Opcode::infos_[] = { #define WABT_OPCODE(rtype, type1, type2, type3, mem_size, prefix, code, Name, \ text, decomp) \ /* static */ Opcode Opcode::Name##_Opcode(Opcode::Name); -#include "src/opcode.def" +#include "wabt/opcode.def" #undef WABT_OPCODE Opcode::Info Opcode::GetInfo() const { diff --git a/src/opcode.def b/src/opcode.def deleted file mode 100644 index 9005418e..00000000 --- a/src/opcode.def +++ /dev/null @@ -1,571 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_OPCODE -#error "You must define WABT_OPCODE before including this file." -#endif - -/* *** NOTE *** This list must be kept sorted so it can be binary searched */ - -/* - * tr: result type - * t1: type of the 1st parameter - * t2: type of the 2nd parameter - * t3: type of the 3rd parameter - * m: memory size of the operation, if any - * prefix: the 1-byte opcode prefix, if any - * code: opcode - * Name: used to generate the opcode enum - * text: a string of the opcode name in the text format - * decomp: an optional friendly version of text, used for decompilation. - * - * tr t1 t2 t3 m prefix code Name text - * ========================================================== */ - -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x00, Unreachable, "unreachable", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x01, Nop, "nop", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x02, Block, "block", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x03, Loop, "loop", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x04, If, "if", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x05, Else, "else", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x06, Try, "try", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x07, Catch, "catch", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x08, Throw, "throw", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x09, Rethrow, "rethrow", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x0b, End, "end", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x0c, Br, "br", "") -WABT_OPCODE(___, I32, ___, ___, 0, 0, 0x0d, BrIf, "br_if", "") -WABT_OPCODE(___, I32, ___, ___, 0, 0, 0x0e, BrTable, "br_table", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x0f, Return, "return", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x10, Call, "call", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x11, CallIndirect, "call_indirect", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x12, ReturnCall, "return_call", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x13, ReturnCallIndirect, "return_call_indirect", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x14, CallRef, "call_ref", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x18, Delegate, "delegate", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x19, CatchAll, "catch_all", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x1a, Drop, "drop", "") -WABT_OPCODE(___, ___, ___, I32, 0, 0, 0x1b, Select, "select", "") -WABT_OPCODE(___, ___, ___, I32, 0, 0, 0x1c, SelectT, "select", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x20, LocalGet, "local.get", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x21, LocalSet, "local.set", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x22, LocalTee, "local.tee", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x23, GlobalGet, "global.get", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0x24, GlobalSet, "global.set", "") -WABT_OPCODE(I32, I32, ___, ___, 4, 0, 0x28, I32Load, "i32.load", "") -WABT_OPCODE(I64, I32, ___, ___, 8, 0, 0x29, I64Load, "i64.load", "") -WABT_OPCODE(F32, I32, ___, ___, 4, 0, 0x2a, F32Load, "f32.load", "") -WABT_OPCODE(F64, I32, ___, ___, 8, 0, 0x2b, F64Load, "f64.load", "") -WABT_OPCODE(I32, I32, ___, ___, 1, 0, 0x2c, I32Load8S, "i32.load8_s", "") -WABT_OPCODE(I32, I32, ___, ___, 1, 0, 0x2d, I32Load8U, "i32.load8_u", "") -WABT_OPCODE(I32, I32, ___, ___, 2, 0, 0x2e, I32Load16S, "i32.load16_s", "") -WABT_OPCODE(I32, I32, ___, ___, 2, 0, 0x2f, I32Load16U, "i32.load16_u", "") -WABT_OPCODE(I64, I32, ___, ___, 1, 0, 0x30, I64Load8S, "i64.load8_s", "") -WABT_OPCODE(I64, I32, ___, ___, 1, 0, 0x31, I64Load8U, "i64.load8_u", "") -WABT_OPCODE(I64, I32, ___, ___, 2, 0, 0x32, I64Load16S, "i64.load16_s", "") -WABT_OPCODE(I64, I32, ___, ___, 2, 0, 0x33, I64Load16U, "i64.load16_u", "") -WABT_OPCODE(I64, I32, ___, ___, 4, 0, 0x34, I64Load32S, "i64.load32_s", "") -WABT_OPCODE(I64, I32, ___, ___, 4, 0, 0x35, I64Load32U, "i64.load32_u", "") -WABT_OPCODE(___, I32, I32, ___, 4, 0, 0x36, I32Store, "i32.store", "") -WABT_OPCODE(___, I32, I64, ___, 8, 0, 0x37, I64Store, "i64.store", "") -WABT_OPCODE(___, I32, F32, ___, 4, 0, 0x38, F32Store, "f32.store", "") -WABT_OPCODE(___, I32, F64, ___, 8, 0, 0x39, F64Store, "f64.store", "") -WABT_OPCODE(___, I32, I32, ___, 1, 0, 0x3a, I32Store8, "i32.store8", "") -WABT_OPCODE(___, I32, I32, ___, 2, 0, 0x3b, I32Store16, "i32.store16", "") -WABT_OPCODE(___, I32, I64, ___, 1, 0, 0x3c, I64Store8, "i64.store8", "") -WABT_OPCODE(___, I32, I64, ___, 2, 0, 0x3d, I64Store16, "i64.store16", "") -WABT_OPCODE(___, I32, I64, ___, 4, 0, 0x3e, I64Store32, "i64.store32", "") -WABT_OPCODE(I32, ___, ___, ___, 0, 0, 0x3f, MemorySize, "memory.size", "") -WABT_OPCODE(I32, I32, ___, ___, 0, 0, 0x40, MemoryGrow, "memory.grow", "") -WABT_OPCODE(I32, ___, ___, ___, 0, 0, 0x41, I32Const, "i32.const", "") -WABT_OPCODE(I64, ___, ___, ___, 0, 0, 0x42, I64Const, "i64.const", "") -WABT_OPCODE(F32, ___, ___, ___, 0, 0, 0x43, F32Const, "f32.const", "") -WABT_OPCODE(F64, ___, ___, ___, 0, 0, 0x44, F64Const, "f64.const", "") -WABT_OPCODE(I32, I32, ___, ___, 0, 0, 0x45, I32Eqz, "i32.eqz", "eqz") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x46, I32Eq, "i32.eq", "==") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x47, I32Ne, "i32.ne", "!=") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x48, I32LtS, "i32.lt_s", "<") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x49, I32LtU, "i32.lt_u", "<") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x4a, I32GtS, "i32.gt_s", ">") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x4b, I32GtU, "i32.gt_u", ">") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x4c, I32LeS, "i32.le_s", "<=") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x4d, I32LeU, "i32.le_u", "<=") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x4e, I32GeS, "i32.ge_s", ">=") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x4f, I32GeU, "i32.ge_u", ">=") -WABT_OPCODE(I32, I64, ___, ___, 0, 0, 0x50, I64Eqz, "i64.eqz", "eqz") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x51, I64Eq, "i64.eq", "==") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x52, I64Ne, "i64.ne", "!=") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x53, I64LtS, "i64.lt_s", "<") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x54, I64LtU, "i64.lt_u", "<") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x55, I64GtS, "i64.gt_s", ">") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x56, I64GtU, "i64.gt_u", ">") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x57, I64LeS, "i64.le_s", "<=") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x58, I64LeU, "i64.le_u", "<=") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x59, I64GeS, "i64.ge_s", ">=") -WABT_OPCODE(I32, I64, I64, ___, 0, 0, 0x5a, I64GeU, "i64.ge_u", ">=") -WABT_OPCODE(I32, F32, F32, ___, 0, 0, 0x5b, F32Eq, "f32.eq", "==") -WABT_OPCODE(I32, F32, F32, ___, 0, 0, 0x5c, F32Ne, "f32.ne", "!=") -WABT_OPCODE(I32, F32, F32, ___, 0, 0, 0x5d, F32Lt, "f32.lt", "<") -WABT_OPCODE(I32, F32, F32, ___, 0, 0, 0x5e, F32Gt, "f32.gt", ">") -WABT_OPCODE(I32, F32, F32, ___, 0, 0, 0x5f, F32Le, "f32.le", "<=") -WABT_OPCODE(I32, F32, F32, ___, 0, 0, 0x60, F32Ge, "f32.ge", ">=") -WABT_OPCODE(I32, F64, F64, ___, 0, 0, 0x61, F64Eq, "f64.eq", "==") -WABT_OPCODE(I32, F64, F64, ___, 0, 0, 0x62, F64Ne, "f64.ne", "!=") -WABT_OPCODE(I32, F64, F64, ___, 0, 0, 0x63, F64Lt, "f64.lt", "<") -WABT_OPCODE(I32, F64, F64, ___, 0, 0, 0x64, F64Gt, "f64.gt", ">") -WABT_OPCODE(I32, F64, F64, ___, 0, 0, 0x65, F64Le, "f64.le", "<=") -WABT_OPCODE(I32, F64, F64, ___, 0, 0, 0x66, F64Ge, "f64.ge", ">=") -WABT_OPCODE(I32, I32, ___, ___, 0, 0, 0x67, I32Clz, "i32.clz", "clz") -WABT_OPCODE(I32, I32, ___, ___, 0, 0, 0x68, I32Ctz, "i32.ctz", "ctz") -WABT_OPCODE(I32, I32, ___, ___, 0, 0, 0x69, I32Popcnt, "i32.popcnt", "popcnt") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x6a, I32Add, "i32.add", "+") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x6b, I32Sub, "i32.sub", "-") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x6c, I32Mul, "i32.mul", "*") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x6d, I32DivS, "i32.div_s", "/") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x6e, I32DivU, "i32.div_u", "/") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x6f, I32RemS, "i32.rem_s", "%") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x70, I32RemU, "i32.rem_u", "%") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x71, I32And, "i32.and", "&") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x72, I32Or, "i32.or", "|") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x73, I32Xor, "i32.xor", "^") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x74, I32Shl, "i32.shl", "<<") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x75, I32ShrS, "i32.shr_s", ">>") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x76, I32ShrU, "i32.shr_u", ">>") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x77, I32Rotl, "i32.rotl", "<<") -WABT_OPCODE(I32, I32, I32, ___, 0, 0, 0x78, I32Rotr, "i32.rotr", ">>") -WABT_OPCODE(I64, I64, ___, ___, 0, 0, 0x79, I64Clz, "i64.clz", "clz") -WABT_OPCODE(I64, I64, ___, ___, 0, 0, 0x7a, I64Ctz, "i64.ctz", "ctz") -WABT_OPCODE(I64, I64, ___, ___, 0, 0, 0x7b, I64Popcnt, "i64.popcnt", "popcnt") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x7c, I64Add, "i64.add", "+") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x7d, I64Sub, "i64.sub", "-") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x7e, I64Mul, "i64.mul", "*") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x7f, I64DivS, "i64.div_s", "/") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x80, I64DivU, "i64.div_u", "/") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x81, I64RemS, "i64.rem_s", "%") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x82, I64RemU, "i64.rem_u", "%") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x83, I64And, "i64.and", "&") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x84, I64Or, "i64.or", "|") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x85, I64Xor, "i64.xor", "^") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x86, I64Shl, "i64.shl", "<<") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x87, I64ShrS, "i64.shr_s", ">>") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x88, I64ShrU, "i64.shr_u", ">>") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x89, I64Rotl, "i64.rotl", "<<") -WABT_OPCODE(I64, I64, I64, ___, 0, 0, 0x8a, I64Rotr, "i64.rotr", ">>") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x8b, F32Abs, "f32.abs", "abs") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x8c, F32Neg, "f32.neg", "-") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x8d, F32Ceil, "f32.ceil", "ceil") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x8e, F32Floor, "f32.floor", "floor") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x8f, F32Trunc, "f32.trunc", "trunc") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x90, F32Nearest, "f32.nearest", "nearest") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x91, F32Sqrt, "f32.sqrt", "sqrt") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x92, F32Add, "f32.add", "+") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x93, F32Sub, "f32.sub", "-") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x94, F32Mul, "f32.mul", "*") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x95, F32Div, "f32.div", "/") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x96, F32Min, "f32.min", "min") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x97, F32Max, "f32.max", "max") -WABT_OPCODE(F32, F32, F32, ___, 0, 0, 0x98, F32Copysign, "f32.copysign", "copysign") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0x99, F64Abs, "f64.abs", "abs") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0x9a, F64Neg, "f64.neg", "-") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0x9b, F64Ceil, "f64.ceil", "ceil") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0x9c, F64Floor, "f64.floor", "floor") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0x9d, F64Trunc, "f64.trunc", "trunc") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0x9e, F64Nearest, "f64.nearest", "nearest") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0x9f, F64Sqrt, "f64.sqrt", "sqrt") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0xa0, F64Add, "f64.add", "+") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0xa1, F64Sub, "f64.sub", "-") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0xa2, F64Mul, "f64.mul", "*") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0xa3, F64Div, "f64.div", "/") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0xa4, F64Min, "f64.min", "min") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0xa5, F64Max, "f64.max", "max") -WABT_OPCODE(F64, F64, F64, ___, 0, 0, 0xa6, F64Copysign, "f64.copysign", "copysign") -WABT_OPCODE(I32, I64, ___, ___, 0, 0, 0xa7, I32WrapI64, "i32.wrap_i64", "") -WABT_OPCODE(I32, F32, ___, ___, 0, 0, 0xa8, I32TruncF32S, "i32.trunc_f32_s", "") -WABT_OPCODE(I32, F32, ___, ___, 0, 0, 0xa9, I32TruncF32U, "i32.trunc_f32_u", "") -WABT_OPCODE(I32, F64, ___, ___, 0, 0, 0xaa, I32TruncF64S, "i32.trunc_f64_s", "") -WABT_OPCODE(I32, F64, ___, ___, 0, 0, 0xab, I32TruncF64U, "i32.trunc_f64_u", "") -WABT_OPCODE(I64, I32, ___, ___, 0, 0, 0xac, I64ExtendI32S, "i64.extend_i32_s", "") -WABT_OPCODE(I64, I32, ___, ___, 0, 0, 0xad, I64ExtendI32U, "i64.extend_i32_u", "") -WABT_OPCODE(I64, F32, ___, ___, 0, 0, 0xae, I64TruncF32S, "i64.trunc_f32_s", "") -WABT_OPCODE(I64, F32, ___, ___, 0, 0, 0xaf, I64TruncF32U, "i64.trunc_f32_u", "") -WABT_OPCODE(I64, F64, ___, ___, 0, 0, 0xb0, I64TruncF64S, "i64.trunc_f64_s", "") -WABT_OPCODE(I64, F64, ___, ___, 0, 0, 0xb1, I64TruncF64U, "i64.trunc_f64_u", "") -WABT_OPCODE(F32, I32, ___, ___, 0, 0, 0xb2, F32ConvertI32S, "f32.convert_i32_s", "") -WABT_OPCODE(F32, I32, ___, ___, 0, 0, 0xb3, F32ConvertI32U, "f32.convert_i32_u", "") -WABT_OPCODE(F32, I64, ___, ___, 0, 0, 0xb4, F32ConvertI64S, "f32.convert_i64_s", "") -WABT_OPCODE(F32, I64, ___, ___, 0, 0, 0xb5, F32ConvertI64U, "f32.convert_i64_u", "") -WABT_OPCODE(F32, F64, ___, ___, 0, 0, 0xb6, F32DemoteF64, "f32.demote_f64", "") -WABT_OPCODE(F64, I32, ___, ___, 0, 0, 0xb7, F64ConvertI32S, "f64.convert_i32_s", "") -WABT_OPCODE(F64, I32, ___, ___, 0, 0, 0xb8, F64ConvertI32U, "f64.convert_i32_u", "") -WABT_OPCODE(F64, I64, ___, ___, 0, 0, 0xb9, F64ConvertI64S, "f64.convert_i64_s", "") -WABT_OPCODE(F64, I64, ___, ___, 0, 0, 0xba, F64ConvertI64U, "f64.convert_i64_u", "") -WABT_OPCODE(F64, F32, ___, ___, 0, 0, 0xbb, F64PromoteF32, "f64.promote_f32", "") -WABT_OPCODE(I32, F32, ___, ___, 0, 0, 0xbc, I32ReinterpretF32, "i32.reinterpret_f32", "") -WABT_OPCODE(I64, F64, ___, ___, 0, 0, 0xbd, I64ReinterpretF64, "i64.reinterpret_f64", "") -WABT_OPCODE(F32, I32, ___, ___, 0, 0, 0xbe, F32ReinterpretI32, "f32.reinterpret_i32", "") -WABT_OPCODE(F64, I64, ___, ___, 0, 0, 0xbf, F64ReinterpretI64, "f64.reinterpret_i64", "") - -/* Sign-extension opcodes (--enable-sign-extension) */ -WABT_OPCODE(I32, I32, ___, ___, 0, 0, 0xC0, I32Extend8S, "i32.extend8_s", "") -WABT_OPCODE(I32, I32, ___, ___, 0, 0, 0xC1, I32Extend16S, "i32.extend16_s", "") -WABT_OPCODE(I64, I64, ___, ___, 0, 0, 0xC2, I64Extend8S, "i64.extend8_s", "") -WABT_OPCODE(I64, I64, ___, ___, 0, 0, 0xC3, I64Extend16S, "i64.extend16_s", "") -WABT_OPCODE(I64, I64, ___, ___, 0, 0, 0xC4, I64Extend32S, "i64.extend32_s", "") - -/* Interpreter-only opcodes */ -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xe0, InterpAlloca, "alloca", "") -WABT_OPCODE(___, I32, ___, ___, 0, 0, 0xe1, InterpBrUnless, "br_unless", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xe2, InterpCallImport, "call_import", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xe3, InterpData, "data", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xe4, InterpDropKeep, "drop_keep", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xe5, InterpCatchDrop, "catch_drop", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xe6, InterpAdjustFrameForReturnCall, "adjust_frame_for_return_call", "") - -/* Saturating float-to-int opcodes (--enable-saturating-float-to-int) */ -WABT_OPCODE(I32, F32, ___, ___, 0, 0xfc, 0x00, I32TruncSatF32S, "i32.trunc_sat_f32_s", "") -WABT_OPCODE(I32, F32, ___, ___, 0, 0xfc, 0x01, I32TruncSatF32U, "i32.trunc_sat_f32_u", "") -WABT_OPCODE(I32, F64, ___, ___, 0, 0xfc, 0x02, I32TruncSatF64S, "i32.trunc_sat_f64_s", "") -WABT_OPCODE(I32, F64, ___, ___, 0, 0xfc, 0x03, I32TruncSatF64U, "i32.trunc_sat_f64_u", "") -WABT_OPCODE(I64, F32, ___, ___, 0, 0xfc, 0x04, I64TruncSatF32S, "i64.trunc_sat_f32_s", "") -WABT_OPCODE(I64, F32, ___, ___, 0, 0xfc, 0x05, I64TruncSatF32U, "i64.trunc_sat_f32_u", "") -WABT_OPCODE(I64, F64, ___, ___, 0, 0xfc, 0x06, I64TruncSatF64S, "i64.trunc_sat_f64_s", "") -WABT_OPCODE(I64, F64, ___, ___, 0, 0xfc, 0x07, I64TruncSatF64U, "i64.trunc_sat_f64_u", "") - -/* Bulk-memory */ -WABT_OPCODE(___, I32, I32, I32, 0, 0xfc, 0x08, MemoryInit, "memory.init", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0xfc, 0x09, DataDrop, "data.drop", "") -WABT_OPCODE(___, I32, I32, I32, 0, 0xfc, 0x0a, MemoryCopy,"memory.copy", "") -WABT_OPCODE(___, I32, I32, I32, 0, 0xfc, 0x0b, MemoryFill, "memory.fill", "") -WABT_OPCODE(___, I32, I32, I32, 0, 0xfc, 0x0c, TableInit, "table.init", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0xfc, 0x0d, ElemDrop, "elem.drop", "") -WABT_OPCODE(___, I32, I32, I32, 0, 0xfc, 0x0e, TableCopy, "table.copy", "") - -/* Reference types */ -WABT_OPCODE(___, I32, ___, ___, 0, 0, 0x25, TableGet, "table.get", "") -WABT_OPCODE(___, I32, ___, ___, 0, 0, 0x26, TableSet, "table.set", "") -WABT_OPCODE(___, ___, I32, ___, 0, 0xfc, 0x0f, TableGrow, "table.grow", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0xfc, 0x10, TableSize, "table.size", "") -WABT_OPCODE(___, I32, ___, I32, 0, 0xfc, 0x11, TableFill, "table.fill", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xd0, RefNull, "ref.null", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xd1, RefIsNull, "ref.is_null", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0, 0xd2, RefFunc, "ref.func", "") - -/* Simd opcodes */ -WABT_OPCODE(V128, I32, ___, ___, 16, 0xfd, 0x00, V128Load, "v128.load", "") -WABT_OPCODE(V128, I32, ___, ___, 8, 0xfd, 0x01, V128Load8X8S, "v128.load8x8_s", "") -WABT_OPCODE(V128, I32, ___, ___, 8, 0xfd, 0x02, V128Load8X8U, "v128.load8x8_u", "") -WABT_OPCODE(V128, I32, ___, ___, 8, 0xfd, 0x03, V128Load16X4S, "v128.load16x4_s", "") -WABT_OPCODE(V128, I32, ___, ___, 8, 0xfd, 0x04, V128Load16X4U, "v128.load16x4_u", "") -WABT_OPCODE(V128, I32, ___, ___, 8, 0xfd, 0x05, V128Load32X2S, "v128.load32x2_s", "") -WABT_OPCODE(V128, I32, ___, ___, 8, 0xfd, 0x06, V128Load32X2U, "v128.load32x2_u", "") -WABT_OPCODE(V128, I32, ___, ___, 1, 0xfd, 0x07, V128Load8Splat, "v128.load8_splat", "") -WABT_OPCODE(V128, I32, ___, ___, 2, 0xfd, 0x08, V128Load16Splat, "v128.load16_splat", "") -WABT_OPCODE(V128, I32, ___, ___, 4, 0xfd, 0x09, V128Load32Splat, "v128.load32_splat", "") -WABT_OPCODE(V128, I32, ___, ___, 8, 0xfd, 0x0a, V128Load64Splat, "v128.load64_splat", "") -WABT_OPCODE(___, I32, V128, ___, 16, 0xfd, 0x0b, V128Store, "v128.store", "") -WABT_OPCODE(V128, ___, ___, ___, 0, 0xfd, 0x0c, V128Const, "v128.const", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x0d, I8X16Shuffle, "i8x16.shuffle", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x0e, I8X16Swizzle, "i8x16.swizzle", "") -WABT_OPCODE(V128, I32, ___, ___, 0, 0xfd, 0x0f, I8X16Splat, "i8x16.splat", "") -WABT_OPCODE(V128, I32, ___, ___, 0, 0xfd, 0x10, I16X8Splat, "i16x8.splat", "") -WABT_OPCODE(V128, I32, ___, ___, 0, 0xfd, 0x11, I32X4Splat, "i32x4.splat", "") -WABT_OPCODE(V128, I64, ___, ___, 0, 0xfd, 0x12, I64X2Splat, "i64x2.splat", "") -WABT_OPCODE(V128, F32, ___, ___, 0, 0xfd, 0x13, F32X4Splat, "f32x4.splat", "") -WABT_OPCODE(V128, F64, ___, ___, 0, 0xfd, 0x14, F64X2Splat, "f64x2.splat", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x15, I8X16ExtractLaneS, "i8x16.extract_lane_s", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x16, I8X16ExtractLaneU, "i8x16.extract_lane_u", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x17, I8X16ReplaceLane, "i8x16.replace_lane", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x18, I16X8ExtractLaneS, "i16x8.extract_lane_s", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x19, I16X8ExtractLaneU, "i16x8.extract_lane_u", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x1a, I16X8ReplaceLane, "i16x8.replace_lane", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x1b, I32X4ExtractLane, "i32x4.extract_lane", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x1c, I32X4ReplaceLane, "i32x4.replace_lane", "") -WABT_OPCODE(I64, V128, ___, ___, 0, 0xfd, 0x1d, I64X2ExtractLane, "i64x2.extract_lane", "") -WABT_OPCODE(V128, V128, I64, ___, 0, 0xfd, 0x1e, I64X2ReplaceLane, "i64x2.replace_lane", "") -WABT_OPCODE(F32, V128, ___, ___, 0, 0xfd, 0x1f, F32X4ExtractLane, "f32x4.extract_lane", "") -WABT_OPCODE(V128, V128, F32, ___, 0, 0xfd, 0x20, F32X4ReplaceLane, "f32x4.replace_lane", "") -WABT_OPCODE(F64, V128, ___, ___, 0, 0xfd, 0x21, F64X2ExtractLane, "f64x2.extract_lane", "") -WABT_OPCODE(V128, V128, F64, ___, 0, 0xfd, 0x22, F64X2ReplaceLane, "f64x2.replace_lane", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x23, I8X16Eq, "i8x16.eq", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x24, I8X16Ne, "i8x16.ne", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x25, I8X16LtS, "i8x16.lt_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x26, I8X16LtU, "i8x16.lt_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x27, I8X16GtS, "i8x16.gt_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x28, I8X16GtU, "i8x16.gt_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x29, I8X16LeS, "i8x16.le_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x2a, I8X16LeU, "i8x16.le_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x2b, I8X16GeS, "i8x16.ge_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x2c, I8X16GeU, "i8x16.ge_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x2d, I16X8Eq, "i16x8.eq", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x2e, I16X8Ne, "i16x8.ne", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x2f, I16X8LtS, "i16x8.lt_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x30, I16X8LtU, "i16x8.lt_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x31, I16X8GtS, "i16x8.gt_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x32, I16X8GtU, "i16x8.gt_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x33, I16X8LeS, "i16x8.le_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x34, I16X8LeU, "i16x8.le_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x35, I16X8GeS, "i16x8.ge_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x36, I16X8GeU, "i16x8.ge_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x37, I32X4Eq, "i32x4.eq", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x38, I32X4Ne, "i32x4.ne", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x39, I32X4LtS, "i32x4.lt_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x3a, I32X4LtU, "i32x4.lt_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x3b, I32X4GtS, "i32x4.gt_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x3c, I32X4GtU, "i32x4.gt_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x3d, I32X4LeS, "i32x4.le_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x3e, I32X4LeU, "i32x4.le_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x3f, I32X4GeS, "i32x4.ge_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x40, I32X4GeU, "i32x4.ge_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x41, F32X4Eq, "f32x4.eq", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x42, F32X4Ne, "f32x4.ne", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x43, F32X4Lt, "f32x4.lt", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x44, F32X4Gt, "f32x4.gt", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x45, F32X4Le, "f32x4.le", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x46, F32X4Ge, "f32x4.ge", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x47, F64X2Eq, "f64x2.eq", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x48, F64X2Ne, "f64x2.ne", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x49, F64X2Lt, "f64x2.lt", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x4a, F64X2Gt, "f64x2.gt", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x4b, F64X2Le, "f64x2.le", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x4c, F64X2Ge, "f64x2.ge", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x4d, V128Not, "v128.not", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x4e, V128And, "v128.and", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x4f, V128Andnot, "v128.andnot", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x50, V128Or, "v128.or", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x51, V128Xor, "v128.xor", "") -WABT_OPCODE(V128, V128, V128, V128, 0, 0xfd, 0x52, V128BitSelect, "v128.bitselect", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x53, V128AnyTrue, "v128.any_true", "") -WABT_OPCODE(V128, I32, V128, ___, 1, 0xfd, 0x54, V128Load8Lane, "v128.load8_lane", "") -WABT_OPCODE(V128, I32, V128, ___, 2, 0xfd, 0x55, V128Load16Lane, "v128.load16_lane", "") -WABT_OPCODE(V128, I32, V128, ___, 4, 0xfd, 0x56, V128Load32Lane, "v128.load32_lane", "") -WABT_OPCODE(V128, I32, V128, ___, 8, 0xfd, 0x57, V128Load64Lane, "v128.load64_lane", "") -WABT_OPCODE(___, I32, V128, ___, 1, 0xfd, 0x58, V128Store8Lane, "v128.store8_lane", "") -WABT_OPCODE(___, I32, V128, ___, 2, 0xfd, 0x59, V128Store16Lane, "v128.store16_lane", "") -WABT_OPCODE(___, I32, V128, ___, 4, 0xfd, 0x5a, V128Store32Lane, "v128.store32_lane", "") -WABT_OPCODE(___, I32, V128, ___, 8, 0xfd, 0x5b, V128Store64Lane, "v128.store64_lane", "") -WABT_OPCODE(V128, I32, ___, ___, 4, 0xfd, 0x5c, V128Load32Zero, "v128.load32_zero", "") -WABT_OPCODE(V128, I32, ___, ___, 8, 0xfd, 0x5d, V128Load64Zero, "v128.load64_zero", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x5e, F32X4DemoteF64X2Zero, "f32x4.demote_f64x2_zero", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x5f, F64X2PromoteLowF32X4, "f64x2.promote_low_f32x4", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x60, I8X16Abs, "i8x16.abs", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x61, I8X16Neg, "i8x16.neg", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x62, I8X16Popcnt, "i8x16.popcnt", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x63, I8X16AllTrue, "i8x16.all_true", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x64, I8X16Bitmask, "i8x16.bitmask", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x65, I8X16NarrowI16X8S, "i8x16.narrow_i16x8_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x66, I8X16NarrowI16X8U, "i8x16.narrow_i16x8_u", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x6b, I8X16Shl, "i8x16.shl", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x6c, I8X16ShrS, "i8x16.shr_s", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x6d, I8X16ShrU, "i8x16.shr_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x6e, I8X16Add, "i8x16.add", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x6f, I8X16AddSatS, "i8x16.add_sat_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x70, I8X16AddSatU, "i8x16.add_sat_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x71, I8X16Sub, "i8x16.sub", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x72, I8X16SubSatS, "i8x16.sub_sat_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x73, I8X16SubSatU, "i8x16.sub_sat_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x76, I8X16MinS, "i8x16.min_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x77, I8X16MinU, "i8x16.min_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x78, I8X16MaxS, "i8x16.max_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x79, I8X16MaxU, "i8x16.max_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x7b, I8X16AvgrU, "i8x16.avgr_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x7c, I16X8ExtaddPairwiseI8X16S, "i16x8.extadd_pairwise_i8x16_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x7d, I16X8ExtaddPairwiseI8X16U, "i16x8.extadd_pairwise_i8x16_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x7e, I32X4ExtaddPairwiseI16X8S, "i32x4.extadd_pairwise_i16x8_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x7f, I32X4ExtaddPairwiseI16X8U, "i32x4.extadd_pairwise_i16x8_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x80, I16X8Abs, "i16x8.abs", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x81, I16X8Neg, "i16x8.neg", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x82, I16X8Q15mulrSatS, "i16x8.q15mulr_sat_s", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x83, I16X8AllTrue, "i16x8.all_true", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0x84, I16X8Bitmask, "i16x8.bitmask", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x85, I16X8NarrowI32X4S, "i16x8.narrow_i32x4_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x86, I16X8NarrowI32X4U, "i16x8.narrow_i32x4_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x87, I16X8ExtendLowI8X16S, "i16x8.extend_low_i8x16_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x88, I16X8ExtendHighI8X16S, "i16x8.extend_high_i8x16_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x89, I16X8ExtendLowI8X16U, "i16x8.extend_low_i8x16_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x8a, I16X8ExtendHighI8X16U, "i16x8.extend_high_i8x16_u", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x8b, I16X8Shl, "i16x8.shl", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x8c, I16X8ShrS, "i16x8.shr_s", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0x8d, I16X8ShrU, "i16x8.shr_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x8e, I16X8Add, "i16x8.add", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x8f, I16X8AddSatS, "i16x8.add_sat_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x90, I16X8AddSatU, "i16x8.add_sat_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x91, I16X8Sub, "i16x8.sub", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x92, I16X8SubSatS, "i16x8.sub_sat_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x93, I16X8SubSatU, "i16x8.sub_sat_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x95, I16X8Mul, "i16x8.mul", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x96, I16X8MinS, "i16x8.min_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x97, I16X8MinU, "i16x8.min_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x98, I16X8MaxS, "i16x8.max_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x99, I16X8MaxU, "i16x8.max_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x9b, I16X8AvgrU, "i16x8.avgr_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x9c, I16X8ExtmulLowI8X16S, "i16x8.extmul_low_i8x16_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x9d, I16X8ExtmulHighI8X16S, "i16x8.extmul_high_i8x16_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x9e, I16X8ExtmulLowI8X16U, "i16x8.extmul_low_i8x16_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0x9f, I16X8ExtmulHighI8X16U, "i16x8.extmul_high_i8x16_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xa0, I32X4Abs, "i32x4.abs", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xa1, I32X4Neg, "i32x4.neg", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0xa3, I32X4AllTrue, "i32x4.all_true", "") -WABT_OPCODE(I32, V128, ___, ___, 0, 0xfd, 0xa4, I32X4Bitmask, "i32x4.bitmask", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xa7, I32X4ExtendLowI16X8S, "i32x4.extend_low_i16x8_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xa8, I32X4ExtendHighI16X8S, "i32x4.extend_high_i16x8_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xa9, I32X4ExtendLowI16X8U, "i32x4.extend_low_i16x8_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xaa, I32X4ExtendHighI16X8U, "i32x4.extend_high_i16x8_u", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0xab, I32X4Shl, "i32x4.shl", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0xac, I32X4ShrS, "i32x4.shr_s", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0xad, I32X4ShrU, "i32x4.shr_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xae, I32X4Add, "i32x4.add", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xb1, I32X4Sub, "i32x4.sub", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xb5, I32X4Mul, "i32x4.mul", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xb6, I32X4MinS, "i32x4.min_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xb7, I32X4MinU, "i32x4.min_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xb8, I32X4MaxS, "i32x4.max_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xb9, I32X4MaxU, "i32x4.max_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xba, I32X4DotI16X8S, "i32x4.dot_i16x8_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xbc, I32X4ExtmulLowI16X8S, "i32x4.extmul_low_i16x8_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xbd, I32X4ExtmulHighI16X8S, "i32x4.extmul_high_i16x8_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xbe, I32X4ExtmulLowI16X8U, "i32x4.extmul_low_i16x8_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xbf, I32X4ExtmulHighI16X8U, "i32x4.extmul_high_i16x8_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xc0, I64X2Abs, "i64x2.abs", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xc1, I64X2Neg, "i64x2.neg", "") -WABT_OPCODE( I32, V128, ___, ___, 0, 0xfd, 0xc3, I64X2AllTrue, "i64x2.all_true", "") -WABT_OPCODE( I32, V128, ___, ___, 0, 0xfd, 0xc4, I64X2Bitmask, "i64x2.bitmask", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xc7, I64X2ExtendLowI32X4S, "i64x2.extend_low_i32x4_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xc8, I64X2ExtendHighI32X4S, "i64x2.extend_high_i32x4_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xc9, I64X2ExtendLowI32X4U, "i64x2.extend_low_i32x4_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xca, I64X2ExtendHighI32X4U, "i64x2.extend_high_i32x4_u", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0xcb, I64X2Shl, "i64x2.shl", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0xcc, I64X2ShrS, "i64x2.shr_s", "") -WABT_OPCODE(V128, V128, I32, ___, 0, 0xfd, 0xcd, I64X2ShrU, "i64x2.shr_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xce, I64X2Add, "i64x2.add", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xd1, I64X2Sub, "i64x2.sub", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xd5, I64X2Mul, "i64x2.mul", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xd6, I64X2Eq, "i64x2.eq", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xd7, I64X2Ne, "i64x2.ne", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xd8, I64X2LtS, "i64x2.lt_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xd9, I64X2GtS, "i64x2.gt_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xda, I64X2LeS, "i64x2.le_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xdb, I64X2GeS, "i64x2.ge_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xdc, I64X2ExtmulLowI32X4S, "i64x2.extmul_low_i32x4_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xdd, I64X2ExtmulHighI32X4S, "i64x2.extmul_high_i32x4_s", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xde, I64X2ExtmulLowI32X4U, "i64x2.extmul_low_i32x4_u", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xdf, I64X2ExtmulHighI32X4U, "i64x2.extmul_high_i32x4_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x67, F32X4Ceil, "f32x4.ceil", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x68, F32X4Floor, "f32x4.floor", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x69, F32X4Trunc, "f32x4.trunc", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x6a, F32X4Nearest, "f32x4.nearest", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x74, F64X2Ceil, "f64x2.ceil", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x75, F64X2Floor, "f64x2.floor", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x7a, F64X2Trunc, "f64x2.trunc", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0x94, F64X2Nearest, "f64x2.nearest", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xe0, F32X4Abs, "f32x4.abs", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xe1, F32X4Neg, "f32x4.neg", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xe3, F32X4Sqrt, "f32x4.sqrt", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xe4, F32X4Add, "f32x4.add", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xe5, F32X4Sub, "f32x4.sub", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xe6, F32X4Mul, "f32x4.mul", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xe7, F32X4Div, "f32x4.div", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xe8, F32X4Min, "f32x4.min", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xe9, F32X4Max, "f32x4.max", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xea, F32X4PMin, "f32x4.pmin", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xeb, F32X4PMax, "f32x4.pmax", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xec, F64X2Abs, "f64x2.abs", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xed, F64X2Neg, "f64x2.neg", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xef, F64X2Sqrt, "f64x2.sqrt", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xf0, F64X2Add, "f64x2.add", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xf1, F64X2Sub, "f64x2.sub", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xf2, F64X2Mul, "f64x2.mul", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xf3, F64X2Div, "f64x2.div", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xf4, F64X2Min, "f64x2.min", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xf5, F64X2Max, "f64x2.max", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xf6, F64X2PMin, "f64x2.pmin", "") -WABT_OPCODE(V128, V128, V128, ___, 0, 0xfd, 0xf7, F64X2PMax, "f64x2.pmax", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xf8, I32X4TruncSatF32X4S,"i32x4.trunc_sat_f32x4_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xf9, I32X4TruncSatF32X4U,"i32x4.trunc_sat_f32x4_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xfa, F32X4ConvertI32X4S, "f32x4.convert_i32x4_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xfb, F32X4ConvertI32X4U, "f32x4.convert_i32x4_u", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xfc, I32X4TruncSatF64X2SZero, "i32x4.trunc_sat_f64x2_s_zero", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xfd, I32X4TruncSatF64X2UZero, "i32x4.trunc_sat_f64x2_u_zero", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xfe, F64X2ConvertLowI32X4S, "f64x2.convert_low_i32x4_s", "") -WABT_OPCODE(V128, V128, ___, ___, 0, 0xfd, 0xff, F64X2ConvertLowI32X4U, "f64x2.convert_low_i32x4_u", "") - -/* Thread opcodes (--enable-threads) */ -WABT_OPCODE(I32, I32, I32, ___, 4, 0xfe, 0x00, MemoryAtomicNotify, "memory.atomic.notify", "") -WABT_OPCODE(I32, I32, I32, I64, 4, 0xfe, 0x01, MemoryAtomicWait32, "memory.atomic.wait32", "") -WABT_OPCODE(I32, I32, I64, I64, 8, 0xfe, 0x02, MemoryAtomicWait64, "memory.atomic.wait64", "") -WABT_OPCODE(___, ___, ___, ___, 0, 0xfe, 0x03, AtomicFence, "atomic.fence", "") -WABT_OPCODE(I32, I32, ___, ___, 4, 0xfe, 0x10, I32AtomicLoad, "i32.atomic.load", "") -WABT_OPCODE(I64, I32, ___, ___, 8, 0xfe, 0x11, I64AtomicLoad, "i64.atomic.load", "") -WABT_OPCODE(I32, I32, ___, ___, 1, 0xfe, 0x12, I32AtomicLoad8U, "i32.atomic.load8_u", "") -WABT_OPCODE(I32, I32, ___, ___, 2, 0xfe, 0x13, I32AtomicLoad16U, "i32.atomic.load16_u", "") -WABT_OPCODE(I64, I32, ___, ___, 1, 0xfe, 0x14, I64AtomicLoad8U, "i64.atomic.load8_u", "") -WABT_OPCODE(I64, I32, ___, ___, 2, 0xfe, 0x15, I64AtomicLoad16U, "i64.atomic.load16_u", "") -WABT_OPCODE(I64, I32, ___, ___, 4, 0xfe, 0x16, I64AtomicLoad32U, "i64.atomic.load32_u", "") -WABT_OPCODE(___, I32, I32, ___, 4, 0xfe, 0x17, I32AtomicStore, "i32.atomic.store", "") -WABT_OPCODE(___, I32, I64, ___, 8, 0xfe, 0x18, I64AtomicStore, "i64.atomic.store", "") -WABT_OPCODE(___, I32, I32, ___, 1, 0xfe, 0x19, I32AtomicStore8, "i32.atomic.store8", "") -WABT_OPCODE(___, I32, I32, ___, 2, 0xfe, 0x1a, I32AtomicStore16, "i32.atomic.store16", "") -WABT_OPCODE(___, I32, I64, ___, 1, 0xfe, 0x1b, I64AtomicStore8, "i64.atomic.store8", "") -WABT_OPCODE(___, I32, I64, ___, 2, 0xfe, 0x1c, I64AtomicStore16, "i64.atomic.store16", "") -WABT_OPCODE(___, I32, I64, ___, 4, 0xfe, 0x1d, I64AtomicStore32, "i64.atomic.store32", "") -WABT_OPCODE(I32, I32, I32, ___, 4, 0xfe, 0x1e, I32AtomicRmwAdd, "i32.atomic.rmw.add", "") -WABT_OPCODE(I64, I32, I64, ___, 8, 0xfe, 0x1f, I64AtomicRmwAdd, "i64.atomic.rmw.add", "") -WABT_OPCODE(I32, I32, I32, ___, 1, 0xfe, 0x20, I32AtomicRmw8AddU, "i32.atomic.rmw8.add_u", "") -WABT_OPCODE(I32, I32, I32, ___, 2, 0xfe, 0x21, I32AtomicRmw16AddU, "i32.atomic.rmw16.add_u", "") -WABT_OPCODE(I64, I32, I64, ___, 1, 0xfe, 0x22, I64AtomicRmw8AddU, "i64.atomic.rmw8.add_u", "") -WABT_OPCODE(I64, I32, I64, ___, 2, 0xfe, 0x23, I64AtomicRmw16AddU, "i64.atomic.rmw16.add_u", "") -WABT_OPCODE(I64, I32, I64, ___, 4, 0xfe, 0x24, I64AtomicRmw32AddU, "i64.atomic.rmw32.add_u", "") -WABT_OPCODE(I32, I32, I32, ___, 4, 0xfe, 0x25, I32AtomicRmwSub, "i32.atomic.rmw.sub", "") -WABT_OPCODE(I64, I32, I64, ___, 8, 0xfe, 0x26, I64AtomicRmwSub, "i64.atomic.rmw.sub", "") -WABT_OPCODE(I32, I32, I32, ___, 1, 0xfe, 0x27, I32AtomicRmw8SubU, "i32.atomic.rmw8.sub_u", "") -WABT_OPCODE(I32, I32, I32, ___, 2, 0xfe, 0x28, I32AtomicRmw16SubU, "i32.atomic.rmw16.sub_u", "") -WABT_OPCODE(I64, I32, I64, ___, 1, 0xfe, 0x29, I64AtomicRmw8SubU, "i64.atomic.rmw8.sub_u", "") -WABT_OPCODE(I64, I32, I64, ___, 2, 0xfe, 0x2a, I64AtomicRmw16SubU, "i64.atomic.rmw16.sub_u", "") -WABT_OPCODE(I64, I32, I64, ___, 4, 0xfe, 0x2b, I64AtomicRmw32SubU, "i64.atomic.rmw32.sub_u", "") -WABT_OPCODE(I32, I32, I32, ___, 4, 0xfe, 0x2c, I32AtomicRmwAnd, "i32.atomic.rmw.and", "") -WABT_OPCODE(I64, I32, I64, ___, 8, 0xfe, 0x2d, I64AtomicRmwAnd, "i64.atomic.rmw.and", "") -WABT_OPCODE(I32, I32, I32, ___, 1, 0xfe, 0x2e, I32AtomicRmw8AndU, "i32.atomic.rmw8.and_u", "") -WABT_OPCODE(I32, I32, I32, ___, 2, 0xfe, 0x2f, I32AtomicRmw16AndU, "i32.atomic.rmw16.and_u", "") -WABT_OPCODE(I64, I32, I64, ___, 1, 0xfe, 0x30, I64AtomicRmw8AndU, "i64.atomic.rmw8.and_u", "") -WABT_OPCODE(I64, I32, I64, ___, 2, 0xfe, 0x31, I64AtomicRmw16AndU, "i64.atomic.rmw16.and_u", "") -WABT_OPCODE(I64, I32, I64, ___, 4, 0xfe, 0x32, I64AtomicRmw32AndU, "i64.atomic.rmw32.and_u", "") -WABT_OPCODE(I32, I32, I32, ___, 4, 0xfe, 0x33, I32AtomicRmwOr, "i32.atomic.rmw.or", "") -WABT_OPCODE(I64, I32, I64, ___, 8, 0xfe, 0x34, I64AtomicRmwOr, "i64.atomic.rmw.or", "") -WABT_OPCODE(I32, I32, I32, ___, 1, 0xfe, 0x35, I32AtomicRmw8OrU, "i32.atomic.rmw8.or_u", "") -WABT_OPCODE(I32, I32, I32, ___, 2, 0xfe, 0x36, I32AtomicRmw16OrU, "i32.atomic.rmw16.or_u", "") -WABT_OPCODE(I64, I32, I64, ___, 1, 0xfe, 0x37, I64AtomicRmw8OrU, "i64.atomic.rmw8.or_u", "") -WABT_OPCODE(I64, I32, I64, ___, 2, 0xfe, 0x38, I64AtomicRmw16OrU, "i64.atomic.rmw16.or_u", "") -WABT_OPCODE(I64, I32, I64, ___, 4, 0xfe, 0x39, I64AtomicRmw32OrU, "i64.atomic.rmw32.or_u", "") -WABT_OPCODE(I32, I32, I32, ___, 4, 0xfe, 0x3a, I32AtomicRmwXor, "i32.atomic.rmw.xor", "") -WABT_OPCODE(I64, I32, I64, ___, 8, 0xfe, 0x3b, I64AtomicRmwXor, "i64.atomic.rmw.xor", "") -WABT_OPCODE(I32, I32, I32, ___, 1, 0xfe, 0x3c, I32AtomicRmw8XorU, "i32.atomic.rmw8.xor_u", "") -WABT_OPCODE(I32, I32, I32, ___, 2, 0xfe, 0x3d, I32AtomicRmw16XorU, "i32.atomic.rmw16.xor_u", "") -WABT_OPCODE(I64, I32, I64, ___, 1, 0xfe, 0x3e, I64AtomicRmw8XorU, "i64.atomic.rmw8.xor_u", "") -WABT_OPCODE(I64, I32, I64, ___, 2, 0xfe, 0x3f, I64AtomicRmw16XorU, "i64.atomic.rmw16.xor_u", "") -WABT_OPCODE(I64, I32, I64, ___, 4, 0xfe, 0x40, I64AtomicRmw32XorU, "i64.atomic.rmw32.xor_u", "") -WABT_OPCODE(I32, I32, I32, ___, 4, 0xfe, 0x41, I32AtomicRmwXchg, "i32.atomic.rmw.xchg", "") -WABT_OPCODE(I64, I32, I64, ___, 8, 0xfe, 0x42, I64AtomicRmwXchg, "i64.atomic.rmw.xchg", "") -WABT_OPCODE(I32, I32, I32, ___, 1, 0xfe, 0x43, I32AtomicRmw8XchgU, "i32.atomic.rmw8.xchg_u", "") -WABT_OPCODE(I32, I32, I32, ___, 2, 0xfe, 0x44, I32AtomicRmw16XchgU, "i32.atomic.rmw16.xchg_u", "") -WABT_OPCODE(I64, I32, I64, ___, 1, 0xfe, 0x45, I64AtomicRmw8XchgU, "i64.atomic.rmw8.xchg_u", "") -WABT_OPCODE(I64, I32, I64, ___, 2, 0xfe, 0x46, I64AtomicRmw16XchgU, "i64.atomic.rmw16.xchg_u", "") -WABT_OPCODE(I64, I32, I64, ___, 4, 0xfe, 0x47, I64AtomicRmw32XchgU, "i64.atomic.rmw32.xchg_u", "") -WABT_OPCODE(I32, I32, I32, I32, 4, 0xfe, 0x48, I32AtomicRmwCmpxchg, "i32.atomic.rmw.cmpxchg", "") -WABT_OPCODE(I64, I32, I64, I64, 8, 0xfe, 0x49, I64AtomicRmwCmpxchg, "i64.atomic.rmw.cmpxchg", "") -WABT_OPCODE(I32, I32, I32, I32, 1, 0xfe, 0x4a, I32AtomicRmw8CmpxchgU, "i32.atomic.rmw8.cmpxchg_u", "") -WABT_OPCODE(I32, I32, I32, I32, 2, 0xfe, 0x4b, I32AtomicRmw16CmpxchgU, "i32.atomic.rmw16.cmpxchg_u", "") -WABT_OPCODE(I64, I32, I64, I64, 1, 0xfe, 0x4c, I64AtomicRmw8CmpxchgU, "i64.atomic.rmw8.cmpxchg_u", "") -WABT_OPCODE(I64, I32, I64, I64, 2, 0xfe, 0x4d, I64AtomicRmw16CmpxchgU, "i64.atomic.rmw16.cmpxchg_u", "") -WABT_OPCODE(I64, I32, I64, I64, 4, 0xfe, 0x4e, I64AtomicRmw32CmpxchgU, "i64.atomic.rmw32.cmpxchg_u", "") diff --git a/src/opcode.h b/src/opcode.h deleted file mode 100644 index 486af52a..00000000 --- a/src/opcode.h +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_OPCODE_H_ -#define WABT_OPCODE_H_ - -#include <vector> - -#include "src/common.h" -#include "src/leb128.h" -#include "src/opcode-code-table.h" - -namespace wabt { - -class Features; - -struct Opcode { - // Opcode enumerations. - // - // NOTE: this enum does not match the binary encoding. - // - enum Enum : uint32_t { -#define WABT_OPCODE(rtype, type1, type2, type3, mem_size, prefix, code, Name, \ - text, decomp) \ - Name, -#include "src/opcode.def" -#undef WABT_OPCODE - Invalid, - }; - -// Static opcode objects. -#define WABT_OPCODE(rtype, type1, type2, type3, mem_size, prefix, code, Name, \ - text, decomp) \ - static Opcode Name##_Opcode; -#include "src/opcode.def" -#undef WABT_OPCODE - - Opcode() = default; // Provided so Opcode can be member of a union. - Opcode(Enum e) : enum_(e) {} - operator Enum() const { return enum_; } - - static Opcode FromCode(uint32_t); - static Opcode FromCode(uint8_t prefix, uint32_t code); - bool HasPrefix() const { return GetInfo().prefix != 0; } - uint8_t GetPrefix() const { return GetInfo().prefix; } - uint32_t GetCode() const { return GetInfo().code; } - size_t GetLength() const { return GetBytes().size(); } - const char* GetName() const { return GetInfo().name; } - const char* GetDecomp() const { - return *GetInfo().decomp ? GetInfo().decomp : GetInfo().name; - } - Type GetResultType() const { return GetInfo().result_type; } - Type GetParamType1() const { return GetInfo().param_types[0]; } - Type GetParamType2() const { return GetInfo().param_types[1]; } - Type GetParamType3() const { return GetInfo().param_types[2]; } - Type GetParamType(int n) const { return GetInfo().param_types[n - 1]; } - Address GetMemorySize() const { return GetInfo().memory_size; } - - // If this is a load/store op, the type depends on the memory used. - Type GetMemoryParam(Type param, - const Limits* limits, - bool has_address_operands) { - return limits && limits->is_64 && has_address_operands ? Type(Type::I64) - : param; - } - - // Get the byte sequence for this opcode, including prefix. - std::vector<uint8_t> GetBytes() const; - - // Get the lane count of an extract/replace simd op. - uint32_t GetSimdLaneCount() const; - - // Return 1 if |alignment| matches the alignment of |opcode|, or if - // |alignment| is WABT_USE_NATURAL_ALIGNMENT. - bool IsNaturallyAligned(Address alignment) const; - - // If |alignment| is WABT_USE_NATURAL_ALIGNMENT, return the alignment of - // |opcode|, else return |alignment|. - Address GetAlignment(Address alignment) const; - - static bool IsPrefixByte(uint8_t byte) { - return byte == kMathPrefix || byte == kThreadsPrefix || byte == kSimdPrefix; - } - - bool IsEnabled(const Features& features) const; - bool IsInvalid() const { return enum_ >= Invalid; } - - private: - static const uint32_t kMathPrefix = 0xfc; - static const uint32_t kThreadsPrefix = 0xfe; - static const uint32_t kSimdPrefix = 0xfd; - - struct Info { - const char* name; - const char* decomp; - Type result_type; - Type param_types[3]; - Address memory_size; - uint8_t prefix; - uint32_t code; - uint32_t prefix_code; // See PrefixCode below. Used for fast lookup. - }; - - static uint32_t PrefixCode(uint8_t prefix, uint32_t code) { - // For now, 8 bits is enough for all codes. - if (code >= 0x100) { - // Clamp to 0xff, since we know that it is an invalid code. - code = 0xff; - } - return (prefix << 8) | code; - } - - // The Opcode struct only stores an enumeration (Opcode::Enum) of all valid - // opcodes, densely packed. We want to be able to store invalid opcodes as - // well, for display to the user. To encode these, we use PrefixCode() to - // generate a uint32_t of the prefix/code pair, then negate the value so it - // doesn't overlap with the valid enum values. The negation is done using - // `~code + 1` since prefix_code is unsigned, and MSVC warns if you use - on - // an unsigned value. - // - // | 0 | Opcode::Invalid | INT32_MAX+1 UINT32_MAX | - // |---------------|-------------------------|---------------------------| - // | valid opcodes | unused space | invalid opcodes | - // - static Enum EncodeInvalidOpcode(uint32_t prefix_code) { - Enum result = static_cast<Enum>(~prefix_code + 1); - assert(result >= Invalid); - return result; - } - - static void DecodeInvalidOpcode(Enum e, - uint8_t* out_prefix, - uint32_t* out_code) { - uint32_t prefix_code = ~static_cast<uint32_t>(e) + 1; - *out_prefix = prefix_code >> 8; - *out_code = prefix_code & 0xff; - } - - Info GetInfo() const; - static Info infos_[]; - - Enum enum_; -}; - -// static -inline Opcode Opcode::FromCode(uint32_t code) { - return FromCode(0, code); -} - -// static -inline Opcode Opcode::FromCode(uint8_t prefix, uint32_t code) { - uint32_t prefix_code = PrefixCode(prefix, code); - - if (WABT_LIKELY(prefix_code < WABT_ARRAY_SIZE(WabtOpcodeCodeTable))) { - uint32_t value = WabtOpcodeCodeTable[prefix_code]; - // The default value in the table is 0. That's a valid value, but only if - // the code is 0 (for nop). - if (WABT_LIKELY(value != 0 || code == 0)) { - return Opcode(static_cast<Enum>(value)); - } - } - - return Opcode(EncodeInvalidOpcode(prefix_code)); -} - -} // namespace wabt - -#endif // WABT_OPCODE_H_ diff --git a/src/option-parser.cc b/src/option-parser.cc index fe06fe94..9c799c37 100644 --- a/src/option-parser.cc +++ b/src/option-parser.cc @@ -14,13 +14,13 @@ * limitations under the License. */ -#include "src/option-parser.h" +#include "wabt/option-parser.h" #include <cstdarg> #include <cstdio> #include <cstring> -#include "config.h" +#include "wabt/config.h" #if HAVE_ALLOCA #include <alloca.h> diff --git a/src/option-parser.h b/src/option-parser.h deleted file mode 100644 index 051ce784..00000000 --- a/src/option-parser.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_OPTION_PARSER_H_ -#define WABT_OPTION_PARSER_H_ - -#include <functional> -#include <string> -#include <vector> - -#include "src/common.h" - -namespace wabt { - -class OptionParser { - public: - enum class HasArgument { No, Yes }; - enum class ArgumentCount { One, OneOrMore, ZeroOrMore }; - - struct Option; - typedef std::function<void(const char*)> Callback; - typedef std::function<void()> NullCallback; - - struct Option { - Option(char short_name, - const std::string& long_name, - const std::string& metavar, - HasArgument has_argument, - const std::string& help, - const Callback&); - - char short_name; - std::string long_name; - std::string metavar; - bool has_argument; - std::string help; - Callback callback; - }; - - struct Argument { - Argument(const std::string& name, ArgumentCount, const Callback&); - - std::string name; - ArgumentCount count; - Callback callback; - int handled_count = 0; - }; - - explicit OptionParser(const char* program_name, const char* description); - - void AddOption(const Option&); - void AddArgument(const std::string& name, ArgumentCount, const Callback&); - void SetErrorCallback(const Callback&); - void Parse(int argc, char* argv[]); - void PrintHelp(); - - // Helper functions. - void AddOption(char short_name, - const char* long_name, - const char* help, - const NullCallback&); - void AddOption(const char* long_name, const char* help, const NullCallback&); - void AddOption(char short_name, - const char* long_name, - const char* metavar, - const char* help, - const Callback&); - - private: - static int Match(const char* s, const std::string& full, bool has_argument); - void WABT_PRINTF_FORMAT(2, 3) Errorf(const char* format, ...); - void HandleArgument(size_t* arg_index, const char* arg_value); - - // Print the error and exit(1). - void DefaultError(const std::string&); - - std::string program_name_; - std::string description_; - std::vector<Option> options_; - std::vector<Argument> arguments_; - Callback on_error_; -}; - -} // namespace wabt - -#endif /* WABT_OPTION_PARSER_H_ */ diff --git a/src/range.h b/src/range.h deleted file mode 100644 index fa0310ee..00000000 --- a/src/range.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_RANGE_H_ -#define WABT_RANGE_H_ - -namespace wabt { - -template <typename T> -struct Range { - Range() : start(0), end(0) {} - Range(T start, T end) : start(start), end(end) {} - T start; - T end; - - T size() const { return end - start; } -}; - -typedef Range<Offset> OffsetRange; -typedef Range<int> ColumnRange; - -} // namespace wabt - -#endif // WABT_RANGE_H_ diff --git a/src/resolve-names.cc b/src/resolve-names.cc index fcd274c9..9f0b3b02 100644 --- a/src/resolve-names.cc +++ b/src/resolve-names.cc @@ -14,15 +14,15 @@ * limitations under the License. */ -#include "src/resolve-names.h" +#include "wabt/resolve-names.h" #include <cassert> #include <cstdio> -#include "src/cast.h" -#include "src/expr-visitor.h" -#include "src/ir.h" -#include "src/wast-lexer.h" +#include "wabt/cast.h" +#include "wabt/expr-visitor.h" +#include "wabt/ir.h" +#include "wabt/wast-lexer.h" namespace wabt { diff --git a/src/resolve-names.h b/src/resolve-names.h deleted file mode 100644 index 04f2115c..00000000 --- a/src/resolve-names.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_RESOLVE_NAMES_H_ -#define WABT_RESOLVE_NAMES_H_ - -#include "src/common.h" -#include "src/error.h" - -namespace wabt { - -struct Module; -struct Script; - -Result ResolveNamesModule(Module*, Errors*); -Result ResolveNamesScript(Script*, Errors*); - -} // namespace wabt - -#endif /* WABT_RESOLVE_NAMES_H_ */ diff --git a/src/result.h b/src/result.h deleted file mode 100644 index a40faab7..00000000 --- a/src/result.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_RESULT_H_ -#define WABT_RESULT_H_ - -namespace wabt { - -struct Result { - enum Enum { - Ok, - Error, - }; - - Result() : Result(Ok) {} - Result(Enum e) : enum_(e) {} - operator Enum() const { return enum_; } - Result& operator|=(Result rhs); - - private: - Enum enum_; -}; - -inline Result operator|(Result lhs, Result rhs) { - return (lhs == Result::Error || rhs == Result::Error) ? Result::Error - : Result::Ok; -} - -inline Result& Result::operator|=(Result rhs) { - enum_ = *this | rhs; - return *this; -} - -inline bool Succeeded(Result result) { - return result == Result::Ok; -} -inline bool Failed(Result result) { - return result == Result::Error; -} - -#define CHECK_RESULT(expr) \ - do { \ - if (Failed(expr)) { \ - return ::wabt::Result::Error; \ - } \ - } while (0) - -} // namespace wabt - -#endif // WABT_RESULT_H_ diff --git a/src/shared-validator.cc b/src/shared-validator.cc index 6513f2d7..0bff3266 100644 --- a/src/shared-validator.cc +++ b/src/shared-validator.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/shared-validator.h" +#include "wabt/shared-validator.h" #include <algorithm> #include <cinttypes> diff --git a/src/shared-validator.h b/src/shared-validator.h deleted file mode 100644 index 76d1b6b2..00000000 --- a/src/shared-validator.h +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright 2020 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_SHARED_VALIDATOR_H_ -#define WABT_SHARED_VALIDATOR_H_ - -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "src/common.h" -#include "src/error.h" -#include "src/feature.h" -#include "src/ir.h" -#include "src/opcode.h" -#include "src/type-checker.h" - -#include "src/binary-reader.h" // For TypeMut. - -namespace wabt { - -struct ValidateOptions { - ValidateOptions() = default; - ValidateOptions(const Features& features) : features(features) {} - - Features features; -}; - -class SharedValidator { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(SharedValidator); - SharedValidator(Errors*, const ValidateOptions& options); - - // TODO: Move into SharedValidator? - using Label = TypeChecker::Label; - size_t type_stack_size() const { return typechecker_.type_stack_size(); } - Result GetLabel(Index depth, Label** out_label) { - return typechecker_.GetLabel(depth, out_label); - } - Result GetCatchCount(Index depth, Index* out_count) { - return typechecker_.GetCatchCount(depth, out_count); - } - - Result WABT_PRINTF_FORMAT(3, 4) - PrintError(const Location& loc, const char* fmt, ...); - - void OnTypecheckerError(const char* msg); - - Index GetLocalCount() const; - - Result EndModule(); - - Result OnFuncType(const Location&, - Index param_count, - const Type* param_types, - Index result_count, - const Type* result_types, - Index type_index); - Result OnStructType(const Location&, Index field_count, TypeMut* fields); - Result OnArrayType(const Location&, TypeMut field); - - Result OnFunction(const Location&, Var sig_var); - Result OnTable(const Location&, Type elem_type, const Limits&); - Result OnMemory(const Location&, const Limits&); - Result OnGlobalImport(const Location&, Type type, bool mutable_); - Result OnGlobal(const Location&, Type type, bool mutable_); - Result OnTag(const Location&, Var sig_var); - - Result OnExport(const Location&, - ExternalKind, - Var item_var, - std::string_view name); - - Result OnStart(const Location&, Var func_var); - - Result OnElemSegment(const Location&, Var table_var, SegmentKind); - void OnElemSegmentElemType(Type elem_type); - Result OnElemSegmentElemExpr_RefNull(const Location&, Type type); - Result OnElemSegmentElemExpr_RefFunc(const Location&, Var func_var); - Result OnElemSegmentElemExpr_Other(const Location&); - - void OnDataCount(Index count); - Result OnDataSegment(const Location&, Var memory_var, SegmentKind); - - Result BeginInitExpr(const Location&, Type type); - Result EndInitExpr(); - - Result BeginFunctionBody(const Location&, Index func_index); - Result EndFunctionBody(const Location&); - Result OnLocalDecl(const Location&, Index count, Type type); - - Result OnAtomicFence(const Location&, uint32_t consistency_model); - Result OnAtomicLoad(const Location&, Opcode, Var memidx, Address align); - Result OnAtomicNotify(const Location&, Opcode, Var memidx, Address align); - Result OnAtomicRmwCmpxchg(const Location&, Opcode, Var memidx, Address align); - Result OnAtomicRmw(const Location&, Opcode, Var memidx, Address align); - Result OnAtomicStore(const Location&, Opcode, Var memidx, Address align); - Result OnAtomicWait(const Location&, Opcode, Var memidx, Address align); - Result OnBinary(const Location&, Opcode); - Result OnBlock(const Location&, Type sig_type); - Result OnBr(const Location&, Var depth); - Result OnBrIf(const Location&, Var depth); - Result BeginBrTable(const Location&); - Result OnBrTableTarget(const Location&, Var depth); - Result EndBrTable(const Location&); - Result OnCall(const Location&, Var func_var); - Result OnCallIndirect(const Location&, Var sig_var, Var table_var); - Result OnCallRef(const Location&, Index* function_type_index); - Result OnCatch(const Location&, Var tag_var, bool is_catch_all); - Result OnCompare(const Location&, Opcode); - Result OnConst(const Location&, Type); - Result OnConvert(const Location&, Opcode); - Result OnDataDrop(const Location&, Var segment_var); - Result OnDelegate(const Location&, Var depth); - Result OnDrop(const Location&); - Result OnElemDrop(const Location&, Var segment_var); - Result OnElse(const Location&); - Result OnEnd(const Location&); - Result OnGlobalGet(const Location&, Var); - Result OnGlobalSet(const Location&, Var); - Result OnIf(const Location&, Type sig_type); - Result OnLoad(const Location&, Opcode, Var memidx, Address align); - Result OnLoadSplat(const Location&, Opcode, Var memidx, Address align); - Result OnLoadZero(const Location&, Opcode, Var memidx, Address align); - Result OnLocalGet(const Location&, Var); - Result OnLocalSet(const Location&, Var); - Result OnLocalTee(const Location&, Var); - Result OnLoop(const Location&, Type sig_type); - Result OnMemoryCopy(const Location&, Var srcmemidx, Var destmemidx); - Result OnMemoryFill(const Location&, Var memidx); - Result OnMemoryGrow(const Location&, Var memidx); - Result OnMemoryInit(const Location&, Var segment_var, Var memidx); - Result OnMemorySize(const Location&, Var memidx); - Result OnNop(const Location&); - Result OnRefFunc(const Location&, Var func_var); - Result OnRefIsNull(const Location&); - Result OnRefNull(const Location&, Type type); - Result OnRethrow(const Location&, Var depth); - Result OnReturnCall(const Location&, Var func_var); - Result OnReturnCallIndirect(const Location&, Var sig_var, Var table_var); - Result OnReturn(const Location&); - Result OnSelect(const Location&, Index result_count, Type* result_types); - Result OnSimdLaneOp(const Location&, Opcode, uint64_t lane_idx); - Result OnSimdLoadLane(const Location&, - Opcode, - Var memidx, - Address align, - uint64_t lane_idx); - Result OnSimdStoreLane(const Location&, - Opcode, - Var memidx, - Address align, - uint64_t lane_idx); - Result OnSimdShuffleOp(const Location&, Opcode, v128 lane_idx); - Result OnStore(const Location&, Opcode, Var memidx, Address align); - Result OnTableCopy(const Location&, Var dst_var, Var src_var); - Result OnTableFill(const Location&, Var table_var); - Result OnTableGet(const Location&, Var table_var); - Result OnTableGrow(const Location&, Var table_var); - Result OnTableInit(const Location&, Var segment_var, Var table_var); - Result OnTableSet(const Location&, Var table_var); - Result OnTableSize(const Location&, Var table_var); - Result OnTernary(const Location&, Opcode); - Result OnThrow(const Location&, Var tag_var); - Result OnTry(const Location&, Type sig_type); - Result OnUnary(const Location&, Opcode); - Result OnUnreachable(const Location&); - - private: - struct FuncType { - FuncType() = default; - FuncType(const TypeVector& params, - const TypeVector& results, - Index type_index) - : params(params), results(results), type_index(type_index) {} - - TypeVector params; - TypeVector results; - Index type_index; - }; - - struct StructType { - StructType() = default; - StructType(const TypeMutVector& fields) : fields(fields) {} - - TypeMutVector fields; - }; - - struct ArrayType { - ArrayType() = default; - ArrayType(TypeMut field) : field(field) {} - - TypeMut field; - }; - - struct TableType { - TableType() = default; - TableType(Type element, Limits limits) : element(element), limits(limits) {} - - Type element = Type::Any; - Limits limits; - }; - - struct MemoryType { - MemoryType() = default; - MemoryType(Limits limits) : limits(limits) {} - - Limits limits; - }; - - struct GlobalType { - GlobalType() = default; - GlobalType(Type type, bool mutable_) : type(type), mutable_(mutable_) {} - - Type type = Type::Any; - bool mutable_ = true; - }; - - struct TagType { - TypeVector params; - }; - - struct ElemType { - ElemType() = default; - ElemType(Type element) : element(element) {} - - Type element; - }; - - struct LocalDecl { - Type type; - Index end; - }; - - bool ValidInitOpcode(Opcode opcode) const; - Result CheckInstr(Opcode opcode, const Location& loc); - Result CheckType(const Location&, - Type actual, - Type expected, - const char* desc); - Result CheckLimits(const Location&, - const Limits&, - uint64_t absolute_max, - const char* desc); - - Result CheckLocalIndex(Var local_var, Type* out_type); - - Result CheckDeclaredFunc(Var func_var); - - Result CheckIndex(Var var, Index max_index, const char* desc); - template <typename T> - Result CheckIndexWithValue(Var var, - const std::vector<T>& values, - T* out, - const char* desc); - Result CheckFuncTypeIndex(Var sig_var, FuncType* out = nullptr); - Result CheckFuncIndex(Var func_var, FuncType* out = nullptr); - Result CheckTableIndex(Var table_var, TableType* out = nullptr); - Result CheckMemoryIndex(Var memory_var, MemoryType* out = nullptr); - Result CheckGlobalIndex(Var global_var, GlobalType* out = nullptr); - Result CheckTagIndex(Var tag_var, TagType* out = nullptr); - Result CheckElemSegmentIndex(Var elem_segment_var, ElemType* out = nullptr); - Result CheckDataSegmentIndex(Var data_segment_var); - - Result CheckAlign(const Location&, Address align, Address natural_align); - Result CheckAtomicAlign(const Location&, - Address align, - Address natural_align); - - Result CheckBlockSignature(const Location&, - Opcode, - Type sig_type, - TypeVector* out_param_types, - TypeVector* out_result_types); - - Index GetFunctionTypeIndex(Index func_index) const; - - TypeVector ToTypeVector(Index count, const Type* types); - - ValidateOptions options_; - Errors* errors_; - TypeChecker typechecker_; // TODO: Move into SharedValidator. - // Cached for access by OnTypecheckerError. - Location expr_loc_ = Location(kInvalidOffset); - bool in_init_expr_ = false; - - Index num_types_ = 0; - std::map<Index, FuncType> func_types_; - std::map<Index, StructType> struct_types_; - std::map<Index, ArrayType> array_types_; - - std::vector<FuncType> funcs_; // Includes imported and defined. - std::vector<TableType> tables_; // Includes imported and defined. - std::vector<MemoryType> memories_; // Includes imported and defined. - std::vector<GlobalType> globals_; // Includes imported and defined. - std::vector<TagType> tags_; // Includes imported and defined. - std::vector<ElemType> elems_; - Index starts_ = 0; - Index num_imported_globals_ = 0; - Index data_segments_ = 0; - - // Includes parameters, since this is only used for validating - // local.{get,set,tee} instructions. - std::vector<LocalDecl> locals_; - - std::set<std::string> export_names_; // Used to check for duplicates. - std::set<Index> declared_funcs_; // TODO: optimize? - std::vector<Var> check_declared_funcs_; -}; - -} // namespace wabt - -#endif // WABT_SHARED_VALIDATOR_H_ diff --git a/src/stream.cc b/src/stream.cc index b1d18c04..5f27e01b 100644 --- a/src/stream.cc +++ b/src/stream.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/stream.h" +#include "wabt/stream.h" #include <cassert> #include <cctype> diff --git a/src/stream.h b/src/stream.h deleted file mode 100644 index 07c507bd..00000000 --- a/src/stream.h +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_STREAM_H_ -#define WABT_STREAM_H_ - -#include <cassert> -#include <memory> -#include <vector> - -#include "src/common.h" - -namespace wabt { - -/* whether to display the ASCII characters in the debug output for - * write_memory */ -enum class PrintChars { - No = 0, - Yes = 1, -}; - -class Stream { - public: - explicit Stream(Stream* log_stream = nullptr); - virtual ~Stream() = default; - - size_t offset() { return offset_; } - Result result() { return result_; } - - void set_log_stream(Stream* stream) { - assert(stream); - log_stream_ = stream; - } - - Stream& log_stream() { - assert(log_stream_); - return *log_stream_; - } - - bool has_log_stream() const { return log_stream_ != nullptr; } - - void ClearOffset() { offset_ = 0; } - void AddOffset(ssize_t delta); - - void WriteData(const void* src, - size_t size, - const char* desc = nullptr, - PrintChars = PrintChars::No); - - template <typename T> - void WriteData(const std::vector<T> src, - const char* desc, - PrintChars print_chars = PrintChars::No) { - if (!src.empty()) { - WriteData(src.data(), src.size() * sizeof(T), desc, print_chars); - } - } - - void WriteDataAt(size_t offset, - const void* src, - size_t size, - const char* desc = nullptr, - PrintChars = PrintChars::No); - - void MoveData(size_t dst_offset, size_t src_offset, size_t size); - - void Truncate(size_t size); - - void WABT_PRINTF_FORMAT(2, 3) Writef(const char* format, ...); - - // Specified as uint32_t instead of uint8_t so we can check if the value - // given is in range before wrapping. - void WriteU8(uint32_t value, - const char* desc = nullptr, - PrintChars print_chars = PrintChars::No) { - assert(value <= UINT8_MAX); - Write(static_cast<uint8_t>(value), desc, print_chars); - } - void WriteU32(uint32_t value, - const char* desc = nullptr, - PrintChars print_chars = PrintChars::No) { - Write(value, desc, print_chars); - } - void WriteU64(uint64_t value, - const char* desc = nullptr, - PrintChars print_chars = PrintChars::No) { - Write(value, desc, print_chars); - } - void WriteU128(v128 value, - const char* desc = nullptr, - PrintChars print_chars = PrintChars::No) { - Write(value, desc, print_chars); - } - - void WriteChar(char c, - const char* desc = nullptr, - PrintChars print_chars = PrintChars::No) { - WriteU8(static_cast<unsigned char>(c), desc, print_chars); - } - - // Dump memory as text, similar to the xxd format. - void WriteMemoryDump(const void* start, - size_t size, - size_t offset = 0, - PrintChars print_chars = PrintChars::No, - const char* prefix = nullptr, - const char* desc = nullptr); - - // Convenience functions for writing enums. - template <typename T> - void WriteU8Enum(T value, - const char* desc = nullptr, - PrintChars print_chars = PrintChars::No) { - WriteU8(static_cast<uint32_t>(value), desc, print_chars); - } - - virtual void Flush() {} - - protected: - virtual Result WriteDataImpl(size_t offset, - const void* data, - size_t size) = 0; - virtual Result MoveDataImpl(size_t dst_offset, - size_t src_offset, - size_t size) = 0; - virtual Result TruncateImpl(size_t size) = 0; - - private: - template <typename T> - void Write(const T& data, const char* desc, PrintChars print_chars) { -#if WABT_BIG_ENDIAN - char tmp[sizeof(T)]; - memcpy(tmp, &data, sizeof(tmp)); - SwapBytesSized(tmp, sizeof(tmp)); - WriteData(tmp, sizeof(tmp), desc, print_chars); -#else - WriteData(&data, sizeof(data), desc, print_chars); -#endif - } - - size_t offset_; - Result result_; - // Not owned. If non-null, log all writes to this stream. - Stream* log_stream_; -}; - -struct OutputBuffer { - Result WriteToFile(std::string_view filename) const; - Result WriteToStdout() const; - - void clear() { data.clear(); } - size_t size() const { return data.size(); } - - std::vector<uint8_t> data; -}; - -class MemoryStream : public Stream { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(MemoryStream); - MemoryStream(MemoryStream&&) = default; - explicit MemoryStream(Stream* log_stream = nullptr); - explicit MemoryStream(std::unique_ptr<OutputBuffer>&&, - Stream* log_stream = nullptr); - - OutputBuffer& output_buffer() { return *buf_; } - std::unique_ptr<OutputBuffer> ReleaseOutputBuffer(); - - void Clear(); - - Result WriteToFile(std::string_view filename) { - return buf_->WriteToFile(filename); - } - - protected: - Result WriteDataImpl(size_t offset, const void* data, size_t size) override; - Result MoveDataImpl(size_t dst_offset, - size_t src_offset, - size_t size) override; - Result TruncateImpl(size_t size) override; - - private: - std::unique_ptr<OutputBuffer> buf_; -}; - -class FileStream : public Stream { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(FileStream); - explicit FileStream(std::string_view filename, Stream* log_stream = nullptr); - explicit FileStream(FILE*, Stream* log_stream = nullptr); - FileStream(FileStream&&); - FileStream& operator=(FileStream&&); - ~FileStream() override; - - static std::unique_ptr<FileStream> CreateStdout(); - static std::unique_ptr<FileStream> CreateStderr(); - - bool is_open() const { return file_ != nullptr; } - - void Flush() override; - - protected: - Result WriteDataImpl(size_t offset, const void* data, size_t size) override; - Result MoveDataImpl(size_t dst_offset, - size_t src_offset, - size_t size) override; - Result TruncateImpl(size_t size) override; - - private: - FILE* file_; - size_t offset_; - bool should_close_; -}; - -} // namespace wabt - -#endif /* WABT_STREAM_H_ */ diff --git a/src/string-format.h b/src/string-format.h deleted file mode 100644 index 642ee11e..00000000 --- a/src/string-format.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2021 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_STRING_FORMAT_H_ -#define WABT_STRING_FORMAT_H_ - -#include <string> -#include <vector> - -#include "config.h" - -#define PRIstringview "%.*s" -#define WABT_PRINTF_STRING_VIEW_ARG(x) \ - static_cast<int>((x).length()), (x).data() - -#define PRItypecode "%s%#x" -#define WABT_PRINTF_TYPE_CODE(x) \ - (static_cast<int32_t>(x) < 0 ? "-" : ""), std::abs(static_cast<int32_t>(x)) - -#define WABT_DEFAULT_SNPRINTF_ALLOCA_BUFSIZE 128 -#define WABT_SNPRINTF_ALLOCA(buffer, len, format) \ - va_list args; \ - va_list args_copy; \ - va_start(args, format); \ - va_copy(args_copy, args); \ - char fixed_buf[WABT_DEFAULT_SNPRINTF_ALLOCA_BUFSIZE]; \ - char* buffer = fixed_buf; \ - size_t len = wabt_vsnprintf(fixed_buf, sizeof(fixed_buf), format, args); \ - va_end(args); \ - if (len + 1 > sizeof(fixed_buf)) { \ - buffer = static_cast<char*>(alloca(len + 1)); \ - len = wabt_vsnprintf(buffer, len + 1, format, args_copy); \ - } \ - va_end(args_copy) - -namespace wabt { - -inline std::string WABT_PRINTF_FORMAT(1, 2) - StringPrintf(const char* format, ...) { - va_list args; - va_list args_copy; - va_start(args, format); - va_copy(args_copy, args); - size_t len = wabt_vsnprintf(nullptr, 0, format, args) + 1; // For \0. - std::vector<char> buffer(len); - va_end(args); - wabt_vsnprintf(buffer.data(), len, format, args_copy); - va_end(args_copy); - return std::string(buffer.data(), len - 1); -} - -} // namespace wabt - -#endif // WABT_STRING_FORMAT_H_ diff --git a/src/string-util.h b/src/string-util.h deleted file mode 100644 index 28734d50..00000000 --- a/src/string-util.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_STRING_UTIL_H_ -#define WABT_STRING_UTIL_H_ - -#include <string> -#include <string_view> - -namespace wabt { - -inline std::string& operator+=(std::string& x, std::string_view y) { - x.append(y.data(), y.size()); - return x; -} - -inline std::string operator+(std::string_view x, std::string_view y) { - std::string s; - s.reserve(x.size() + y.size()); - s.append(x.data(), x.size()); - s.append(y.data(), y.size()); - return s; -} - -inline std::string operator+(const std::string& x, std::string_view y) { - return std::string_view(x) + y; -} - -inline std::string operator+(std::string_view x, const std::string& y) { - return x + std::string_view(y); -} - -inline std::string operator+(const char* x, std::string_view y) { - return std::string_view(x) + y; -} - -inline std::string operator+(std::string_view x, const char* y) { - return x + std::string_view(y); -} - -inline void cat_concatenate(std::string&) {} - -template <typename T, typename... Ts> -void cat_concatenate(std::string& s, const T& t, const Ts&... args) { - s += t; - cat_concatenate(s, args...); -} - -inline size_t cat_compute_size() { - return 0; -} - -template <typename T, typename... Ts> -size_t cat_compute_size(const T& t, const Ts&... args) { - return std::string_view(t).size() + cat_compute_size(args...); -} - -// Is able to concatenate any combination of string/string_view/char* -template <typename... Ts> -std::string cat(const Ts&... args) { - std::string s; - s.reserve(cat_compute_size(args...)); - cat_concatenate(s, args...); - return s; -} - -} // namespace wabt - -#endif // WABT_STRING_UTIL_H_ diff --git a/src/test-binary-reader.cc b/src/test-binary-reader.cc index ee206013..b3e3540d 100644 --- a/src/test-binary-reader.cc +++ b/src/test-binary-reader.cc @@ -16,10 +16,10 @@ #include "gtest/gtest.h" -#include "src/binary-reader-nop.h" -#include "src/binary-reader.h" -#include "src/leb128.h" -#include "src/opcode.h" +#include "wabt/binary-reader-nop.h" +#include "wabt/binary-reader.h" +#include "wabt/leb128.h" +#include "wabt/opcode.h" using namespace wabt; diff --git a/src/test-circular-array.cc b/src/test-circular-array.cc index aefea514..a2a8919e 100644 --- a/src/test-circular-array.cc +++ b/src/test-circular-array.cc @@ -18,7 +18,7 @@ #include <memory> -#include "src/circular-array.h" +#include "wabt/circular-array.h" using namespace wabt; diff --git a/src/test-filenames.cc b/src/test-filenames.cc index a0552bf8..b734f58b 100644 --- a/src/test-filenames.cc +++ b/src/test-filenames.cc @@ -16,7 +16,7 @@ #include "gtest/gtest.h" -#include "src/filenames.h" +#include "wabt/filenames.h" using namespace wabt; diff --git a/src/test-hexfloat.cc b/src/test-hexfloat.cc index 7b493518..6dba8c06 100644 --- a/src/test-hexfloat.cc +++ b/src/test-hexfloat.cc @@ -20,7 +20,7 @@ #include "gtest/gtest.h" -#include "src/literal.h" +#include "wabt/literal.h" #define FOREACH_UINT32_MULTIPLIER 1 diff --git a/src/test-interp.cc b/src/test-interp.cc index e3de004b..11e4770f 100644 --- a/src/test-interp.cc +++ b/src/test-interp.cc @@ -16,11 +16,11 @@ #include "gtest/gtest.h" -#include "src/binary-reader.h" -#include "src/error-formatter.h" +#include "wabt/binary-reader.h" +#include "wabt/error-formatter.h" -#include "src/interp/binary-reader-interp.h" -#include "src/interp/interp.h" +#include "wabt/interp/binary-reader-interp.h" +#include "wabt/interp/interp.h" using namespace wabt; using namespace wabt::interp; diff --git a/src/test-intrusive-list.cc b/src/test-intrusive-list.cc index dfc3dbb3..ec817ecf 100644 --- a/src/test-intrusive-list.cc +++ b/src/test-intrusive-list.cc @@ -18,8 +18,8 @@ #include <memory> -#include "src/intrusive-list.h" -#include "src/make-unique.h" +#include "wabt/intrusive-list.h" +#include "wabt/make-unique.h" using namespace wabt; diff --git a/src/test-literal.cc b/src/test-literal.cc index 57a933a4..d9990d16 100644 --- a/src/test-literal.cc +++ b/src/test-literal.cc @@ -21,7 +21,7 @@ #include "gtest/gtest.h" -#include "src/literal.h" +#include "wabt/literal.h" using namespace wabt; diff --git a/src/test-option-parser.cc b/src/test-option-parser.cc index 6d6c4db5..757e6578 100644 --- a/src/test-option-parser.cc +++ b/src/test-option-parser.cc @@ -16,7 +16,7 @@ #include <string> -#include "src/option-parser.h" +#include "wabt/option-parser.h" using namespace wabt; diff --git a/src/test-utf8.cc b/src/test-utf8.cc index 8e420628..d19077e9 100644 --- a/src/test-utf8.cc +++ b/src/test-utf8.cc @@ -16,7 +16,7 @@ #include "gtest/gtest.h" -#include "src/utf8.h" +#include "wabt/utf8.h" using namespace wabt; diff --git a/src/test-wast-parser.cc b/src/test-wast-parser.cc index 00a27bf5..69b5cf67 100644 --- a/src/test-wast-parser.cc +++ b/src/test-wast-parser.cc @@ -18,8 +18,8 @@ #include <memory> -#include "src/wast-lexer.h" -#include "src/wast-parser.h" +#include "wabt/wast-lexer.h" +#include "wabt/wast-parser.h" using namespace wabt; diff --git a/src/token.cc b/src/token.cc index cb1a19df..576fadd1 100644 --- a/src/token.cc +++ b/src/token.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/token.h" +#include "wabt/token.h" namespace wabt { @@ -23,7 +23,7 @@ const char* GetTokenTypeName(TokenType token_type) { #define WABT_TOKEN(name, string) string, #define WABT_TOKEN_FIRST(name, string) #define WABT_TOKEN_LAST(name, string) -#include "token.def" +#include "wabt/token.def" #undef WABT_TOKEN #undef WABT_TOKEN_FIRST #undef WABT_TOKEN_LAST diff --git a/src/token.def b/src/token.def deleted file mode 100644 index b8869abd..00000000 --- a/src/token.def +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright 2018 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_TOKEN -#error "You must define WABT_TOKEN before including this file." -#endif - -/* Tokens with no additional data (i.e. bare). */ -WABT_TOKEN(Invalid, "Invalid") -WABT_TOKEN(Array, "array") -WABT_TOKEN(AssertException, "assert_exception") -WABT_TOKEN(AssertExhaustion, "assert_exhaustion") -WABT_TOKEN(AssertInvalid, "assert_invalid") -WABT_TOKEN(AssertMalformed, "assert_malformed") -WABT_TOKEN(AssertReturn, "assert_return") -WABT_TOKEN(AssertTrap, "assert_trap") -WABT_TOKEN(AssertUnlinkable, "assert_unlinkable") -WABT_TOKEN(Bin, "bin") -WABT_TOKEN(Item, "item") -WABT_TOKEN(Data, "data") -WABT_TOKEN(Declare, "declare") -WABT_TOKEN(Delegate, "delegate") -WABT_TOKEN(Do, "do") -WABT_TOKEN(Elem, "elem") -WABT_TOKEN(Eof, "EOF") -WABT_TOKEN(Tag, "tag") -WABT_TOKEN(Export, "export") -WABT_TOKEN(Field, "field") -WABT_TOKEN(Get, "get") -WABT_TOKEN(Global, "global") -WABT_TOKEN(Import, "import") -WABT_TOKEN(Invoke, "invoke") -WABT_TOKEN(Input, "input") -WABT_TOKEN(Local, "local") -WABT_TOKEN(Lpar, "(") -WABT_TOKEN(Memory, "memory") -WABT_TOKEN(Module, "module") -WABT_TOKEN(Mut, "mut") -WABT_TOKEN(NanArithmetic, "nan:arithmetic") -WABT_TOKEN(NanCanonical, "nan:canonical") -WABT_TOKEN(Offset, "offset") -WABT_TOKEN(Output, "output") -WABT_TOKEN(Param, "param") -WABT_TOKEN(Ref, "ref") -WABT_TOKEN(Quote, "quote") -WABT_TOKEN(Register, "register") -WABT_TOKEN(Result, "result") -WABT_TOKEN(Rpar, ")") -WABT_TOKEN(Shared, "shared") -WABT_TOKEN(Start, "start") -WABT_TOKEN(Struct, "struct") -WABT_TOKEN(Table, "table") -WABT_TOKEN(Then, "then") -WABT_TOKEN(Type, "type") -WABT_TOKEN(I8X16, "i8x16") -WABT_TOKEN(I16X8, "i16x8") -WABT_TOKEN(I32X4, "i32x4") -WABT_TOKEN(I64X2, "i64x2") -WABT_TOKEN(F32X4, "f32x4") -WABT_TOKEN(F64X2, "f64x2") -WABT_TOKEN_FIRST(Bare, Invalid) -WABT_TOKEN_LAST(Bare, F64X2) - -/* Tokens with Literal data. */ -WABT_TOKEN(Float, "FLOAT") -WABT_TOKEN(Int, "INT") -WABT_TOKEN(Nat, "NAT") -WABT_TOKEN_FIRST(Literal, Float) -WABT_TOKEN_LAST(Literal, Nat) - -/* Tokens with Opcode data. */ -WABT_TOKEN(AtomicFence, "atomic.fence") -WABT_TOKEN(AtomicLoad, "ATOMIC_LOAD") -WABT_TOKEN(AtomicNotify, "ATOMIC_NOTIFY") -WABT_TOKEN(AtomicRmw, "ATOMIC_RMW") -WABT_TOKEN(AtomicRmwCmpxchg, "ATOMIC_RMW_CMPXCHG") -WABT_TOKEN(AtomicStore, "ATOMIC_STORE") -WABT_TOKEN(AtomicWait, "ATOMIC_WAIT") -WABT_TOKEN(Binary, "BINARY") -WABT_TOKEN(Block, "block") -WABT_TOKEN(Br, "br") -WABT_TOKEN(BrIf, "br_if") -WABT_TOKEN(BrTable, "br_table") -WABT_TOKEN(Call, "call") -WABT_TOKEN(CallIndirect, "call_indirect") -WABT_TOKEN(CallRef, "call_ref") -WABT_TOKEN(Catch, "catch") -WABT_TOKEN(CatchAll, "catch_all") -WABT_TOKEN(Compare, "COMPARE") -WABT_TOKEN(Const, "CONST") -WABT_TOKEN(Convert, "CONVERT") -WABT_TOKEN(DataDrop, "data.drop") -WABT_TOKEN(Drop, "drop") -WABT_TOKEN(ElemDrop, "elem.drop") -WABT_TOKEN(Else, "else") -WABT_TOKEN(End, "end") -WABT_TOKEN(GlobalGet, "global.get") -WABT_TOKEN(GlobalSet, "global.set") -WABT_TOKEN(If, "if") -WABT_TOKEN(Load, "LOAD") -WABT_TOKEN(LocalGet, "local.get") -WABT_TOKEN(LocalSet, "local.set") -WABT_TOKEN(LocalTee, "local.tee") -WABT_TOKEN(Loop, "loop") -WABT_TOKEN(MemoryCopy, "memory.copy") -WABT_TOKEN(MemoryFill, "memory.fill") -WABT_TOKEN(MemoryGrow, "memory.grow") -WABT_TOKEN(MemoryInit, "memory.init") -WABT_TOKEN(MemorySize, "memory.size") -WABT_TOKEN(Nop, "nop") -WABT_TOKEN(RefExtern, "ref.extern") -WABT_TOKEN(RefFunc, "ref.func") -WABT_TOKEN(RefIsNull, "ref.is_null") -WABT_TOKEN(RefNull, "ref.null") -WABT_TOKEN(Rethrow, "rethrow") -WABT_TOKEN(ReturnCallIndirect, "return_call_indirect") -WABT_TOKEN(ReturnCall, "return_call") -WABT_TOKEN(Return, "return") -WABT_TOKEN(Select, "select") -WABT_TOKEN(SimdLaneOp, "SIMDLANEOP") -WABT_TOKEN(SimdLoadSplat, "SIMDLOADSPLAT") -WABT_TOKEN(SimdLoadLane, "SIMDLOADLANE") -WABT_TOKEN(SimdStoreLane, "SIMDSTORELANE") -WABT_TOKEN(SimdShuffleOp, "i8x16.shuffle") -WABT_TOKEN(Store, "STORE") -WABT_TOKEN(TableCopy, "table.copy") -WABT_TOKEN(TableFill, "table.full") -WABT_TOKEN(TableGet, "table.get") -WABT_TOKEN(TableGrow, "table.grow") -WABT_TOKEN(TableInit, "table.init") -WABT_TOKEN(TableSet, "table.set") -WABT_TOKEN(TableSize, "table.size") -WABT_TOKEN(Ternary, "TERNARY") -WABT_TOKEN(Throw, "throw") -WABT_TOKEN(Try, "try") -WABT_TOKEN(Unary, "UNARY") -WABT_TOKEN(Unreachable, "unreachable") -WABT_TOKEN_FIRST(Opcode, AtomicFence) -WABT_TOKEN_LAST(Opcode, Unreachable) - -/* Tokens with string data. */ -WABT_TOKEN(AlignEqNat, "align=") -WABT_TOKEN(LparAnn, "Annotation") -WABT_TOKEN(OffsetEqNat, "offset=") -WABT_TOKEN(Reserved, "Reserved") -WABT_TOKEN(Text, "TEXT") -WABT_TOKEN(Var, "VAR") -WABT_TOKEN_FIRST(String, AlignEqNat) -WABT_TOKEN_LAST(String, Var) - -/* Tokens with Type data. */ -WABT_TOKEN(ValueType, "VALUETYPE") -WABT_TOKEN_FIRST(Type, ValueType) -WABT_TOKEN_LAST(Type, ValueType) - -/* Tokens with Type data, but are reference kinds. */ -WABT_TOKEN(Func, "func") -WABT_TOKEN(Extern, "extern") -WABT_TOKEN(Exn, "exn") -WABT_TOKEN_FIRST(RefKind, Func) -WABT_TOKEN_LAST(RefKind, Exn) diff --git a/src/token.h b/src/token.h deleted file mode 100644 index 20c9c181..00000000 --- a/src/token.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_TOKEN_H_ -#define WABT_TOKEN_H_ - -#include <string_view> - -#include "src/literal.h" -#include "src/opcode.h" - -namespace wabt { - -struct Literal { - Literal() = default; - Literal(LiteralType type, std::string_view text) : type(type), text(text) {} - - LiteralType type; - std::string_view text; -}; - -enum class TokenType { -#define WABT_TOKEN(name, string) name, -#define WABT_TOKEN_FIRST(group, first) First_##group = first, -#define WABT_TOKEN_LAST(group, last) Last_##group = last, -#include "token.def" -#undef WABT_TOKEN -#undef WABT_TOKEN_FIRST -#undef WABT_TOKEN_LAST - - First = First_Bare, - Last = Last_RefKind, -}; - -const char* GetTokenTypeName(TokenType); - -inline bool IsTokenTypeBare(TokenType token_type) { - return token_type >= TokenType::First_Bare && - token_type <= TokenType::Last_Bare; -} - -inline bool IsTokenTypeString(TokenType token_type) { - return token_type >= TokenType::First_String && - token_type <= TokenType::Last_String; -} - -inline bool IsTokenTypeType(TokenType token_type) { - return token_type == TokenType::ValueType; -} - -inline bool IsTokenTypeOpcode(TokenType token_type) { - return token_type >= TokenType::First_Opcode && - token_type <= TokenType::Last_Opcode; -} - -inline bool IsTokenTypeLiteral(TokenType token_type) { - return token_type >= TokenType::First_Literal && - token_type <= TokenType::Last_Literal; -} - -inline bool IsTokenTypeRefKind(TokenType token_type) { - return token_type >= TokenType::First_RefKind && - token_type <= TokenType::Last_RefKind; -} - -struct Token { - Token() : token_type_(TokenType::Invalid) {} - Token(Location, TokenType); - Token(Location, TokenType, Type); - Token(Location, TokenType, std::string_view); - Token(Location, TokenType, Opcode); - Token(Location, TokenType, const Literal&); - - Location loc; - - TokenType token_type() const { return token_type_; } - - bool HasText() const { return IsTokenTypeString(token_type_); } - bool HasType() const { - return IsTokenTypeType(token_type_) || IsTokenTypeRefKind(token_type_); - } - bool HasOpcode() const { return IsTokenTypeOpcode(token_type_); } - bool HasLiteral() const { return IsTokenTypeLiteral(token_type_); } - - std::string_view text() const { - assert(HasText()); - return text_; - } - - Type type() const { - assert(HasType()); - return type_; - } - - Opcode opcode() const { - assert(HasOpcode()); - return opcode_; - } - - const Literal& literal() const { - assert(HasLiteral()); - return literal_; - } - - std::string to_string() const; - std::string to_string_clamp(size_t max_length) const; - - private: - TokenType token_type_; - - union { - std::string_view text_; - Type type_; - Opcode opcode_; - Literal literal_; - }; -}; - -} // namespace wabt - -#endif // WABT_TOKEN_H_ diff --git a/src/tools/spectest-interp.cc b/src/tools/spectest-interp.cc index 2e842dfd..af50bfb2 100644 --- a/src/tools/spectest-interp.cc +++ b/src/tools/spectest-interp.cc @@ -24,21 +24,21 @@ #include <string> #include <vector> -#include "src/binary-reader.h" -#include "src/cast.h" -#include "src/common.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/interp/binary-reader-interp.h" -#include "src/interp/interp-util.h" -#include "src/interp/interp.h" -#include "src/literal.h" -#include "src/option-parser.h" -#include "src/stream.h" -#include "src/string-util.h" -#include "src/validator.h" -#include "src/wast-lexer.h" -#include "src/wast-parser.h" +#include "wabt/binary-reader.h" +#include "wabt/cast.h" +#include "wabt/common.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/interp/binary-reader-interp.h" +#include "wabt/interp/interp-util.h" +#include "wabt/interp/interp.h" +#include "wabt/literal.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" +#include "wabt/string-util.h" +#include "wabt/validator.h" +#include "wabt/wast-lexer.h" +#include "wabt/wast-parser.h" using namespace wabt; using namespace wabt::interp; diff --git a/src/tools/wasm-decompile.cc b/src/tools/wasm-decompile.cc index df2bd2b5..5c8c1252 100644 --- a/src/tools/wasm-decompile.cc +++ b/src/tools/wasm-decompile.cc @@ -19,18 +19,18 @@ #include <cstdio> #include <cstdlib> -#include "src/apply-names.h" -#include "src/binary-reader-ir.h" -#include "src/binary-reader.h" -#include "src/decompiler.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/generate-names.h" -#include "src/ir.h" -#include "src/option-parser.h" -#include "src/stream.h" -#include "src/validator.h" -#include "src/wast-lexer.h" +#include "wabt/apply-names.h" +#include "wabt/binary-reader-ir.h" +#include "wabt/binary-reader.h" +#include "wabt/decompiler.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/generate-names.h" +#include "wabt/ir.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" +#include "wabt/validator.h" +#include "wabt/wast-lexer.h" using namespace wabt; diff --git a/src/tools/wasm-interp.cc b/src/tools/wasm-interp.cc index 465ad611..addde767 100644 --- a/src/tools/wasm-interp.cc +++ b/src/tools/wasm-interp.cc @@ -22,15 +22,15 @@ #include <string> #include <vector> -#include "src/binary-reader.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/interp/binary-reader-interp.h" -#include "src/interp/interp-util.h" -#include "src/interp/interp-wasi.h" -#include "src/interp/interp.h" -#include "src/option-parser.h" -#include "src/stream.h" +#include "wabt/binary-reader.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/interp/binary-reader-interp.h" +#include "wabt/interp/interp-util.h" +#include "wabt/interp/interp-wasi.h" +#include "wabt/interp/interp.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" #ifdef WITH_WASI #include "uvwasi.h" diff --git a/src/tools/wasm-objdump.cc b/src/tools/wasm-objdump.cc index 59060432..d553c742 100644 --- a/src/tools/wasm-objdump.cc +++ b/src/tools/wasm-objdump.cc @@ -18,11 +18,11 @@ #include <cstdlib> #include <cstring> -#include "src/binary-reader-objdump.h" -#include "src/binary-reader.h" -#include "src/common.h" -#include "src/option-parser.h" -#include "src/stream.h" +#include "wabt/binary-reader-objdump.h" +#include "wabt/binary-reader.h" +#include "wabt/common.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" using namespace wabt; diff --git a/src/tools/wasm-opcodecnt.cc b/src/tools/wasm-opcodecnt.cc index f3abb868..63153d39 100644 --- a/src/tools/wasm-opcodecnt.cc +++ b/src/tools/wasm-opcodecnt.cc @@ -24,10 +24,10 @@ #include <map> #include <vector> -#include "src/binary-reader-opcnt.h" -#include "src/binary-reader.h" -#include "src/option-parser.h" -#include "src/stream.h" +#include "wabt/binary-reader-opcnt.h" +#include "wabt/binary-reader.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" #define ERROR(fmt, ...) \ fprintf(stderr, "%s:%d: " fmt, __FILE__, __LINE__, __VA_ARGS__) diff --git a/src/tools/wasm-strip.cc b/src/tools/wasm-strip.cc index f7abd5ff..8d8b33a0 100644 --- a/src/tools/wasm-strip.cc +++ b/src/tools/wasm-strip.cc @@ -14,13 +14,13 @@ * limitations under the License. */ -#include "src/binary-reader-nop.h" -#include "src/binary-reader.h" -#include "src/binary.h" -#include "src/error-formatter.h" -#include "src/leb128.h" -#include "src/option-parser.h" -#include "src/stream.h" +#include "wabt/binary-reader-nop.h" +#include "wabt/binary-reader.h" +#include "wabt/binary.h" +#include "wabt/error-formatter.h" +#include "wabt/leb128.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" using namespace wabt; diff --git a/src/tools/wasm-validate.cc b/src/tools/wasm-validate.cc index dd48e121..d093f1be 100644 --- a/src/tools/wasm-validate.cc +++ b/src/tools/wasm-validate.cc @@ -19,14 +19,14 @@ #include <cstdio> #include <cstdlib> -#include "src/binary-reader-ir.h" -#include "src/binary-reader.h" -#include "src/error-formatter.h" -#include "src/ir.h" -#include "src/option-parser.h" -#include "src/stream.h" -#include "src/validator.h" -#include "src/wast-lexer.h" +#include "wabt/binary-reader-ir.h" +#include "wabt/binary-reader.h" +#include "wabt/error-formatter.h" +#include "wabt/ir.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" +#include "wabt/validator.h" +#include "wabt/wast-lexer.h" using namespace wabt; diff --git a/src/tools/wasm2c.cc b/src/tools/wasm2c.cc index 3dd14483..b00bce58 100644 --- a/src/tools/wasm2c.cc +++ b/src/tools/wasm2c.cc @@ -19,20 +19,20 @@ #include <cstdio> #include <cstdlib> -#include "src/apply-names.h" -#include "src/binary-reader-ir.h" -#include "src/binary-reader.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/filenames.h" -#include "src/generate-names.h" -#include "src/ir.h" -#include "src/option-parser.h" -#include "src/stream.h" -#include "src/validator.h" -#include "src/wast-lexer.h" - -#include "src/c-writer.h" +#include "wabt/apply-names.h" +#include "wabt/binary-reader-ir.h" +#include "wabt/binary-reader.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/filenames.h" +#include "wabt/generate-names.h" +#include "wabt/ir.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" +#include "wabt/validator.h" +#include "wabt/wast-lexer.h" + +#include "wabt/c-writer.h" using namespace wabt; @@ -101,7 +101,7 @@ static void ParseOptions(int argc, char** argv) { any_non_supported_feature |= \ (s_features.variable##_enabled() != default_) && \ !IsFeatureSupported(flag); -#include "src/feature.def" +#include "wabt/feature.def" #undef WABT_FEATURE if (any_non_supported_feature) { diff --git a/src/tools/wasm2wat-fuzz.cc b/src/tools/wasm2wat-fuzz.cc index 1318ef62..52474248 100644 --- a/src/tools/wasm2wat-fuzz.cc +++ b/src/tools/wasm2wat-fuzz.cc @@ -16,10 +16,10 @@ // // https://github.com/google/oss-fuzz/blob/master/projects/wabt/wasm2wat_fuzzer.cc -#include "src/binary-reader-ir.h" -#include "src/binary-reader.h" -#include "src/common.h" -#include "src/ir.h" +#include "wabt/binary-reader-ir.h" +#include "wabt/binary-reader.h" +#include "wabt/common.h" +#include "wabt/ir.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { wabt::ReadBinaryOptions options; diff --git a/src/tools/wasm2wat.cc b/src/tools/wasm2wat.cc index 2c50fea7..7846f710 100644 --- a/src/tools/wasm2wat.cc +++ b/src/tools/wasm2wat.cc @@ -19,18 +19,18 @@ #include <cstdio> #include <cstdlib> -#include "src/apply-names.h" -#include "src/binary-reader-ir.h" -#include "src/binary-reader.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/generate-names.h" -#include "src/ir.h" -#include "src/option-parser.h" -#include "src/stream.h" -#include "src/validator.h" -#include "src/wast-lexer.h" -#include "src/wat-writer.h" +#include "wabt/apply-names.h" +#include "wabt/binary-reader-ir.h" +#include "wabt/binary-reader.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/generate-names.h" +#include "wabt/ir.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" +#include "wabt/validator.h" +#include "wabt/wast-lexer.h" +#include "wabt/wat-writer.h" using namespace wabt; diff --git a/src/tools/wast2json.cc b/src/tools/wast2json.cc index e3afed4d..bdc4a674 100644 --- a/src/tools/wast2json.cc +++ b/src/tools/wast2json.cc @@ -21,20 +21,20 @@ #include <cstdlib> #include <string> -#include "config.h" - -#include "src/binary-writer-spec.h" -#include "src/binary-writer.h" -#include "src/common.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/filenames.h" -#include "src/ir.h" -#include "src/option-parser.h" -#include "src/resolve-names.h" -#include "src/stream.h" -#include "src/validator.h" -#include "src/wast-parser.h" +#include "wabt/config.h" + +#include "wabt/binary-writer-spec.h" +#include "wabt/binary-writer.h" +#include "wabt/common.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/filenames.h" +#include "wabt/ir.h" +#include "wabt/option-parser.h" +#include "wabt/resolve-names.h" +#include "wabt/stream.h" +#include "wabt/validator.h" +#include "wabt/wast-parser.h" using namespace wabt; diff --git a/src/tools/wat-desugar.cc b/src/tools/wat-desugar.cc index 85c2d8a5..69a5dd54 100644 --- a/src/tools/wat-desugar.cc +++ b/src/tools/wat-desugar.cc @@ -20,18 +20,18 @@ #include <cstdio> #include <cstdlib> -#include "config.h" - -#include "src/apply-names.h" -#include "src/common.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/generate-names.h" -#include "src/ir.h" -#include "src/option-parser.h" -#include "src/stream.h" -#include "src/wast-parser.h" -#include "src/wat-writer.h" +#include "wabt/config.h" + +#include "wabt/apply-names.h" +#include "wabt/common.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/generate-names.h" +#include "wabt/ir.h" +#include "wabt/option-parser.h" +#include "wabt/stream.h" +#include "wabt/wast-parser.h" +#include "wabt/wat-writer.h" using namespace wabt; diff --git a/src/tools/wat2wasm.cc b/src/tools/wat2wasm.cc index 39eeed01..eab17ebf 100644 --- a/src/tools/wat2wasm.cc +++ b/src/tools/wat2wasm.cc @@ -21,19 +21,19 @@ #include <cstdlib> #include <string> -#include "config.h" - -#include "src/binary-writer.h" -#include "src/common.h" -#include "src/error-formatter.h" -#include "src/feature.h" -#include "src/filenames.h" -#include "src/ir.h" -#include "src/option-parser.h" -#include "src/resolve-names.h" -#include "src/stream.h" -#include "src/validator.h" -#include "src/wast-parser.h" +#include "wabt/config.h" + +#include "wabt/binary-writer.h" +#include "wabt/common.h" +#include "wabt/error-formatter.h" +#include "wabt/feature.h" +#include "wabt/filenames.h" +#include "wabt/ir.h" +#include "wabt/option-parser.h" +#include "wabt/resolve-names.h" +#include "wabt/stream.h" +#include "wabt/validator.h" +#include "wabt/wast-parser.h" using namespace wabt; diff --git a/src/tracing.cc b/src/tracing.cc index 3208acdf..21f512f5 100644 --- a/src/tracing.cc +++ b/src/tracing.cc @@ -15,7 +15,7 @@ */ #define WABT_TRACING 1 -#include "src/tracing.h" +#include "wabt/tracing.h" namespace { diff --git a/src/tracing.h b/src/tracing.h deleted file mode 100644 index 86daf63c..00000000 --- a/src/tracing.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_TRACING_H_ -#define WABT_TRACING_H_ - -// Provides a simple tracing class that automatically generates enter/exit -// messages using the scope of the instance. -// -// It also assumes that this file is only included in .cc files. -// Immediately before the inclusion of this file, there is a define of -// for WABT_TRACING, defining whether tracing should be compiled in for -// that source file. - -#ifndef WABT_TRACING -#define WABT_TRACING 0 -#endif - -#include "src/common.h" - -namespace wabt { - -#if WABT_TRACING - -// Scoped class that automatically prints enter("->") and exit("<-") -// lines, indented by trace level. -struct TraceScope { - WABT_DISALLOW_COPY_AND_ASSIGN(TraceScope); - TraceScope() = delete; - TraceScope(const char* method); - template <typename... Args> - TraceScope(const char* method, const char* format, Args&&... args) - : method_(method) { - PrintEnter(method); - fprintf(stderr, format, std::forward<Args>(args)...); - PrintNewline(); - } - ~TraceScope(); - - private: - const char* method_; - void PrintEnter(const char* method); - void PrintNewline(); -}; - -#define WABT_TRACE(method_name) TraceScope _func_(#method_name) - -#define WABT_TRACE_ARGS(method_name, format, ...) \ - TraceScope _func_(#method_name, format, __VA_ARGS__) - -#else - -#define WABT_TRACE(method) -#define WABT_TRACE_ARGS(method_name, format, ...) - -#endif - -} // end namespace wabt - -#endif // WABT_TRACING_H_ diff --git a/src/type-checker.cc b/src/type-checker.cc index 7282c5b2..01b5e233 100644 --- a/src/type-checker.cc +++ b/src/type-checker.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/type-checker.h" +#include "wabt/type-checker.h" #include <cinttypes> diff --git a/src/type-checker.h b/src/type-checker.h deleted file mode 100644 index 73ac5fb8..00000000 --- a/src/type-checker.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_TYPE_CHECKER_H_ -#define WABT_TYPE_CHECKER_H_ - -#include <functional> -#include <vector> - -#include "src/common.h" -#include "src/feature.h" -#include "src/opcode.h" - -namespace wabt { - -class TypeChecker { - public: - typedef std::function<void(const char* msg)> ErrorCallback; - - struct Label { - Label(LabelType, - const TypeVector& param_types, - const TypeVector& result_types, - size_t limit); - - TypeVector& br_types() { - return label_type == LabelType::Loop ? param_types : result_types; - } - - LabelType label_type; - TypeVector param_types; - TypeVector result_types; - size_t type_stack_limit; - bool unreachable; - }; - - explicit TypeChecker(const Features& features) : features_(features) {} - - void set_error_callback(const ErrorCallback& error_callback) { - error_callback_ = error_callback; - } - - size_t type_stack_size() const { return type_stack_.size(); } - - bool IsUnreachable(); - Result GetLabel(Index depth, Label** out_label); - Result GetRethrowLabel(Index depth, Label** out_label); - Result GetCatchCount(Index depth, Index* out_depth); - - Result BeginFunction(const TypeVector& sig); - Result OnAtomicFence(uint32_t consistency_model); - Result OnAtomicLoad(Opcode, const Limits& limits); - Result OnAtomicNotify(Opcode, const Limits& limits); - Result OnAtomicStore(Opcode, const Limits& limits); - Result OnAtomicRmw(Opcode, const Limits& limits); - Result OnAtomicRmwCmpxchg(Opcode, const Limits& limits); - Result OnAtomicWait(Opcode, const Limits& limits); - Result OnBinary(Opcode); - Result OnBlock(const TypeVector& param_types, const TypeVector& result_types); - Result OnBr(Index depth); - Result OnBrIf(Index depth); - Result BeginBrTable(); - Result OnBrTableTarget(Index depth); - Result EndBrTable(); - Result OnCall(const TypeVector& param_types, const TypeVector& result_types); - Result OnCallIndirect(const TypeVector& param_types, - const TypeVector& result_types); - Result OnIndexedFuncRef(Index* out_index); - Result OnReturnCall(const TypeVector& param_types, - const TypeVector& result_types); - Result OnReturnCallIndirect(const TypeVector& param_types, - const TypeVector& result_types); - Result OnCatch(const TypeVector& sig); - Result OnCompare(Opcode); - Result OnConst(Type); - Result OnConvert(Opcode); - Result OnDelegate(Index depth); - Result OnDrop(); - Result OnElse(); - Result OnEnd(); - Result OnGlobalGet(Type); - Result OnGlobalSet(Type); - Result OnIf(const TypeVector& param_types, const TypeVector& result_types); - Result OnLoad(Opcode, const Limits& limits); - Result OnLocalGet(Type); - Result OnLocalSet(Type); - Result OnLocalTee(Type); - Result OnLoop(const TypeVector& param_types, const TypeVector& result_types); - Result OnMemoryCopy(const Limits& limits); - Result OnDataDrop(Index); - Result OnMemoryFill(const Limits& limits); - Result OnMemoryGrow(const Limits& limits); - Result OnMemoryInit(Index, const Limits& limits); - Result OnMemorySize(const Limits& limits); - Result OnTableCopy(); - Result OnElemDrop(Index); - Result OnTableInit(Index, Index); - Result OnTableGet(Type elem_type); - Result OnTableSet(Type elem_type); - Result OnTableGrow(Type elem_type); - Result OnTableSize(); - Result OnTableFill(Type elem_type); - Result OnRefFuncExpr(Index func_type); - Result OnRefNullExpr(Type type); - Result OnRefIsNullExpr(); - Result OnRethrow(Index depth); - Result OnReturn(); - Result OnSelect(const TypeVector& result_types); - Result OnSimdLaneOp(Opcode, uint64_t); - Result OnSimdLoadLane(Opcode, const Limits& limits, uint64_t); - Result OnSimdStoreLane(Opcode, const Limits& limits, uint64_t); - Result OnSimdShuffleOp(Opcode, v128); - Result OnStore(Opcode, const Limits& limits); - Result OnTernary(Opcode); - Result OnThrow(const TypeVector& sig); - Result OnTry(const TypeVector& param_types, const TypeVector& result_types); - Result OnUnary(Opcode); - Result OnUnreachable(); - Result EndFunction(); - - Result BeginInitExpr(Type type); - Result EndInitExpr(); - - static Result CheckType(Type actual, Type expected); - - private: - void WABT_PRINTF_FORMAT(2, 3) PrintError(const char* fmt, ...); - Result TopLabel(Label** out_label); - void ResetTypeStackToLabel(Label* label); - Result SetUnreachable(); - void PushLabel(LabelType label_type, - const TypeVector& param_types, - const TypeVector& result_types); - Result PopLabel(); - Result CheckLabelType(Label* label, LabelType label_type); - Result Check2LabelTypes(Label* label, - LabelType label_type1, - LabelType label_type2); - Result GetThisFunctionLabel(Label** label); - Result PeekType(Index depth, Type* out_type); - Result PeekAndCheckType(Index depth, Type expected); - Result DropTypes(size_t drop_count); - void PushType(Type type); - void PushTypes(const TypeVector& types); - Result CheckTypeStackEnd(const char* desc); - Result CheckTypes(const TypeVector& actual, const TypeVector& expected); - Result CheckSignature(const TypeVector& sig, const char* desc); - Result CheckReturnSignature(const TypeVector& sig, - const TypeVector& expected, - const char* desc); - Result PopAndCheckSignature(const TypeVector& sig, const char* desc); - Result PopAndCheckCall(const TypeVector& param_types, - const TypeVector& result_types, - const char* desc); - Result PopAndCheck1Type(Type expected, const char* desc); - Result PopAndCheck2Types(Type expected1, Type expected2, const char* desc); - Result PopAndCheck3Types(Type expected1, - Type expected2, - Type expected3, - const char* desc); - Result CheckOpcode1(Opcode opcode, - const Limits* limits = nullptr, - bool has_address_operands = false); - Result CheckOpcode2(Opcode opcode, const Limits* limits = nullptr); - Result CheckOpcode3(Opcode opcode, - const Limits* limits1 = nullptr, - const Limits* limits2 = nullptr, - const Limits* limits3 = nullptr); - Result OnEnd(Label* label, const char* sig_desc, const char* end_desc); - - template <typename... Args> - void PrintStackIfFailed(Result result, const char* desc, Args... args) { - // Minor optimization, check result before constructing the vector to pass - // to the other overload of PrintStackIfFailed. - if (Failed(result)) { - PrintStackIfFailedV(result, desc, {args...}, /*is_end=*/false); - } - } - - void PrintStackIfFailedV(Result, - const char* desc, - const TypeVector&, - bool is_end); - - ErrorCallback error_callback_; - TypeVector type_stack_; - std::vector<Label> label_stack_; - // Cache the expected br_table signature. It will be initialized to `nullptr` - // to represent "any". - TypeVector* br_table_sig_ = nullptr; - Features features_; -}; - -} // namespace wabt - -#endif /* WABT_TYPE_CHECKER_H_ */ diff --git a/src/type.h b/src/type.h deleted file mode 100644 index d9b662aa..00000000 --- a/src/type.h +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2020 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_TYPE_H_ -#define WABT_TYPE_H_ - -#include <cassert> -#include <cstdint> -#include <vector> - -#include "config.h" -#include "src/base-types.h" -#include "src/string-format.h" - -namespace wabt { - -class Type; - -using TypeVector = std::vector<Type>; - -class Type { - public: - // Matches binary format, do not change. - enum Enum : int32_t { - I32 = -0x01, // 0x7f - I64 = -0x02, // 0x7e - F32 = -0x03, // 0x7d - F64 = -0x04, // 0x7c - V128 = -0x05, // 0x7b - I8 = -0x06, // 0x7a : packed-type only, used in gc and as v128 lane - I16 = -0x07, // 0x79 : packed-type only, used in gc and as v128 lane - FuncRef = -0x10, // 0x70 - ExternRef = -0x11, // 0x6f - Reference = -0x15, // 0x6b - Func = -0x20, // 0x60 - Struct = -0x21, // 0x5f - Array = -0x22, // 0x5e - Void = -0x40, // 0x40 - ___ = Void, // Convenient for the opcode table in opcode.h - - Any = 0, // Not actually specified, but useful for type-checking - I8U = 4, // Not actually specified, but used internally with load/store - I16U = 6, // Not actually specified, but used internally with load/store - I32U = 7, // Not actually specified, but used internally with load/store - }; - - Type() = default; // Provided so Type can be member of a union. - Type(int32_t code) - : enum_(static_cast<Enum>(code)), type_index_(kInvalidIndex) {} - Type(Enum e) : enum_(e), type_index_(kInvalidIndex) {} - Type(Enum e, Index type_index) : enum_(e), type_index_(type_index) { - assert(e == Enum::Reference); - } - operator Enum() const { return enum_; } - - bool IsRef() const { - return enum_ == Type::ExternRef || enum_ == Type::FuncRef || - enum_ == Type::Reference; - } - - bool IsReferenceWithIndex() const { return enum_ == Type::Reference; } - - bool IsNullableRef() const { - // Currently all reftypes are nullable - return IsRef(); - } - - std::string GetName() const { - switch (enum_) { - case Type::I32: return "i32"; - case Type::I64: return "i64"; - case Type::F32: return "f32"; - case Type::F64: return "f64"; - case Type::V128: return "v128"; - case Type::I8: return "i8"; - case Type::I16: return "i16"; - case Type::FuncRef: return "funcref"; - case Type::Func: return "func"; - case Type::Void: return "void"; - case Type::Any: return "any"; - case Type::ExternRef: return "externref"; - case Type::Reference: - return StringPrintf("(ref %d)", type_index_); - default: - return StringPrintf("<type_index[%d]>", enum_); - } - } - - const char* GetRefKindName() const { - switch (enum_) { - case Type::FuncRef: return "func"; - case Type::ExternRef: return "extern"; - case Type::Struct: return "struct"; - case Type::Array: return "array"; - default: return "<invalid>"; - } - } - - // Functions for handling types that are an index into the type section. - // These are always positive integers. They occur in the binary format in - // block signatures, e.g. - // - // (block (result i32 i64) ...) - // - // is encoded as - // - // (type $T (func (result i32 i64))) - // ... - // (block (type $T) ...) - // - bool IsIndex() const { return static_cast<int32_t>(enum_) >= 0; } - - Index GetIndex() const { - assert(IsIndex()); - return static_cast<Index>(enum_); - } - - Index GetReferenceIndex() const { - assert(enum_ == Enum::Reference); - return type_index_; - } - - TypeVector GetInlineVector() const { - assert(!IsIndex()); - switch (enum_) { - case Type::Void: - return TypeVector(); - - case Type::I32: - case Type::I64: - case Type::F32: - case Type::F64: - case Type::V128: - case Type::FuncRef: - case Type::ExternRef: - case Type::Reference: - return TypeVector(this, this + 1); - - default: - WABT_UNREACHABLE; - } - } - - private: - Enum enum_; - Index type_index_; // Only used for for Type::Reference -}; - -} // namespace wabt - -#endif // WABT_TYPE_H_ diff --git a/src/utf8.cc b/src/utf8.cc index f3ca98e4..dd95c8c6 100644 --- a/src/utf8.cc +++ b/src/utf8.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/utf8.h" +#include "wabt/utf8.h" #include <cstdint> diff --git a/src/utf8.h b/src/utf8.h deleted file mode 100644 index c3780357..00000000 --- a/src/utf8.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2017 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_UTF8_H_ -#define WABT_UTF8_H_ - -#include <stdlib.h> - -namespace wabt { - -bool IsValidUtf8(const char* s, size_t length); - -} // namespace wabt - -#endif // WABT_UTF8_H_ diff --git a/src/validator.cc b/src/validator.cc index d44764cb..f05018ab 100644 --- a/src/validator.cc +++ b/src/validator.cc @@ -14,20 +14,20 @@ * limitations under the License. */ -#include "src/validator.h" +#include "wabt/validator.h" #include <cassert> #include <cinttypes> #include <cstdarg> #include <cstdio> -#include "config.h" +#include "wabt/config.h" -#include "src/binary-reader.h" -#include "src/cast.h" -#include "src/expr-visitor.h" -#include "src/ir.h" -#include "src/shared-validator.h" +#include "wabt/binary-reader.h" +#include "wabt/cast.h" +#include "wabt/expr-visitor.h" +#include "wabt/ir.h" +#include "wabt/shared-validator.h" namespace wabt { diff --git a/src/validator.h b/src/validator.h deleted file mode 100644 index 23ba72c1..00000000 --- a/src/validator.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_VALIDATOR_H_ -#define WABT_VALIDATOR_H_ - -#include "src/error.h" -#include "src/feature.h" -#include "src/shared-validator.h" - -namespace wabt { - -struct Module; -struct Script; - -// Perform all checks on the script. It is valid if and only if this function -// succeeds. -Result ValidateScript(const Script*, Errors*, const ValidateOptions&); -Result ValidateModule(const Module*, Errors*, const ValidateOptions&); - -} // namespace wabt - -#endif // WABT_VALIDATOR_H_ diff --git a/src/wast-lexer.cc b/src/wast-lexer.cc index 50c5d558..a601b75d 100644 --- a/src/wast-lexer.cc +++ b/src/wast-lexer.cc @@ -14,15 +14,15 @@ * limitations under the License. */ -#include "src/wast-lexer.h" +#include "wabt/wast-lexer.h" #include <cassert> #include <cstdio> -#include "config.h" +#include "wabt/config.h" -#include "src/lexer-source.h" -#include "src/wast-parser.h" +#include "wabt/lexer-source.h" +#include "wabt/wast-parser.h" #define ERROR(...) parser->Error(GetLocation(), __VA_ARGS__) @@ -30,7 +30,7 @@ namespace wabt { namespace { -#include "src/prebuilt/lexer-keywords.cc" +#include "prebuilt/lexer-keywords.cc" } // namespace diff --git a/src/wast-lexer.h b/src/wast-lexer.h deleted file mode 100644 index ddb5b4a3..00000000 --- a/src/wast-lexer.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_WAST_LEXER_H_ -#define WABT_WAST_LEXER_H_ - -#include <cstddef> -#include <cstdio> -#include <memory> - -#include "src/common.h" -#include "src/lexer-source-line-finder.h" -#include "src/literal.h" -#include "src/make-unique.h" -#include "src/opcode.h" -#include "src/token.h" - -namespace wabt { - -class ErrorHandler; -class LexerSource; -class WastParser; - -class WastLexer { - public: - WABT_DISALLOW_COPY_AND_ASSIGN(WastLexer); - - WastLexer(std::unique_ptr<LexerSource> source, std::string_view filename); - - // Convenience functions. - static std::unique_ptr<WastLexer> CreateBufferLexer(std::string_view filename, - const void* data, - size_t size); - - Token GetToken(WastParser* parser); - - // TODO(binji): Move this out of the lexer. - std::unique_ptr<LexerSourceLineFinder> MakeLineFinder() { - return MakeUnique<LexerSourceLineFinder>(source_->Clone()); - } - - private: - static const int kEof = -1; - enum class CharClass { Reserved = 1, Keyword = 2, HexDigit = 4, Digit = 8 }; - - Location GetLocation(); - std::string_view GetText(size_t offset = 0); - - Token BareToken(TokenType); - Token LiteralToken(TokenType, LiteralType); - Token TextToken(TokenType, size_t offset = 0); - - int PeekChar(); - int ReadChar(); - bool MatchChar(char); - bool MatchString(std::string_view); - void Newline(); - bool ReadBlockComment(WastParser*); // Returns false if EOF. - bool ReadLineComment(); // Returns false if EOF. - void ReadWhitespace(); - - static bool IsCharClass(int c, CharClass); - static bool IsDigit(int c) { return IsCharClass(c, CharClass::Digit); } - static bool IsHexDigit(int c) { return IsCharClass(c, CharClass::HexDigit); } - static bool IsKeyword(int c) { return IsCharClass(c, CharClass::Keyword); } - static bool IsReserved(int c) { return IsCharClass(c, CharClass::Reserved); } - - bool ReadNum(); - bool ReadHexNum(); - int ReadReservedChars(); - bool NoTrailingReservedChars() { return ReadReservedChars() == 0; } - void ReadSign(); - Token GetStringToken(WastParser*); - Token GetNumberToken(TokenType); - Token GetHexNumberToken(TokenType); - Token GetInfToken(); - Token GetNanToken(); - Token GetNameEqNumToken(std::string_view name, TokenType); - Token GetIdToken(); - Token GetKeywordToken(); - Token GetReservedToken(); - - std::unique_ptr<LexerSource> source_; - std::string filename_; - int line_; - const char* buffer_; - const char* buffer_end_; - const char* line_start_; - const char* token_start_; - const char* cursor_; -}; - -} // namespace wabt - -#endif /* WABT_WAST_LEXER_H_ */ diff --git a/src/wast-parser.cc b/src/wast-parser.cc index d804e21e..a3cc7a66 100644 --- a/src/wast-parser.cc +++ b/src/wast-parser.cc @@ -14,20 +14,20 @@ * limitations under the License. */ -#include "src/wast-parser.h" - -#include "src/binary-reader-ir.h" -#include "src/binary-reader.h" -#include "src/cast.h" -#include "src/expr-visitor.h" -#include "src/make-unique.h" -#include "src/resolve-names.h" -#include "src/stream.h" -#include "src/utf8.h" -#include "src/validator.h" +#include "wabt/wast-parser.h" + +#include "wabt/binary-reader-ir.h" +#include "wabt/binary-reader.h" +#include "wabt/cast.h" +#include "wabt/expr-visitor.h" +#include "wabt/make-unique.h" +#include "wabt/resolve-names.h" +#include "wabt/stream.h" +#include "wabt/utf8.h" +#include "wabt/validator.h" #define WABT_TRACING 0 -#include "src/tracing.h" +#include "wabt/tracing.h" #define EXPECT(token_type) CHECK_RESULT(Expect(TokenType::token_type)) diff --git a/src/wast-parser.h b/src/wast-parser.h deleted file mode 100644 index bc92bfd6..00000000 --- a/src/wast-parser.h +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_WAST_PARSER_H_ -#define WABT_WAST_PARSER_H_ - -#include <array> -#include <unordered_map> - -#include "src/circular-array.h" -#include "src/error.h" -#include "src/feature.h" -#include "src/intrusive-list.h" -#include "src/ir.h" -#include "src/wast-lexer.h" - -namespace wabt { - -struct WastParseOptions { - WastParseOptions(const Features& features) : features(features) {} - - Features features; - bool debug_parsing = false; -}; - -typedef std::array<TokenType, 2> TokenTypePair; - -class WastParser { - public: - WastParser(WastLexer*, Errors*, WastParseOptions*); - - void WABT_PRINTF_FORMAT(3, 4) Error(Location, const char* format, ...); - Result ParseModule(std::unique_ptr<Module>* out_module); - Result ParseScript(std::unique_ptr<Script>* out_script); - - std::unique_ptr<Script> ReleaseScript(); - - private: - enum class ConstType { - Normal, - Expectation, - }; - - void ErrorUnlessOpcodeEnabled(const Token&); - - // Print an error message listing the expected tokens, as well as an example - // of expected input. - Result ErrorExpected(const std::vector<std::string>& expected, - const char* example = nullptr); - - // Print an error message, and and return Result::Error if the next token is - // '('. This is commonly used after parsing a sequence of s-expressions -- if - // no more can be parsed, we know that a following '(' is invalid. This - // function consumes the '(' so a better error message can be provided - // (assuming the following token was unexpected). - Result ErrorIfLpar(const std::vector<std::string>& expected, - const char* example = nullptr); - - // Returns the next token without consuming it. - Token GetToken(); - - // Returns the location of the next token. - Location GetLocation(); - - // Returns the type of the next token. - TokenType Peek(size_t n = 0); - - // Returns the types of the next two tokens. - TokenTypePair PeekPair(); - - // Returns true if the next token's type is equal to the parameter. - bool PeekMatch(TokenType, size_t n = 0); - - // Returns true if the next token's type is '(' and the following token is - // equal to the parameter. - bool PeekMatchLpar(TokenType); - - // Returns true if the next two tokens can start an Expr. This allows for - // folded expressions, plain instructions and block instructions. - bool PeekMatchExpr(); - - // Returns true if the next two tokens are form reference type - (ref $t) - bool PeekMatchRefType(); - - // Returns true if the next token's type is equal to the parameter. If so, - // then the token is consumed. - bool Match(TokenType); - - // Returns true if the next token's type is equal to '(' and the following - // token is equal to the parameter. If so, then the token is consumed. - bool MatchLpar(TokenType); - - // Like Match(), but prints an error message if the token doesn't match, and - // returns Result::Error. - Result Expect(TokenType); - - // Consume one token and return it. - Token Consume(); - - // Give the Match() function a clearer name when used to optionally consume a - // token (used for printing better error messages). - void ConsumeIfLpar() { Match(TokenType::Lpar); } - - typedef bool SynchronizeFunc(TokenTypePair pair); - - // Attempt to synchronize the token stream by dropping tokens until the - // SynchronizeFunc returns true, or until a token limit is reached. This - // function returns Result::Error if the stream was not able to be - // synchronized. - Result Synchronize(SynchronizeFunc); - - bool ParseBindVarOpt(std::string* name); - Result ParseVar(Var* out_var); - bool ParseVarOpt(Var* out_var, Var default_var = Var()); - Result ParseOffsetExpr(ExprList* out_expr_list); - bool ParseOffsetExprOpt(ExprList* out_expr_list); - Result ParseTextList(std::vector<uint8_t>* out_data); - bool ParseTextListOpt(std::vector<uint8_t>* out_data); - Result ParseVarList(VarVector* out_var_list); - bool ParseElemExprOpt(ExprList* out_elem_expr); - bool ParseElemExprListOpt(ExprListVector* out_list); - bool ParseElemExprVarListOpt(ExprListVector* out_list); - Result ParseValueType(Var* out_type); - Result ParseValueTypeList( - TypeVector* out_type_list, - std::unordered_map<uint32_t, std::string>* type_names); - Result ParseRefKind(Type* out_type); - Result ParseRefType(Type* out_type); - bool ParseRefTypeOpt(Type* out_type); - Result ParseQuotedText(std::string* text, bool check_utf8 = true); - bool ParseOffsetOpt(Address* offset); - bool ParseAlignOpt(Address* align); - Result ParseMemidx(Location loc, Var* memidx); - Result ParseLimitsIndex(Limits*); - Result ParseLimits(Limits*); - Result ParseNat(uint64_t*, bool is_64); - - Result ParseModuleFieldList(Module*); - Result ParseModuleField(Module*); - Result ParseDataModuleField(Module*); - Result ParseElemModuleField(Module*); - Result ParseTagModuleField(Module*); - Result ParseExportModuleField(Module*); - Result ParseFuncModuleField(Module*); - Result ParseTypeModuleField(Module*); - Result ParseGlobalModuleField(Module*); - Result ParseImportModuleField(Module*); - Result ParseMemoryModuleField(Module*); - Result ParseStartModuleField(Module*); - Result ParseTableModuleField(Module*); - - Result ParseExportDesc(Export*); - Result ParseInlineExports(ModuleFieldList*, ExternalKind); - Result ParseInlineImport(Import*); - Result ParseTypeUseOpt(FuncDeclaration*); - Result ParseFuncSignature(FuncSignature*, BindingHash* param_bindings); - Result ParseUnboundFuncSignature(FuncSignature*); - Result ParseBoundValueTypeList(TokenType, - TypeVector*, - BindingHash*, - std::unordered_map<uint32_t, std::string>*, - Index binding_index_offset = 0); - Result ParseUnboundValueTypeList(TokenType, - TypeVector*, - std::unordered_map<uint32_t, std::string>*); - Result ParseResultList(TypeVector*, - std::unordered_map<uint32_t, std::string>*); - Result ParseInstrList(ExprList*); - Result ParseTerminatingInstrList(ExprList*); - Result ParseInstr(ExprList*); - Result ParseCodeMetadataAnnotation(ExprList*); - Result ParsePlainInstr(std::unique_ptr<Expr>*); - Result ParseF32(Const*, ConstType type); - Result ParseF64(Const*, ConstType type); - Result ParseConst(Const*, ConstType type); - Result ParseExternref(Const*); - Result ParseExpectedNan(ExpectedNan* expected); - Result ParseConstList(ConstVector*, ConstType type); - Result ParseBlockInstr(std::unique_ptr<Expr>*); - Result ParseLabelOpt(std::string*); - Result ParseEndLabelOpt(const std::string&); - Result ParseBlockDeclaration(BlockDeclaration*); - Result ParseBlock(Block*); - Result ParseExprList(ExprList*); - Result ParseExpr(ExprList*); - Result ParseCatchInstrList(CatchVector* catches); - Result ParseCatchExprList(CatchVector* catches); - Result ParseGlobalType(Global*); - Result ParseField(Field*); - Result ParseFieldList(std::vector<Field>*); - - template <typename T> - Result ParsePlainInstrVar(Location, std::unique_ptr<Expr>*); - template <typename T> - Result ParseMemoryInstrVar(Location, std::unique_ptr<Expr>*); - template <typename T> - Result ParseLoadStoreInstr(Location, Token, std::unique_ptr<Expr>*); - template <typename T> - Result ParseSIMDLoadStoreInstr(Location loc, - Token token, - std::unique_ptr<Expr>* out_expr); - template <typename T> - Result ParseMemoryExpr(Location, std::unique_ptr<Expr>*); - template <typename T> - Result ParseMemoryBinaryExpr(Location, std::unique_ptr<Expr>*); - Result ParseSimdLane(Location, uint64_t*); - - Result ParseCommandList(Script*, CommandPtrVector*); - Result ParseCommand(Script*, CommandPtr*); - Result ParseAssertExceptionCommand(CommandPtr*); - Result ParseAssertExhaustionCommand(CommandPtr*); - Result ParseAssertInvalidCommand(CommandPtr*); - Result ParseAssertMalformedCommand(CommandPtr*); - Result ParseAssertReturnCommand(CommandPtr*); - Result ParseAssertReturnFuncCommand(CommandPtr*); - Result ParseAssertTrapCommand(CommandPtr*); - Result ParseAssertUnlinkableCommand(CommandPtr*); - Result ParseActionCommand(CommandPtr*); - Result ParseModuleCommand(Script*, CommandPtr*); - Result ParseRegisterCommand(CommandPtr*); - Result ParseInputCommand(CommandPtr*); - Result ParseOutputCommand(CommandPtr*); - - Result ParseAction(ActionPtr*); - Result ParseScriptModule(std::unique_ptr<ScriptModule>*); - - template <typename T> - Result ParseActionCommand(TokenType, CommandPtr*); - template <typename T> - Result ParseAssertActionCommand(TokenType, CommandPtr*); - template <typename T> - Result ParseAssertActionTextCommand(TokenType, CommandPtr*); - template <typename T> - Result ParseAssertScriptModuleCommand(TokenType, CommandPtr*); - - Result ParseSimdV128Const(Const*, TokenType, ConstType); - - void CheckImportOrdering(Module*); - - WastLexer* lexer_; - Index last_module_index_ = kInvalidIndex; - Errors* errors_; - WastParseOptions* options_; - - CircularArray<Token, 2> tokens_; -}; - -Result ParseWatModule(WastLexer* lexer, - std::unique_ptr<Module>* out_module, - Errors*, - WastParseOptions* options); - -Result ParseWastScript(WastLexer* lexer, - std::unique_ptr<Script>* out_script, - Errors*, - WastParseOptions* options); - -} // namespace wabt - -#endif /* WABT_WAST_PARSER_H_ */ diff --git a/src/wat-writer.cc b/src/wat-writer.cc index 265f4285..5b0e6599 100644 --- a/src/wat-writer.cc +++ b/src/wat-writer.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "src/wat-writer.h" +#include "wabt/wat-writer.h" #include <algorithm> #include <array> @@ -27,16 +27,16 @@ #include <string> #include <vector> -#include "src/cast.h" -#include "src/common.h" -#include "src/expr-visitor.h" -#include "src/ir-util.h" -#include "src/ir.h" -#include "src/literal.h" -#include "src/stream.h" +#include "wabt/cast.h" +#include "wabt/common.h" +#include "wabt/expr-visitor.h" +#include "wabt/ir-util.h" +#include "wabt/ir.h" +#include "wabt/literal.h" +#include "wabt/stream.h" #define WABT_TRACING 0 -#include "src/tracing.h" +#include "wabt/tracing.h" #define INDENT_SIZE 2 #define NO_FORCE_NEWLINE 0 diff --git a/src/wat-writer.h b/src/wat-writer.h deleted file mode 100644 index ec8a3eeb..00000000 --- a/src/wat-writer.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2016 WebAssembly Community Group participants - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef WABT_WAT_WRITER_H_ -#define WABT_WAT_WRITER_H_ - -#include "src/common.h" - -namespace wabt { - -struct Module; -class Stream; - -struct WriteWatOptions { - bool fold_exprs = false; // Write folded expressions. - bool inline_export = false; - bool inline_import = false; -}; - -Result WriteWat(Stream*, const Module*, const WriteWatOptions&); - -} // namespace wabt - -#endif /* WABT_WAT_WRITER_H_ */ |