You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by tq...@apache.org on 2025/05/02 13:37:30 UTC
(tvm) 01/03: [WIN] Initial stab to make win ffi compile
This is an automated email from the ASF dual-hosted git repository.
tqchen pushed a commit to branch refactor-s2
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit 184a813e7783741d14063ea582fbd6dd2bc73e7d
Author: tqchen <tq...@gmail.com>
AuthorDate: Wed Apr 30 11:23:35 2025 -0400
[WIN] Initial stab to make win ffi compile
Still need followup refactors
---
ffi/CMakeLists.txt | 3 +
ffi/cmake/Utils/CxxWarning.cmake | 2 +-
ffi/cmake/Utils/Library.cmake | 11 ++
ffi/include/tvm/ffi/any.h | 1 +
ffi/include/tvm/ffi/base_details.h | 12 +-
ffi/include/tvm/ffi/container/container_details.h | 2 +-
ffi/include/tvm/ffi/container/map.h | 11 +-
ffi/include/tvm/ffi/error.h | 12 +-
ffi/include/tvm/ffi/function.h | 6 +-
ffi/include/tvm/ffi/function_details.h | 13 ++-
ffi/include/tvm/ffi/type_traits.h | 8 +-
ffi/src/ffi/container.cc | 53 ++++-----
ffi/src/ffi/dtype.cc | 6 +-
ffi/src/ffi/testing.cc | 12 +-
ffi/src/ffi/traceback_win.cc | 128 ++++++++++++++++++++++
ffi/tests/cpp/CMakeLists.txt | 1 +
16 files changed, 216 insertions(+), 65 deletions(-)
diff --git a/ffi/CMakeLists.txt b/ffi/CMakeLists.txt
index 5ba8fd0f2f..11e380e46f 100644
--- a/ffi/CMakeLists.txt
+++ b/ffi/CMakeLists.txt
@@ -59,6 +59,7 @@ target_link_libraries(tvm_ffi_header INTERFACE dlpack_header)
########## Target: `tvm_ffi` ##########
add_library(tvm_ffi_objs OBJECT
"${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/traceback.cc"
+ "${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/traceback_win.cc"
"${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/object.cc"
"${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/function.cc"
"${CMAKE_CURRENT_SOURCE_DIR}/src/ffi/ndarray.cc"
@@ -110,6 +111,8 @@ target_link_libraries(tvm_ffi_static PUBLIC tvm_ffi_header)
install(TARGETS tvm_ffi_static DESTINATION lib${LIB_SUFFIX})
install(TARGETS tvm_ffi_shared DESTINATION lib${LIB_SUFFIX})
+add_msvc_compact_defs(tvm_ffi_objs)
+
########## Adding tests ##########
if (${PROJECT_NAME} STREQUAL ${CMAKE_PROJECT_NAME})
diff --git a/ffi/cmake/Utils/CxxWarning.cmake b/ffi/cmake/Utils/CxxWarning.cmake
index 649ce2911a..c272bfdf7b 100644
--- a/ffi/cmake/Utils/CxxWarning.cmake
+++ b/ffi/cmake/Utils/CxxWarning.cmake
@@ -23,7 +23,7 @@ function(add_cxx_warning target_name)
endif()
# MSVC
if(MSVC)
- target_compile_options(${target_name} PRIVATE "/W4" "/WX")
+ # target_compile_options(${target_name} PRIVATE "/W4" "/WX")
return()
endif()
message(FATAL_ERROR "Unsupported compiler: ${CMAKE_CXX_COMPILER_ID}")
diff --git a/ffi/cmake/Utils/Library.cmake b/ffi/cmake/Utils/Library.cmake
index 9f91c53ce6..6afea393d6 100644
--- a/ffi/cmake/Utils/Library.cmake
+++ b/ffi/cmake/Utils/Library.cmake
@@ -28,6 +28,17 @@ function(add_dsymutil target_name)
endif()
endfunction()
+function(add_msvc_compact_defs target_name)
+ # running if we are under msvc
+ if(MSVC)
+ target_compile_definitions(${target_name} PUBLIC -DWIN32_LEAN_AND_MEAN)
+ target_compile_definitions(${target_name} PUBLIC -D_CRT_SECURE_NO_WARNINGS)
+ target_compile_definitions(${target_name} PUBLIC -D_SCL_SECURE_NO_WARNINGS)
+ target_compile_definitions(${target_name} PUBLIC -D_ENABLE_EXTENDED_ALIGNED_STORAGE)
+ target_compile_definitions(${target_name} PUBLIC -DNOMINMAX)
+ endif()
+endfunction()
+
function(add_target_from_obj target_name obj_target_name)
add_library(${target_name}_static STATIC $<TARGET_OBJECTS:${obj_target_name}>)
set_target_properties(
diff --git a/ffi/include/tvm/ffi/any.h b/ffi/include/tvm/ffi/any.h
index 049c07066c..3f787e7571 100644
--- a/ffi/include/tvm/ffi/any.h
+++ b/ffi/include/tvm/ffi/any.h
@@ -304,6 +304,7 @@ class Any {
}
return *std::move(opt);
}
+
/*
* \brief Check if the two Any are same type and value in shallow comparison.
* \param other The other Any
diff --git a/ffi/include/tvm/ffi/base_details.h b/ffi/include/tvm/ffi/base_details.h
index 9debc5b8ee..cc54be77bb 100644
--- a/ffi/include/tvm/ffi/base_details.h
+++ b/ffi/include/tvm/ffi/base_details.h
@@ -31,6 +31,10 @@
#include <cstddef>
#include <utility>
+#if defined(_MSC_VER)
+#include <windows.h>
+#endif
+
#if defined(_MSC_VER)
#define TVM_FFI_INLINE __forceinline
#else
@@ -95,8 +99,8 @@
#define TVM_FFI_LOG_EXCEPTION_CALL_END(Name) \
} \
catch (const std::exception& err) { \
- std::cout << "Exception caught during " << #Name << ":\n" << err.what() << std::endl; \
- throw err; \
+ std::cerr << "Exception caught during " << #Name << ":\n" << err.what() << std::endl; \
+ exit(-1); \
}
/*!
@@ -197,7 +201,7 @@ TVM_FFI_INLINE uint64_t StableHashBytes(const char* data, size_t size) {
const char* end = it + size;
uint64_t result = 0;
for (; it + 8 <= end; it += 8) {
- if (TVM_FFI_IO_NO_ENDIAN_SWAP) {
+ if constexpr (TVM_FFI_IO_NO_ENDIAN_SWAP) {
u.a[0] = it[0];
u.a[1] = it[1];
u.a[2] = it[2];
@@ -240,7 +244,7 @@ TVM_FFI_INLINE uint64_t StableHashBytes(const char* data, size_t size) {
it += 1;
a += 1;
}
- if (!TVM_FFI_IO_NO_ENDIAN_SWAP) {
+ if constexpr (!TVM_FFI_IO_NO_ENDIAN_SWAP) {
std::swap(u.a[0], u.a[7]);
std::swap(u.a[1], u.a[6]);
std::swap(u.a[2], u.a[5]);
diff --git a/ffi/include/tvm/ffi/container/container_details.h b/ffi/include/tvm/ffi/container/container_details.h
index 9f54b32ecb..39ebcb4a58 100644
--- a/ffi/include/tvm/ffi/container/container_details.h
+++ b/ffi/include/tvm/ffi/container/container_details.h
@@ -107,7 +107,7 @@ class InplaceArrayBase {
* \brief Destroy the Inplace Array Base object
*/
~InplaceArrayBase() {
- if (!(std::is_standard_layout<ElemType>::value && std::is_trivial<ElemType>::value)) {
+ if constexpr (!(std::is_standard_layout<ElemType>::value && std::is_trivial<ElemType>::value)) {
size_t size = Self()->GetSize();
for (size_t i = 0; i < size; ++i) {
ElemType* fp = reinterpret_cast<ElemType*>(AddressOf(i));
diff --git a/ffi/include/tvm/ffi/container/map.h b/ffi/include/tvm/ffi/container/map.h
index 26eeee7925..7d805d61e9 100644
--- a/ffi/include/tvm/ffi/container/map.h
+++ b/ffi/include/tvm/ffi/container/map.h
@@ -292,7 +292,10 @@ class SmallMapObj : public MapObj, public details::InplaceArrayBase<SmallMapObj,
}
KVType* begin = static_cast<KVType*>(AddressOf(0));
// call destructor to destroy the item in `begin + index`
- (begin + index)->KVType::~KVType();
+ // Explicit call Any::~Any() to destroy the Any object
+ // Favor this over ~KVType as MSVC may not support ~KVType (need the original name)
+ (begin + index)->first.Any::~Any();
+ (begin + index)->second.Any::~Any();
// IMPORTANT: We do direct raw memmove to bring later items to the current position
// to preserve the order of insertion.
// This works because direct memory copy preserves the Any's move semantics.
@@ -1008,8 +1011,10 @@ class DenseMapObj : public MapObj {
void SetEmpty() const { Meta() = uint8_t(kEmptySlot); }
/*! \brief Destruct the item in the entry */
void DestructData() const {
- // explict call destructor to destroy the item
- (&Data())->KVType::~KVType();
+ // explicit call destructor to destroy the item
+ // Favor this over ~KVType as MSVC may not support ~KVType (need the original name)
+ (&Data())->first.Any::~Any();
+ (&Data())->second.Any::~Any();
}
/*! \brief Set the entry to be protected */
void SetProtected() const { Meta() = uint8_t(kProtectedSlot); }
diff --git a/ffi/include/tvm/ffi/error.h b/ffi/include/tvm/ffi/error.h
index 7473853c6c..8c97ebc8e9 100644
--- a/ffi/include/tvm/ffi/error.h
+++ b/ffi/include/tvm/ffi/error.h
@@ -84,8 +84,8 @@ class ErrorObj : public Object, public TVMFFIErrorInfo {
* \brief Update the traceback of the error object.
* \param traceback The traceback to update.
*/
- void UpdateTraceback(const char* traceback) {
- this->traceback_data_ = traceback;
+ void UpdateTraceback(const char* traceback_str) {
+ this->traceback_data_ = traceback_str;
this->traceback = this->traceback_data_.c_str();
this->what_data_ = (std::string("Traceback (most recent call last):\n") + this->traceback +
this->kind + ": " + this->message + '\n');
@@ -135,11 +135,6 @@ class ErrorBuilder {
explicit ErrorBuilder(std::string kind, std::string traceback, bool log_before_throw)
: kind_(kind), traceback_(traceback), log_before_throw_(log_before_throw) {}
-// MSVC disable warning in error builder as it is exepected
-#ifdef _MSC_VER
-#pragma disagnostic push
-#pragma warning(disable : 4722)
-#endif
// avoid inline to reduce binary size, error throw path do not need to be fast
[[noreturn]] ~ErrorBuilder() noexcept(false) {
::tvm::ffi::Error error(std::move(kind_), stream_.str(), std::move(traceback_));
@@ -148,9 +143,6 @@ class ErrorBuilder {
}
throw error;
}
-#ifdef _MSC_VER
-#pragma disagnostic pop
-#endif
std::ostringstream& stream() { return stream_; }
diff --git a/ffi/include/tvm/ffi/function.h b/ffi/include/tvm/ffi/function.h
index d5e31372c6..22cc553a61 100644
--- a/ffi/include/tvm/ffi/function.h
+++ b/ffi/include/tvm/ffi/function.h
@@ -346,9 +346,9 @@ class Function : public ObjectRef {
static Function ImportFromExternDLL(Function other) {
const FunctionObj* other_func = static_cast<const FunctionObj*>(other.get());
// the other function comes from the same dll, no action needed
- if (other_func->safe_call == FunctionObj::SafeCall ||
- other_func->safe_call == details::ImportedFunctionObjImpl::SafeCall ||
- other_func->safe_call == details::ExternCFunctionObjImpl::SafeCall) {
+ if (other_func->safe_call == &(FunctionObj::SafeCall) ||
+ other_func->safe_call == &(details::ImportedFunctionObjImpl::SafeCall) ||
+ other_func->safe_call == &(details::ExternCFunctionObjImpl::SafeCall)) {
return other;
}
// the other function coems from a different library
diff --git a/ffi/include/tvm/ffi/function_details.h b/ffi/include/tvm/ffi/function_details.h
index f877a45272..0244398efe 100644
--- a/ffi/include/tvm/ffi/function_details.h
+++ b/ffi/include/tvm/ffi/function_details.h
@@ -39,7 +39,10 @@ namespace details {
/*!
* \brief Empty struct, used to reduce unused variable in global static initialization.
*/
-struct EmptyStruct {};
+struct EmptyStruct {
+ /*! \brief at least one byte to ensure address */
+ uint8_t pad;
+};
template <typename ArgType>
struct Arg2Str {
@@ -203,8 +206,12 @@ TVM_FFI_INLINE void unpack_call(const std::string* optional_name, const F& f, co
int32_t num_args, Any* rv) {
using FuncInfo = FunctionInfo<F>;
FGetFuncSignature f_sig = FuncInfo::Sig;
- static_assert(FuncInfo::unpacked_supported,
- "The function signature cannot support unpacked call");
+
+ // somehow MSVC does not support the static constexpr member in this case, function is fine
+#ifndef _MSC_VER
+ static_assert(FuncInfo::unpacked_supported, "The function signature do not support unpacked");
+#endif
+
if (nargs != num_args) {
TVM_FFI_THROW(TypeError) << "Mismatched number of arguments when calling: `"
<< (optional_name == nullptr ? "" : *optional_name)
diff --git a/ffi/include/tvm/ffi/type_traits.h b/ffi/include/tvm/ffi/type_traits.h
index f8a24ac177..d350aea82a 100644
--- a/ffi/include/tvm/ffi/type_traits.h
+++ b/ffi/include/tvm/ffi/type_traits.h
@@ -140,9 +140,7 @@ struct TypeTraits<std::nullptr_t> : public TypeTraitsBase {
return nullptr;
}
- static TVM_FFI_INLINE std::nullptr_t MoveFromAnyStorageAfterCheck(TVMFFIAny* src) {
- return nullptr;
- }
+ static TVM_FFI_INLINE std::nullptr_t MoveFromAnyStorageAfterCheck(TVMFFIAny*) { return nullptr; }
static TVM_FFI_INLINE std::optional<std::nullptr_t> TryConvertFromAnyView(const TVMFFIAny* src) {
if (src->type_index == TypeIndex::kTVMFFINone) {
@@ -256,7 +254,7 @@ struct TypeTraits<Int, std::enable_if_t<std::is_integral_v<Int>>> : public TypeT
return src->type_index == TypeIndex::kTVMFFIInt;
}
- static TVM_FFI_INLINE int CopyFromAnyStorageAfterCheck(const TVMFFIAny* src) {
+ static TVM_FFI_INLINE Int CopyFromAnyStorageAfterCheck(const TVMFFIAny* src) {
return static_cast<Int>(src->v_int64);
}
@@ -406,7 +404,7 @@ struct TypeTraits<DLTensor*> : public TypeTraitsBase {
result->v_ptr = src;
}
- static TVM_FFI_INLINE void MoveToAny(DLTensor* src, TVMFFIAny* result) {
+ static TVM_FFI_INLINE void MoveToAny(DLTensor*, TVMFFIAny*) {
TVM_FFI_THROW(RuntimeError)
<< "DLTensor* cannot be held in Any as it does not retain ownership, use NDArray instead";
}
diff --git a/ffi/src/ffi/container.cc b/ffi/src/ffi/container.cc
index 885e8395ed..563505b74c 100644
--- a/ffi/src/ffi/container.cc
+++ b/ffi/src/ffi/container.cc
@@ -39,7 +39,6 @@ TVM_FFI_REGISTER_GLOBAL("ffi.ArrayGetItem")
TVM_FFI_REGISTER_GLOBAL("ffi.ArraySize").set_body_typed([](const ffi::ArrayObj* n) -> int64_t {
return static_cast<int64_t>(n->size());
});
-
// Map
TVM_FFI_REGISTER_GLOBAL("ffi.Map").set_body_packed([](ffi::PackedArgs args, Any* ret) {
TVM_FFI_ICHECK_EQ(args.size() % 2, 0);
@@ -60,33 +59,35 @@ TVM_FFI_REGISTER_GLOBAL("ffi.MapGetItem")
TVM_FFI_REGISTER_GLOBAL("ffi.MapCount")
.set_body_typed([](const ffi::MapObj* n, const Any& k) -> int64_t { return n->count(k); });
+// Favor struct outside function scope as MSVC may have bug for in fn scope struct.
+class MapForwardIterFunctor {
+ public:
+ MapForwardIterFunctor(ffi::MapObj::iterator iter, ffi::MapObj::iterator end)
+ : iter_(iter), end_(end) {}
+ // 0 get current key
+ // 1 get current value
+ // 2 move to next: return true if success, false if end
+ Any operator()(int command) const {
+ if (command == 0) {
+ return (*iter_).first;
+ } else if (command == 1) {
+ return (*iter_).second;
+ } else {
+ ++iter_;
+ if (iter_ == end_) {
+ return false;
+ }
+ return true;
+ }
+ }
+
+ private:
+ mutable ffi::MapObj::iterator iter_;
+ ffi::MapObj::iterator end_;
+};
+
TVM_FFI_REGISTER_GLOBAL("ffi.MapForwardIterFunctor")
.set_body_typed([](const ffi::MapObj* n) -> ffi::Function {
- class MapForwardIterFunctor {
- public:
- MapForwardIterFunctor(ffi::MapObj::iterator iter, ffi::MapObj::iterator end)
- : iter_(iter), end_(end) {}
- // 0 get current key
- // 1 get current value
- // 2 move to next: return true if success, false if end
- Any operator()(int command) const {
- if (command == 0) {
- return (*iter_).first;
- } else if (command == 1) {
- return (*iter_).second;
- } else {
- ++iter_;
- if (iter_ == end_) {
- return false;
- }
- return true;
- }
- }
-
- private:
- mutable ffi::MapObj::iterator iter_;
- ffi::MapObj::iterator end_;
- };
return ffi::Function::FromUnpacked(MapForwardIterFunctor(n->begin(), n->end()));
});
diff --git a/ffi/src/ffi/dtype.cc b/ffi/src/ffi/dtype.cc
index 25691b9350..a065c70389 100644
--- a/ffi/src/ffi/dtype.cc
+++ b/ffi/src/ffi/dtype.cc
@@ -207,8 +207,8 @@ inline DLDataType StringViewToDLDataType_(std::string_view str) {
const char* scan;
auto parse_float = [&](const std::string_view& str, int offset, int code, int bits) {
- dtype.code = code;
- dtype.bits = bits;
+ dtype.code = static_cast<uint8_t>(code);
+ dtype.bits = static_cast<uint8_t>(bits);
scan = str.data() + offset;
char* endpt = nullptr;
if (*scan == 'x') {
@@ -288,7 +288,7 @@ inline DLDataType StringViewToDLDataType_(std::string_view str) {
dtype.bits = 16;
scan = str.data() + 6;
} else if (str.compare(0, 6, "custom") == 0) {
- dtype.code = details::ParseCustomDataTypeCode(str, &scan);
+ dtype.code = static_cast<uint8_t>(details::ParseCustomDataTypeCode(str, &scan));
} else {
scan = str.data();
TVM_FFI_THROW(ValueError) << "unknown dtype `" << str << '`';
diff --git a/ffi/src/ffi/testing.cc b/ffi/src/ffi/testing.cc
index 73f247f242..b4dc5b718a 100644
--- a/ffi/src/ffi/testing.cc
+++ b/ffi/src/ffi/testing.cc
@@ -26,6 +26,12 @@
namespace tvm {
namespace ffi {
+void TestRaiseError(String kind, String msg) {
+ throw ffi::Error(kind, msg, TVM_FFI_TRACEBACK_HERE);
+}
+
+TVM_FFI_REGISTER_GLOBAL("testing.test_raise_error").set_body_typed(TestRaiseError);
+
TVM_FFI_REGISTER_GLOBAL("testing.nop").set_body_packed([](PackedArgs args, Any* ret) {
*ret = args[0];
});
@@ -41,12 +47,6 @@ TVM_FFI_REGISTER_GLOBAL("testing.apply").set_body_packed([](PackedArgs args, Any
TestApply(f, args.Slice(1), ret);
});
-void TestRaiseError(String kind, String msg) {
- throw ffi::Error(kind, msg, TVM_FFI_TRACEBACK_HERE);
-}
-
-TVM_FFI_REGISTER_GLOBAL("testing.test_raise_error").set_body_typed(TestRaiseError);
-
TVM_FFI_REGISTER_GLOBAL("testing.run_check_signal").set_body_typed([](int nsec) {
for (int i = 0; i < nsec; ++i) {
if (TVMFFIEnvCheckSignals() != 0) {
diff --git a/ffi/src/ffi/traceback_win.cc b/ffi/src/ffi/traceback_win.cc
new file mode 100644
index 0000000000..786b70447a
--- /dev/null
+++ b/ffi/src/ffi/traceback_win.cc
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+/*!
+ * \file traceback_win.cc
+ * \brief Traceback implementation on windows platform
+ * \note We use the term "traceback" to be consistent with python naming convention.
+ */
+#ifdef _MSC_VER
+
+#include <tvm/ffi/c_api.h>
+#include <tvm/ffi/error.h>
+
+#include "./traceback.h"
+
+namespace tvm {
+namespace ffi {
+namespace {
+
+#include <dbghelp.h>
+#include <windows.h>
+
+#include <iostream>
+#include <vector>
+
+#pragma comment(lib, "DbgHelp.lib")
+
+std::string Traceback() {
+ TracebackStorage traceback;
+ HANDLE process = GetCurrentProcess();
+ HANDLE thread = GetCurrentThread();
+
+ SymInitialize(process, NULL, TRUE);
+ CONTEXT context = {};
+ RtlCaptureContext(&context);
+
+ STACKFRAME64 stack = {};
+ DWORD machine_type;
+
+#if defined(_M_X64)
+ machine_type = IMAGE_FILE_MACHINE_AMD64;
+ stack.AddrPC.Offset = context.Rip;
+ stack.AddrFrame.Offset = context.Rbp;
+ stack.AddrStack.Offset = context.Rsp;
+#elif defined(_M_IX86)
+ machine_type = IMAGE_FILE_MACHINE_I386;
+ stack.AddrPC.Offset = context.Eip;
+ stack.AddrFrame.Offset = context.Ebp;
+ stack.AddrStack.Offset = context.Esp;
+#else
+#error "Platform not supported!"
+#endif
+
+ stack.AddrPC.Mode = AddrModeFlat;
+ stack.AddrFrame.Mode = AddrModeFlat;
+ stack.AddrStack.Mode = AddrModeFlat;
+
+ while (!traceback.ExceedTracebackLimit()) {
+ if (!StackWalk64(machine_type, process, thread, &stack, &context, nullptr,
+ SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) {
+ break;
+ }
+
+ if (stack.AddrPC.Offset == 0) {
+ break;
+ }
+ const char* filename = nullptr;
+ const char* symbol = "<unknown>";
+ int lineno = 0;
+ // Get file and line number
+ IMAGEHLP_LINE64 line_info = {};
+ line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
+ DWORD displacement32 = 0;
+
+ if (SymGetLineFromAddr64(process, stack.AddrPC.Offset, &displacement32, &line_info)) {
+ filename = line_info.FileName;
+ lineno = line_info.LineNumber;
+ }
+ // allocate symbol info that aligns to the SYMBOL_INFO
+ // we use u64 here to be safe
+ size_t total_symbol_bytes = sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR);
+ size_t total_u64_words = (total_symbol_bytes + 7) / 8;
+ static_assert(8 % alignof(SYMBOL_INFO) == 0);
+ std::vector<uint64_t> symbol_buffer(total_u64_words, 0);
+ PSYMBOL_INFO symbol_info = reinterpret_cast<PSYMBOL_INFO>(symbol_buffer.data());
+ symbol_info->SizeOfStruct = sizeof(SYMBOL_INFO);
+ symbol_info->MaxNameLen = MAX_SYM_NAME;
+ DWORD64 displacement = 0;
+ if (SymFromAddr(process, stack.AddrPC.Offset, &displacement, symbol_info)) {
+ symbol = symbol_info->Name;
+ }
+
+ if (ShouldStopTraceback(filename, symbol)) {
+ break;
+ }
+ if (ShouldExcludeFrame(filename, symbol)) {
+ continue;
+ }
+ traceback.Append(filename, symbol, lineno);
+ }
+ SymCleanup(process);
+ return traceback.GetTraceback();
+}
+} // namespace
+} // namespace ffi
+} // namespace tvm
+
+const char* TVMFFITraceback(const char*, int, const char*) {
+ static thread_local std::string traceback_str;
+ traceback_str = ::tvm::ffi::Traceback();
+ return traceback_str.c_str();
+}
+#endif // _MSC_VER
diff --git a/ffi/tests/cpp/CMakeLists.txt b/ffi/tests/cpp/CMakeLists.txt
index ce0b318d41..3ae2df73c8 100644
--- a/ffi/tests/cpp/CMakeLists.txt
+++ b/ffi/tests/cpp/CMakeLists.txt
@@ -17,6 +17,7 @@ set_target_properties(
add_cxx_warning(tvm_ffi_tests)
add_sanitizer_address(tvm_ffi_tests)
add_dsymutil(tvm_ffi_tests)
+add_msvc_compact_defs(tvm_ffi_tests)
target_link_libraries(tvm_ffi_tests PRIVATE tvm_ffi_shared)
add_googletest(tvm_ffi_tests)