Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for WASI builds #91051

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion clang/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ CMAKE_DEPENDENT_OPTION(CLANG_PLUGIN_SUPPORT
# If libstdc++ is statically linked, clang-repl needs to statically link libstdc++
# itself, which is not possible in many platforms because of current limitations in
# JIT stack. (more platforms need to be supported by JITLink)
if(NOT LLVM_STATIC_LINK_CXX_STDLIB)
if(NOT LLVM_STATIC_LINK_CXX_STDLIB AND NOT WASI)
set(HAVE_CLANG_REPL_SUPPORT ON)
endif()

Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Driver/Driver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1577,7 +1577,7 @@ bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
CrashDiagDir = "/";
path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
int PID =
#if LLVM_ON_UNIX
#if LLVM_ON_UNIX && !defined(__wasi__)
getpid();
#else
0;
Expand Down
4 changes: 2 additions & 2 deletions libcxxabi/src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ else()
)
endif()

if (LIBCXXABI_ENABLE_THREADS AND (UNIX OR FUCHSIA) AND NOT (APPLE OR CYGWIN)
AND NOT (${CMAKE_SYSTEM_NAME} MATCHES "AIX"))
if (LIBCXXABI_ENABLE_THREADS AND (UNIX OR FUCHSIA OR WASI) AND NOT
(APPLE OR CYGWIN) AND NOT (${CMAKE_SYSTEM_NAME} MATCHES "AIX"))
list(APPEND LIBCXXABI_SOURCES
cxa_thread_atexit.cpp
)
Expand Down
4 changes: 4 additions & 0 deletions llvm/cmake/modules/HandleLLVMOptions.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,10 @@ elseif(FUCHSIA OR UNIX)
else()
set(LLVM_HAVE_LINK_VERSION_SCRIPT 1)
endif()
elseif(WASI)
set(LLVM_ON_WIN32 0)
set(LLVM_ON_UNIX 1)
set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Generic")
set(LLVM_ON_WIN32 0)
set(LLVM_ON_UNIX 0)
Expand Down
4 changes: 2 additions & 2 deletions llvm/include/llvm/ADT/bit.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@
#endif

#if defined(_MSC_VER) && !defined(_DEBUG)
#include <cstdlib> // for _byteswap_{ushort,ulong,uint64}
#include <cstdlib> // for _byteswap_{ushort,ulong,uint64}
#endif

#if defined(__linux__) || defined(__GNU__) || defined(__HAIKU__) || \
defined(__Fuchsia__) || defined(__EMSCRIPTEN__) || defined(__NetBSD__) || \
defined(__OpenBSD__) || defined(__DragonFly__)
defined(__OpenBSD__) || defined(__DragonFly__) || defined(__wasi__)
#include <endian.h>
#elif defined(_AIX)
#include <sys/machine.h>
Expand Down
2 changes: 2 additions & 0 deletions llvm/include/llvm/Support/Memory.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ namespace sys {
private:
void *Address; ///< Address of first byte of memory area
size_t AllocatedSize; ///< Size, in bytes of the memory area
#ifndef __wasi__
unsigned Flags = 0;
#endif
friend class Memory;
};

Expand Down
2 changes: 2 additions & 0 deletions llvm/lib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ add_subdirectory(Remarks)
add_subdirectory(Debuginfod)
add_subdirectory(DebugInfo)
add_subdirectory(DWP)
if (NOT WASI)
add_subdirectory(ExecutionEngine)
endif ()
add_subdirectory(Target)
add_subdirectory(AsmParser)
add_subdirectory(LineEditor)
Expand Down
48 changes: 30 additions & 18 deletions llvm/lib/Support/CrashRecoveryContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@
//===----------------------------------------------------------------------===//

#include "llvm/Support/CrashRecoveryContext.h"

#include "llvm/Config/llvm-config.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ExitCodes.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/thread.h"
#include <cassert>
#include <mutex>
#ifndef __wasi__
#include <setjmp.h>
#endif

using namespace llvm;

Expand All @@ -31,7 +34,9 @@ struct CrashRecoveryContextImpl {
const CrashRecoveryContextImpl *Next;

CrashRecoveryContext *CRC;
#ifndef __wasi__
::jmp_buf JumpBuffer;
#endif
volatile unsigned Failed : 1;
unsigned SwitchedThread : 1;
unsigned ValidJumpBuffer : 1;
Expand Down Expand Up @@ -72,9 +77,11 @@ struct CrashRecoveryContextImpl {

CRC->RetCode = RetCode;

#ifndef __wasi__
// Jump back to the RunSafely we were called under.
if (ValidJumpBuffer)
longjmp(JumpBuffer, 1);
#endif

// Otherwise let the caller decide of the outcome of the crash. Currently
// this occurs when using SEH on Windows with MSVC or clang-cl.
Expand Down Expand Up @@ -118,7 +125,7 @@ CrashRecoveryContext::~CrashRecoveryContext() {
}
IsRecoveringFromCrash = PC;

CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *)Impl;
delete CRCI;
}

Expand Down Expand Up @@ -154,8 +161,8 @@ void CrashRecoveryContext::Disable() {
uninstallExceptionOrSignalHandlers();
}

void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
{
void CrashRecoveryContext::registerCleanup(
CrashRecoveryContextCleanup *cleanup) {
if (!cleanup)
return;
if (head)
Expand All @@ -164,16 +171,15 @@ void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
head = cleanup;
}

void
CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
void CrashRecoveryContext::unregisterCleanup(
CrashRecoveryContextCleanup *cleanup) {
if (!cleanup)
return;
if (cleanup == head) {
head = cleanup->next;
if (head)
head->prev = nullptr;
}
else {
} else {
cleanup->prev->next = cleanup->next;
if (cleanup->next)
cleanup->next->prev = cleanup->prev;
Expand Down Expand Up @@ -263,16 +269,14 @@ bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {

#include "llvm/Support/Windows/WindowsSupport.h"

static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo) {
// DBG_PRINTEXCEPTION_WIDE_C is not properly defined on all supported
// compilers and platforms, so we define it manually.
constexpr ULONG DbgPrintExceptionWideC = 0x4001000AL;
switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
{
switch (ExceptionInfo->ExceptionRecord->ExceptionCode) {
case DBG_PRINTEXCEPTION_C:
case DbgPrintExceptionWideC:
case 0x406D1388: // set debugger thread name
case 0x406D1388: // set debugger thread name
return EXCEPTION_CONTINUE_EXECUTION;
}

Expand Down Expand Up @@ -307,7 +311,7 @@ static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
// CrashRecoveryContext at all. So we make use of a thread-local
// exception table. The handles contained in here will either be
// non-NULL, valid VEH handles, or NULL.
static LLVM_THREAD_LOCAL const void* sCurrentExceptionHandle;
static LLVM_THREAD_LOCAL const void *sCurrentExceptionHandle;

static void installExceptionOrSignalHandlers() {
// We can set up vectored exception handling now. We will install our
Expand Down Expand Up @@ -342,10 +346,11 @@ static void uninstallExceptionOrSignalHandlers() {
// reliable fashion -- if we get a signal outside of a crash recovery context we
// simply disable crash recovery and raise the signal again.

#ifndef __wasi__
#include <signal.h>

static const int Signals[] =
{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
static const int Signals[] = {SIGABRT, SIGBUS, SIGFPE,
SIGILL, SIGSEGV, SIGTRAP};
static const unsigned NumSignals = std::size(Signals);
static struct sigaction PrevActions[NumSignals];

Expand Down Expand Up @@ -389,8 +394,10 @@ static void CrashRecoverySignalHandler(int Signal) {
if (CRCI)
const_cast<CrashRecoveryContextImpl *>(CRCI)->HandleCrash(RetCode, Signal);
}
#endif

static void installExceptionOrSignalHandlers() {
#ifndef __wasi__
// Setup the signal handler.
struct sigaction Handler;
Handler.sa_handler = CrashRecoverySignalHandler;
Expand All @@ -400,12 +407,15 @@ static void installExceptionOrSignalHandlers() {
for (unsigned i = 0; i != NumSignals; ++i) {
sigaction(Signals[i], &Handler, &PrevActions[i]);
}
#endif
}

static void uninstallExceptionOrSignalHandlers() {
#ifndef __wasi__
// Restore the previous signal handlers.
for (unsigned i = 0; i != NumSignals; ++i)
sigaction(Signals[i], &PrevActions[i], nullptr);
#endif
}

#endif // !_WIN32
Expand All @@ -418,9 +428,11 @@ bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
Impl = CRCI;

CRCI->ValidJumpBuffer = true;
#ifndef __wasi__
if (setjmp(CRCI->JumpBuffer) != 0) {
return false;
}
#endif
}

Fn();
Expand Down Expand Up @@ -469,7 +481,7 @@ bool CrashRecoveryContext::throwIfCrash(int RetCode) {
return false;
#if defined(_WIN32)
::RaiseException(RetCode, 0, 0, NULL);
#else
#elif !defined(__wasi__)
llvm::sys::unregisterHandlers();
raise(RetCode - 128);
#endif
Expand Down Expand Up @@ -502,7 +514,7 @@ struct RunSafelyOnThreadInfo {

static void RunSafelyOnThread_Dispatch(void *UserData) {
RunSafelyOnThreadInfo *Info =
reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
reinterpret_cast<RunSafelyOnThreadInfo *>(UserData);

if (Info->UseBackgroundPriority)
setThreadBackgroundPriority();
Expand All @@ -512,7 +524,7 @@ static void RunSafelyOnThread_Dispatch(void *UserData) {
bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
unsigned RequestedStackSize) {
bool UseBackgroundPriority = hasThreadBackgroundPriority();
RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
RunSafelyOnThreadInfo Info = {Fn, this, UseBackgroundPriority, false};
llvm::thread Thread(RequestedStackSize == 0
? std::nullopt
: std::optional<unsigned>(RequestedStackSize),
Expand Down
19 changes: 11 additions & 8 deletions llvm/lib/Support/LockFileManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
#include <unistd.h>
#endif

#if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1050)
#if defined(__APPLE__) && \
defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \
(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1050)
#define USE_OSX_GETHOSTUUID 1
#else
#define USE_OSX_GETHOSTUUID 0
Expand Down Expand Up @@ -94,7 +96,7 @@ static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
StringRef UUIDRef(UUIDStr);
HostID.append(UUIDRef.begin(), UUIDRef.end());

#elif LLVM_ON_UNIX
#elif LLVM_ON_UNIX && !defined(__wasi__)
char HostName[256];
HostName[255] = 0;
HostName[0] = 0;
Expand All @@ -116,9 +118,11 @@ bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
if (getHostID(StoredHostID))
return true; // Conservatively assume it's executing on error.

// Check whether the process is dead. If so, we're done.
// Check whether the process is dead. If so, we're done.
#ifndef __wasi__ // no other processes anyway
if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
return false;
#endif
#endif

return true;
Expand All @@ -136,9 +140,10 @@ namespace {
class RemoveUniqueLockFileOnSignal {
StringRef Filename;
bool RemoveImmediately;

public:
RemoveUniqueLockFileOnSignal(StringRef Name)
: Filename(Name), RemoveImmediately(true) {
: Filename(Name), RemoveImmediately(true) {
sys::RemoveFileOnSignal(Filename, nullptr);
}

Expand All @@ -157,8 +162,7 @@ class RemoveUniqueLockFileOnSignal {

} // end anonymous namespace

LockFileManager::LockFileManager(StringRef FileName)
{
LockFileManager::LockFileManager(StringRef FileName) {
this->FileName = FileName;
if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
std::string S("failed to obtain absolute path for ");
Expand Down Expand Up @@ -217,8 +221,7 @@ LockFileManager::LockFileManager(StringRef FileName)

while (true) {
// Create a link from the lock file name. If this succeeds, we're done.
std::error_code EC =
sys::fs::create_link(UniqueLockFileName, LockFileName);
std::error_code EC = sys::fs::create_link(UniqueLockFileName, LockFileName);
if (!EC) {
RemoveUniqueFile.lockAcquired();
return;
Expand Down
20 changes: 20 additions & 0 deletions llvm/lib/Support/Unix/Memory.inc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
extern "C" void __clear_cache(void *, void *);
#endif

#ifndef __wasi__
static int getPosixProtectionFlags(unsigned Flags) {
switch (Flags & llvm::sys::Memory::MF_RWE_MASK) {
case llvm::sys::Memory::MF_READ:
Expand Down Expand Up @@ -66,6 +67,7 @@ static int getPosixProtectionFlags(unsigned Flags) {
// Provide a default return value as required by some compilers.
return PROT_NONE;
}
#endif

namespace llvm {
namespace sys {
Expand All @@ -77,6 +79,17 @@ MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
if (NumBytes == 0)
return MemoryBlock();

#ifdef __wasi__
MemoryBlock Result;
Result.Address = malloc(NumBytes);
if (!Result.Address) {
EC = errnoAsErrorCode();
Result.AllocatedSize = 0;
} else {
Result.AllocatedSize = NumBytes;
}
return Result;
#else
// On platforms that have it, we can use MAP_ANON to get a memory-mapped
// page without file backing, but we need a fallback of opening /dev/zero
// for strictly POSIX platforms instead.
Expand Down Expand Up @@ -146,14 +159,19 @@ MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
}

return Result;
#endif
}

std::error_code Memory::releaseMappedMemory(MemoryBlock &M) {
#ifdef __wasi__
free(M.Address);
#else
if (M.Address == nullptr || M.AllocatedSize == 0)
return std::error_code();

if (0 != ::munmap(M.Address, M.AllocatedSize))
return errnoAsErrorCode();
#endif

M.Address = nullptr;
M.AllocatedSize = 0;
Expand All @@ -163,6 +181,7 @@ std::error_code Memory::releaseMappedMemory(MemoryBlock &M) {

std::error_code Memory::protectMappedMemory(const MemoryBlock &M,
unsigned Flags) {
#ifndef __wasi__
static const Align PageSize = Align(Process::getPageSizeEstimate());
if (M.Address == nullptr || M.AllocatedSize == 0)
return std::error_code();
Expand Down Expand Up @@ -200,6 +219,7 @@ std::error_code Memory::protectMappedMemory(const MemoryBlock &M,

if (InvalidateCache)
Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
#endif

return std::error_code();
}
Expand Down
Loading
Loading