| 1 |
//=== OrcV2CBindingsMemoryManager.c - OrcV2 Memory Manager C Bindings Demo ===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
// |
| 9 |
// This demo illustrates the C-API bindings for custom memory managers in |
| 10 |
// ORCv2. They are used here to place generated code into manually allocated |
| 11 |
// buffers that are subsequently marked as executable. |
| 12 |
// |
| 13 |
//===----------------------------------------------------------------------===// |
| 14 |
|
| 15 |
#include "llvm-c/Core.h" |
| 16 |
#include "llvm-c/Error.h" |
| 17 |
#include "llvm-c/LLJIT.h" |
| 18 |
#include "llvm-c/OrcEE.h" |
| 19 |
#include "llvm-c/Support.h" |
| 20 |
#include "llvm-c/Target.h" |
| 21 |
|
| 22 |
#include <assert.h> |
| 23 |
#include <stdio.h> |
| 24 |
#include <stdlib.h> |
| 25 |
|
| 26 |
#if defined(_WIN32) |
| 27 |
#include <windows.h> |
| 28 |
#else |
| 29 |
#include <dlfcn.h> |
| 30 |
#include <sys/mman.h> |
| 31 |
#endif |
| 32 |
|
| 33 |
struct Section { |
| 34 |
void *Ptr; |
| 35 |
size_t Size; |
| 36 |
LLVMBool IsCode; |
| 37 |
}; |
| 38 |
|
| 39 |
char CtxCtxPlaceholder; |
| 40 |
char CtxPlaceholder; |
| 41 |
|
| 42 |
#define MaxSections 16 |
| 43 |
static size_t SectionCount = 0; |
| 44 |
static struct Section Sections[MaxSections]; |
| 45 |
|
| 46 |
void *addSection(size_t Size, LLVMBool IsCode) { |
| 47 |
if (SectionCount >= MaxSections) { |
| 48 |
fprintf(stderr, "addSection(): Too many sections!\n"); |
| 49 |
abort(); |
| 50 |
} |
| 51 |
|
| 52 |
#if defined(_WIN32) |
| 53 |
void *Ptr = |
| 54 |
VirtualAlloc(NULL, Size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
| 55 |
if (!Ptr) { |
| 56 |
fprintf(stderr, "addSection(): Memory allocation failed!\n"); |
| 57 |
abort(); |
| 58 |
} |
| 59 |
#else |
| 60 |
void *Ptr = mmap(NULL, Size, PROT_READ | PROT_WRITE, |
| 61 |
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); |
| 62 |
if (Ptr == MAP_FAILED) { |
| 63 |
fprintf(stderr, "addSection(): Memory allocation failed!\n"); |
| 64 |
abort(); |
| 65 |
} |
| 66 |
#endif |
| 67 |
|
| 68 |
Sections[SectionCount].Ptr = Ptr; |
| 69 |
Sections[SectionCount].Size = Size; |
| 70 |
Sections[SectionCount].IsCode = IsCode; |
| 71 |
SectionCount++; |
| 72 |
return Ptr; |
| 73 |
} |
| 74 |
|
| 75 |
// Callbacks to create the context for the subsequent functions (not used in |
| 76 |
// this example) |
| 77 |
void *memCreateContext(void *CtxCtx) { |
| 78 |
assert(CtxCtx == &CtxCtxPlaceholder && "Unexpected CtxCtx value"); |
| 79 |
return &CtxPlaceholder; |
| 80 |
} |
| 81 |
|
| 82 |
void memNotifyTerminating(void *CtxCtx) { |
| 83 |
assert(CtxCtx == &CtxCtxPlaceholder && "Unexpected CtxCtx value"); |
| 84 |
} |
| 85 |
|
| 86 |
uint8_t *memAllocate(void *Opaque, uintptr_t Size, unsigned Align, unsigned Id, |
| 87 |
const char *Name) { |
| 88 |
printf("Allocated code section \"%s\"\n", Name); |
| 89 |
return addSection(Size, 1); |
| 90 |
} |
| 91 |
|
| 92 |
uint8_t *memAllocateData(void *Opaque, uintptr_t Size, unsigned Align, |
| 93 |
unsigned Id, const char *Name, LLVMBool ReadOnly) { |
| 94 |
printf("Allocated data section \"%s\"\n", Name); |
| 95 |
return addSection(Size, 0); |
| 96 |
} |
| 97 |
|
| 98 |
LLVMBool memFinalize(void *Opaque, char **Err) { |
| 99 |
printf("Marking code sections as executable ..\n"); |
| 100 |
for (size_t i = 0; i < SectionCount; ++i) { |
| 101 |
if (Sections[i].IsCode) { |
| 102 |
LLVMBool fail; |
| 103 |
#if defined(_WIN32) |
| 104 |
DWORD unused; |
| 105 |
fail = VirtualProtect(Sections[i].Ptr, Sections[i].Size, |
| 106 |
PAGE_EXECUTE_READ, &unused) == 0; |
| 107 |
#else |
| 108 |
fail = mprotect(Sections[i].Ptr, Sections[i].Size, |
| 109 |
PROT_READ | PROT_EXEC) == -1; |
| 110 |
#endif |
| 111 |
if (fail) { |
| 112 |
fprintf(stderr, "Could not mark code section as executable!\n"); |
| 113 |
abort(); |
| 114 |
} |
| 115 |
} |
| 116 |
} |
| 117 |
return 0; |
| 118 |
} |
| 119 |
|
| 120 |
void memDestroy(void *Opaque) { |
| 121 |
assert(Opaque == &CtxPlaceholder && "Unexpected Ctx value"); |
| 122 |
printf("Releasing section memory ..\n"); |
| 123 |
for (size_t i = 0; i < SectionCount; ++i) { |
| 124 |
LLVMBool fail; |
| 125 |
#if defined(_WIN32) |
| 126 |
fail = VirtualFree(Sections[i].Ptr, 0, MEM_RELEASE) == 0; |
| 127 |
#else |
| 128 |
fail = munmap(Sections[i].Ptr, Sections[i].Size) == -1; |
| 129 |
#endif |
| 130 |
if (fail) { |
| 131 |
fprintf(stderr, "Could not release memory for section!"); |
| 132 |
abort(); |
| 133 |
} |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
LLVMOrcObjectLayerRef objectLinkingLayerCreator(void *Opaque, |
| 138 |
LLVMOrcExecutionSessionRef ES, |
| 139 |
const char *Triple) { |
| 140 |
return LLVMOrcCreateRTDyldObjectLinkingLayerWithMCJITMemoryManagerLikeCallbacks( |
| 141 |
ES, &CtxCtxPlaceholder, memCreateContext, memNotifyTerminating, |
| 142 |
memAllocate, memAllocateData, memFinalize, memDestroy); |
| 143 |
} |
| 144 |
|
| 145 |
int handleError(LLVMErrorRef Err) { |
| 146 |
char *ErrMsg = LLVMGetErrorMessage(Err); |
| 147 |
fprintf(stderr, "Error: %s\n", ErrMsg); |
| 148 |
LLVMDisposeErrorMessage(ErrMsg); |
| 149 |
return 1; |
| 150 |
} |
| 151 |
|
| 152 |
LLVMOrcThreadSafeModuleRef createDemoModule(void) { |
| 153 |
// Create an LLVMContext. |
| 154 |
LLVMContextRef Ctx = LLVMContextCreate(); |
| 155 |
|
| 156 |
// Create a new LLVM module. |
| 157 |
LLVMModuleRef M = LLVMModuleCreateWithNameInContext("demo", Ctx); |
| 158 |
|
| 159 |
// Add a "sum" function": |
| 160 |
// - Create the function type and function instance. |
| 161 |
LLVMTypeRef Int32Type = LLVMInt32TypeInContext(Ctx); |
| 162 |
LLVMTypeRef ParamTypes[] = {Int32Type, Int32Type}; |
| 163 |
LLVMTypeRef SumFunctionType = LLVMFunctionType(Int32Type, ParamTypes, 2, 0); |
| 164 |
LLVMValueRef SumFunction = LLVMAddFunction(M, "sum", SumFunctionType); |
| 165 |
|
| 166 |
// - Add a basic block to the function. |
| 167 |
LLVMBasicBlockRef EntryBB = |
| 168 |
LLVMAppendBasicBlockInContext(Ctx, SumFunction, "entry"); |
| 169 |
|
| 170 |
// - Add an IR builder and point it at the end of the basic block. |
| 171 |
LLVMBuilderRef Builder = LLVMCreateBuilderInContext(Ctx); |
| 172 |
LLVMPositionBuilderAtEnd(Builder, EntryBB); |
| 173 |
|
| 174 |
// - Get the two function arguments and use them co construct an "add" |
| 175 |
// instruction. |
| 176 |
LLVMValueRef SumArg0 = LLVMGetParam(SumFunction, 0); |
| 177 |
LLVMValueRef SumArg1 = LLVMGetParam(SumFunction, 1); |
| 178 |
LLVMValueRef Result = LLVMBuildAdd(Builder, SumArg0, SumArg1, "result"); |
| 179 |
|
| 180 |
// - Build the return instruction. |
| 181 |
LLVMBuildRet(Builder, Result); |
| 182 |
|
| 183 |
// Create a new ThreadSafeContext to hold the context. |
| 184 |
LLVMOrcThreadSafeContextRef TSCtx = |
| 185 |
LLVMOrcCreateNewThreadSafeContextFromLLVMContext(Ctx); |
| 186 |
|
| 187 |
// Our demo module is now complete. Wrap it and our ThreadSafeContext in a |
| 188 |
// ThreadSafeModule. |
| 189 |
LLVMOrcThreadSafeModuleRef TSM = LLVMOrcCreateNewThreadSafeModule(M, TSCtx); |
| 190 |
|
| 191 |
// Dispose of our local ThreadSafeContext value. The underlying LLVMContext |
| 192 |
// will be kept alive by our ThreadSafeModule, TSM. |
| 193 |
LLVMOrcDisposeThreadSafeContext(TSCtx); |
| 194 |
|
| 195 |
// Return the result. |
| 196 |
return TSM; |
| 197 |
} |
| 198 |
|
| 199 |
int main(int argc, const char *argv[]) { |
| 200 |
|
| 201 |
int MainResult = 0; |
| 202 |
|
| 203 |
// Parse command line arguments and initialize LLVM Core. |
| 204 |
LLVMParseCommandLineOptions(argc, argv, ""); |
| 205 |
|
| 206 |
// Initialize native target codegen and asm printer. |
| 207 |
LLVMInitializeNativeTarget(); |
| 208 |
LLVMInitializeNativeAsmPrinter(); |
| 209 |
|
| 210 |
// Create the JIT instance. |
| 211 |
LLVMOrcLLJITRef J; |
| 212 |
{ |
| 213 |
LLVMErrorRef Err; |
| 214 |
|
| 215 |
LLVMOrcLLJITBuilderRef Builder = LLVMOrcCreateLLJITBuilder(); |
| 216 |
LLVMOrcLLJITBuilderSetObjectLinkingLayerCreator( |
| 217 |
Builder, objectLinkingLayerCreator, NULL); |
| 218 |
|
| 219 |
if ((Err = LLVMOrcCreateLLJIT(&J, Builder))) { |
| 220 |
MainResult = handleError(Err); |
| 221 |
goto llvm_shutdown; |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
// Create our demo module. |
| 226 |
LLVMOrcThreadSafeModuleRef TSM = createDemoModule(); |
| 227 |
|
| 228 |
// Add our demo module to the JIT. |
| 229 |
{ |
| 230 |
LLVMOrcJITDylibRef MainJD = LLVMOrcLLJITGetMainJITDylib(J); |
| 231 |
LLVMErrorRef Err; |
| 232 |
if ((Err = LLVMOrcLLJITAddLLVMIRModule(J, MainJD, TSM))) { |
| 233 |
// If adding the ThreadSafeModule fails then we need to clean it up |
| 234 |
// ourselves. If adding it succeeds the JIT will manage the memory. |
| 235 |
LLVMOrcDisposeThreadSafeModule(TSM); |
| 236 |
MainResult = handleError(Err); |
| 237 |
goto jit_cleanup; |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
// Look up the address of our demo entry point. |
| 242 |
LLVMOrcJITTargetAddress SumAddr; |
| 243 |
{ |
| 244 |
LLVMErrorRef Err; |
| 245 |
if ((Err = LLVMOrcLLJITLookup(J, &SumAddr, "sum"))) { |
| 246 |
MainResult = handleError(Err); |
| 247 |
goto jit_cleanup; |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
// If we made it here then everything succeeded. Execute our JIT'd code. |
| 252 |
int32_t (*Sum)(int32_t, int32_t) = (int32_t(*)(int32_t, int32_t))SumAddr; |
| 253 |
int32_t Result = Sum(1, 2); |
| 254 |
|
| 255 |
// Print the result. |
| 256 |
printf("1 + 2 = %i\n", Result); |
| 257 |
|
| 258 |
jit_cleanup: |
| 259 |
// Destroy our JIT instance. This will clean up any memory that the JIT has |
| 260 |
// taken ownership of. This operation is non-trivial (e.g. it may need to |
| 261 |
// JIT static destructors) and may also fail. In that case we want to render |
| 262 |
// the error to stderr, but not overwrite any existing return value. |
| 263 |
{ |
| 264 |
LLVMErrorRef Err; |
| 265 |
if ((Err = LLVMOrcDisposeLLJIT(J))) { |
| 266 |
int NewFailureResult = handleError(Err); |
| 267 |
if (MainResult == 0) |
| 268 |
MainResult = NewFailureResult; |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
llvm_shutdown: |
| 273 |
// Shut down LLVM. |
| 274 |
LLVMShutdown(); |
| 275 |
|
| 276 |
return MainResult; |
| 277 |
} |