Skip to content

Commit e1c9c7a

Browse files
committed
Add support for building clang on WASI.
1 parent a573b26 commit e1c9c7a

File tree

13 files changed

+184
-44
lines changed

13 files changed

+184
-44
lines changed

clang/lib/Driver/Driver.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1577,7 +1577,7 @@ bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
15771577
CrashDiagDir = "/";
15781578
path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
15791579
int PID =
1580-
#if LLVM_ON_UNIX
1580+
#if LLVM_ON_UNIX && !defined(__wasi__)
15811581
getpid();
15821582
#else
15831583
0;

llvm/include/llvm/ADT/bit.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,12 @@
2424
#endif
2525

2626
#if defined(_MSC_VER) && !defined(_DEBUG)
27-
#include <cstdlib> // for _byteswap_{ushort,ulong,uint64}
27+
#include <cstdlib> // for _byteswap_{ushort,ulong,uint64}
2828
#endif
2929

3030
#if defined(__linux__) || defined(__GNU__) || defined(__HAIKU__) || \
3131
defined(__Fuchsia__) || defined(__EMSCRIPTEN__) || defined(__NetBSD__) || \
32-
defined(__OpenBSD__) || defined(__DragonFly__)
32+
defined(__OpenBSD__) || defined(__DragonFly__) || defined(__wasi__)
3333
#include <endian.h>
3434
#elif defined(_AIX)
3535
#include <sys/machine.h>

llvm/include/llvm/Support/Memory.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ namespace sys {
4141
private:
4242
void *Address; ///< Address of first byte of memory area
4343
size_t AllocatedSize; ///< Size, in bytes of the memory area
44+
#ifndef __wasi__
4445
unsigned Flags = 0;
46+
#endif
4547
friend class Memory;
4648
};
4749

llvm/lib/Support/CrashRecoveryContext.cpp

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@
77
//===----------------------------------------------------------------------===//
88

99
#include "llvm/Support/CrashRecoveryContext.h"
10+
1011
#include "llvm/Config/llvm-config.h"
1112
#include "llvm/Support/ErrorHandling.h"
1213
#include "llvm/Support/ExitCodes.h"
1314
#include "llvm/Support/Signals.h"
1415
#include "llvm/Support/thread.h"
1516
#include <cassert>
1617
#include <mutex>
18+
#ifndef __wasi__
1719
#include <setjmp.h>
20+
#endif
1821

1922
using namespace llvm;
2023

@@ -31,7 +34,9 @@ struct CrashRecoveryContextImpl {
3134
const CrashRecoveryContextImpl *Next;
3235

3336
CrashRecoveryContext *CRC;
37+
#ifndef __wasi__
3438
::jmp_buf JumpBuffer;
39+
#endif
3540
volatile unsigned Failed : 1;
3641
unsigned SwitchedThread : 1;
3742
unsigned ValidJumpBuffer : 1;
@@ -72,9 +77,11 @@ struct CrashRecoveryContextImpl {
7277

7378
CRC->RetCode = RetCode;
7479

80+
#ifndef __wasi__
7581
// Jump back to the RunSafely we were called under.
7682
if (ValidJumpBuffer)
7783
longjmp(JumpBuffer, 1);
84+
#endif
7885

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

121-
CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *) Impl;
128+
CrashRecoveryContextImpl *CRCI = (CrashRecoveryContextImpl *)Impl;
122129
delete CRCI;
123130
}
124131

@@ -154,8 +161,8 @@ void CrashRecoveryContext::Disable() {
154161
uninstallExceptionOrSignalHandlers();
155162
}
156163

157-
void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
158-
{
164+
void CrashRecoveryContext::registerCleanup(
165+
CrashRecoveryContextCleanup *cleanup) {
159166
if (!cleanup)
160167
return;
161168
if (head)
@@ -164,16 +171,15 @@ void CrashRecoveryContext::registerCleanup(CrashRecoveryContextCleanup *cleanup)
164171
head = cleanup;
165172
}
166173

167-
void
168-
CrashRecoveryContext::unregisterCleanup(CrashRecoveryContextCleanup *cleanup) {
174+
void CrashRecoveryContext::unregisterCleanup(
175+
CrashRecoveryContextCleanup *cleanup) {
169176
if (!cleanup)
170177
return;
171178
if (cleanup == head) {
172179
head = cleanup->next;
173180
if (head)
174181
head->prev = nullptr;
175-
}
176-
else {
182+
} else {
177183
cleanup->prev->next = cleanup->next;
178184
if (cleanup->next)
179185
cleanup->next->prev = cleanup->prev;
@@ -263,16 +269,14 @@ bool CrashRecoveryContext::RunSafely(function_ref<void()> Fn) {
263269

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

266-
static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
267-
{
272+
static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo) {
268273
// DBG_PRINTEXCEPTION_WIDE_C is not properly defined on all supported
269274
// compilers and platforms, so we define it manually.
270275
constexpr ULONG DbgPrintExceptionWideC = 0x4001000AL;
271-
switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
272-
{
276+
switch (ExceptionInfo->ExceptionRecord->ExceptionCode) {
273277
case DBG_PRINTEXCEPTION_C:
274278
case DbgPrintExceptionWideC:
275-
case 0x406D1388: // set debugger thread name
279+
case 0x406D1388: // set debugger thread name
276280
return EXCEPTION_CONTINUE_EXECUTION;
277281
}
278282

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

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

349+
#ifndef __wasi__
345350
#include <signal.h>
346351

347-
static const int Signals[] =
348-
{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
352+
static const int Signals[] = {SIGABRT, SIGBUS, SIGFPE,
353+
SIGILL, SIGSEGV, SIGTRAP};
349354
static const unsigned NumSignals = std::size(Signals);
350355
static struct sigaction PrevActions[NumSignals];
351356

@@ -389,8 +394,10 @@ static void CrashRecoverySignalHandler(int Signal) {
389394
if (CRCI)
390395
const_cast<CrashRecoveryContextImpl *>(CRCI)->HandleCrash(RetCode, Signal);
391396
}
397+
#endif
392398

393399
static void installExceptionOrSignalHandlers() {
400+
#ifndef __wasi__
394401
// Setup the signal handler.
395402
struct sigaction Handler;
396403
Handler.sa_handler = CrashRecoverySignalHandler;
@@ -400,12 +407,15 @@ static void installExceptionOrSignalHandlers() {
400407
for (unsigned i = 0; i != NumSignals; ++i) {
401408
sigaction(Signals[i], &Handler, &PrevActions[i]);
402409
}
410+
#endif
403411
}
404412

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

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

420430
CRCI->ValidJumpBuffer = true;
431+
#ifndef __wasi__
421432
if (setjmp(CRCI->JumpBuffer) != 0) {
422433
return false;
423434
}
435+
#endif
424436
}
425437

426438
Fn();
@@ -469,7 +481,7 @@ bool CrashRecoveryContext::throwIfCrash(int RetCode) {
469481
return false;
470482
#if defined(_WIN32)
471483
::RaiseException(RetCode, 0, 0, NULL);
472-
#else
484+
#elif !defined(__wasi__)
473485
llvm::sys::unregisterHandlers();
474486
raise(RetCode - 128);
475487
#endif
@@ -502,7 +514,7 @@ struct RunSafelyOnThreadInfo {
502514

503515
static void RunSafelyOnThread_Dispatch(void *UserData) {
504516
RunSafelyOnThreadInfo *Info =
505-
reinterpret_cast<RunSafelyOnThreadInfo*>(UserData);
517+
reinterpret_cast<RunSafelyOnThreadInfo *>(UserData);
506518

507519
if (Info->UseBackgroundPriority)
508520
setThreadBackgroundPriority();
@@ -512,7 +524,7 @@ static void RunSafelyOnThread_Dispatch(void *UserData) {
512524
bool CrashRecoveryContext::RunSafelyOnThread(function_ref<void()> Fn,
513525
unsigned RequestedStackSize) {
514526
bool UseBackgroundPriority = hasThreadBackgroundPriority();
515-
RunSafelyOnThreadInfo Info = { Fn, this, UseBackgroundPriority, false };
527+
RunSafelyOnThreadInfo Info = {Fn, this, UseBackgroundPriority, false};
516528
llvm::thread Thread(RequestedStackSize == 0
517529
? std::nullopt
518530
: std::optional<unsigned>(RequestedStackSize),

llvm/lib/Support/LockFileManager.cpp

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@
3434
#include <unistd.h>
3535
#endif
3636

37-
#if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1050)
37+
#if defined(__APPLE__) && \
38+
defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \
39+
(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1050)
3840
#define USE_OSX_GETHOSTUUID 1
3941
#else
4042
#define USE_OSX_GETHOSTUUID 0
@@ -94,7 +96,7 @@ static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
9496
StringRef UUIDRef(UUIDStr);
9597
HostID.append(UUIDRef.begin(), UUIDRef.end());
9698

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

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

124128
return true;
@@ -136,9 +140,10 @@ namespace {
136140
class RemoveUniqueLockFileOnSignal {
137141
StringRef Filename;
138142
bool RemoveImmediately;
143+
139144
public:
140145
RemoveUniqueLockFileOnSignal(StringRef Name)
141-
: Filename(Name), RemoveImmediately(true) {
146+
: Filename(Name), RemoveImmediately(true) {
142147
sys::RemoveFileOnSignal(Filename, nullptr);
143148
}
144149

@@ -157,8 +162,7 @@ class RemoveUniqueLockFileOnSignal {
157162

158163
} // end anonymous namespace
159164

160-
LockFileManager::LockFileManager(StringRef FileName)
161-
{
165+
LockFileManager::LockFileManager(StringRef FileName) {
162166
this->FileName = FileName;
163167
if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
164168
std::string S("failed to obtain absolute path for ");
@@ -217,8 +221,7 @@ LockFileManager::LockFileManager(StringRef FileName)
217221

218222
while (true) {
219223
// Create a link from the lock file name. If this succeeds, we're done.
220-
std::error_code EC =
221-
sys::fs::create_link(UniqueLockFileName, LockFileName);
224+
std::error_code EC = sys::fs::create_link(UniqueLockFileName, LockFileName);
222225
if (!EC) {
223226
RemoveUniqueFile.lockAcquired();
224227
return;

llvm/lib/Support/Unix/Memory.inc

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
3636
extern "C" void __clear_cache(void *, void *);
3737
#endif
3838

39+
#ifndef __wasi__
3940
static int getPosixProtectionFlags(unsigned Flags) {
4041
switch (Flags & llvm::sys::Memory::MF_RWE_MASK) {
4142
case llvm::sys::Memory::MF_READ:
@@ -66,6 +67,7 @@ static int getPosixProtectionFlags(unsigned Flags) {
6667
// Provide a default return value as required by some compilers.
6768
return PROT_NONE;
6869
}
70+
#endif
6971

7072
namespace llvm {
7173
namespace sys {
@@ -77,6 +79,17 @@ MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
7779
if (NumBytes == 0)
7880
return MemoryBlock();
7981

82+
#ifdef __wasi__
83+
MemoryBlock Result;
84+
Result.Address = malloc(NumBytes);
85+
if (!Result.Address) {
86+
EC = errnoAsErrorCode();
87+
Result.AllocatedSize = 0;
88+
} else {
89+
Result.AllocatedSize = NumBytes;
90+
}
91+
return Result;
92+
#else
8093
// On platforms that have it, we can use MAP_ANON to get a memory-mapped
8194
// page without file backing, but we need a fallback of opening /dev/zero
8295
// for strictly POSIX platforms instead.
@@ -146,14 +159,19 @@ MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
146159
}
147160

148161
return Result;
162+
#endif
149163
}
150164

151165
std::error_code Memory::releaseMappedMemory(MemoryBlock &M) {
166+
#ifdef __wasi__
167+
free(M.Address);
168+
#else
152169
if (M.Address == nullptr || M.AllocatedSize == 0)
153170
return std::error_code();
154171

155172
if (0 != ::munmap(M.Address, M.AllocatedSize))
156173
return errnoAsErrorCode();
174+
#endif
157175

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

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

201220
if (InvalidateCache)
202221
Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
222+
#endif
203223

204224
return std::error_code();
205225
}

0 commit comments

Comments
 (0)