24 return DL.getPointerABIAlignment(AS).value() >= 8 ? 16 : 8;
29 : Ctx(Ctx), Handler(Handler), DL(DL), Executor(Executor) {}
31std::optional<std::string> Library::readStringFromMemory(
const Pointer &Ptr) {
42 Byte B = (*MO)[ValidOffset];
43 if (
B.ConcreteMask != 0xFF) {
45 <<
"Read uninitialized or poison memory while "
46 "parsing C-string at offset "
54 Result.push_back(
static_cast<char>(
B.Value));
66 "Unexpected MemAllocKind for malloc()/new/new[]");
68 const auto &SizeVal =
Args[0];
70 const uint64_t AllocSize = SizeVal.asInteger().getLimitedValue();
71 const unsigned AS =
Type->getPointerAddressSpace();
73 const IntrusiveRefCntPtr<MemoryObject>
Obj =
74 Ctx.allocate(AllocSize,
getMaxAlign(DL, AS), Name, AS,
81 Executor.reportError() <<
"Insufficient heap space.";
87 return Ctx.deriveFromMemoryObject(Obj);
94 "Unexpected MemAllocKind for calloc()");
96 const auto &CountVal =
Args[0];
97 const auto &SizeVal =
Args[1];
99 const APInt &
Count = CountVal.asInteger();
100 const APInt &
Size = SizeVal.asInteger();
102 bool Overflow =
false;
103 const APInt AllocSize =
Count.umul_ov(
Size, Overflow);
106 const unsigned AS =
Type->getPointerAddressSpace();
108 const IntrusiveRefCntPtr<MemoryObject>
Obj =
109 Ctx.allocate(AllocSize.getLimitedValue(),
getMaxAlign(DL, AS), Name, AS,
115 return Ctx.deriveFromMemoryObject(Obj);
119 const auto &PtrVal =
Args[0];
121 auto &Ptr = PtrVal.asPointer();
126 MemoryObject *
Obj = Ctx.checkProvenance(Ptr, [](
const Provenance &) {
131 Executor.reportImmediateUB()
132 <<
"freeing a pointer with nullary provenance.";
137 SmallString<32> AddrStr;
139 Executor.reportImmediateUB()
140 <<
"freeing a pointer that does not point to "
141 "the start of an allocation. Pointer address: 0x"
142 << AddrStr <<
", allocation base: 0x"
148 Executor.reportImmediateUB()
149 <<
"double-freeing a memory object allocated at 0x"
154 if (!
Obj->isHeapAllocated()) {
155 Executor.reportImmediateUB() <<
"freeing a non-heap allocation at 0x"
164 if (!Ctx.free(*Obj)) {
165 Executor.reportImmediateUB() <<
"freeing an invalid pointer at 0x"
175 const AnyValue &Dest =
Args[0];
176 Executor.executeMemTransfer(Dest, Args[1], Args[2], IID,
182 const AnyValue &Dest =
Args[0];
183 Executor.executeMemSet(Dest, Args[1], Args[2]);
188 const auto &PtrVal =
Args[0];
190 const auto StrOpt = readStringFromMemory(PtrVal.asPointer());
194 Handler.onPrint(*StrOpt +
"\n");
195 return AnyValue(APInt(Executor.getIntSize(), 1));
199 const auto &FormatPtrVal =
Args[0];
201 const auto FormatStrOpt = readStringFromMemory(FormatPtrVal.asPointer());
205 const std::string &FormatStr = *FormatStrOpt;
207 raw_string_ostream OS(Output);
208 unsigned ArgIndex = 1;
210 for (
unsigned I = 0;
I < FormatStr.size();) {
211 if (FormatStr[
I] !=
'%') {
212 OS << FormatStr[
I++];
217 if (
I < FormatStr.size() && FormatStr[
I] ==
'%') {
223 while (
I < FormatStr.size() &&
224 StringRef(
"-= #0123456789").
contains(FormatStr[
I]))
227 while (
I < FormatStr.size() && StringRef(
"hljzt").
contains(FormatStr[
I]))
230 if (
I >= FormatStr.size()) {
231 Executor.reportImmediateUB()
232 <<
"Invalid format string in printf: missing conversion specifier.";
237 std::string CleanChunk = FormatStr.substr(Start,
I - Start - 1);
240 [](
char C) {
return StringRef(
"hljzt").contains(
C); }),
243 if (ArgIndex >=
Args.size()) {
244 Executor.reportImmediateUB() <<
"Not enough arguments provided for the "
245 "format string. Required argument for '"
250 const auto &Arg =
Args[ArgIndex++];
251 if (Arg.isPoison()) {
252 Executor.reportImmediateUB()
253 <<
"Poison argument passed to printf for format specifier '"
254 <<
Specifier <<
"' at argument index " << ArgIndex <<
".";
259 (StringRef(
"diuoxXc").contains(Specifier) &&
260 !(Arg.isInteger() && (Arg.asInteger().getBitWidth() == 32 ||
261 Arg.asInteger().getBitWidth() == 64))) ||
262 (StringRef(
"fFeEgGaA").
contains(Specifier) &&
265 (StringRef(
"nps").contains(Specifier) &&
266 !(Arg.isPointer() && Arg.asPointer().address().getBitWidth() <= 64));
269 Executor.reportImmediateUB()
270 <<
"Argument type mismatch in printf for format specifier '"
271 <<
Specifier <<
"' at argument index " << (ArgIndex - 1) <<
".";
278 std::string HostFmt = CleanChunk +
"ll" +
Specifier;
279 OS <<
format(HostFmt.c_str(),
280 static_cast<long long>(Arg.asInteger().getSExtValue()));
289 std::string HostFmt = CleanChunk +
"ll" +
Specifier;
290 OS <<
format(HostFmt.c_str(),
static_cast<unsigned long long>(
291 Arg.asInteger().getZExtValue()));
295 std::string HostFmt = CleanChunk +
Specifier;
296 OS <<
format(HostFmt.c_str(),
297 static_cast<int>(Arg.asInteger().getZExtValue()));
308 std::string HostFmt = CleanChunk +
Specifier;
309 OS <<
format(HostFmt.c_str(), Arg.asFloat().convertToDouble());
314 Executor.store(Arg,
Align(4), AnyValue(APInt(32,
Output.size())),
319 std::string HostFmt = CleanChunk +
"llx";
321 <<
format(HostFmt.c_str(),
322 static_cast<unsigned long long>(
323 Arg.asPointer().address().getZExtValue()));
327 auto StrOpt = readStringFromMemory(Arg.asPointer());
330 std::string HostFmt = CleanChunk +
"s";
331 OS <<
format(HostFmt.c_str(), StrOpt->c_str());
335 Executor.reportImmediateUB()
336 <<
"Unknown or unsupported format specifier '" <<
Specifier
343 Handler.onPrint(Output);
344 return AnyValue(APInt(Executor.getIntSize(),
Output.size()));
348 const auto &RetCodeVal =
Args[0];
351 RetCodeVal.asInteger().getZExtValue());
360AnyValue Library::executeTerminate() {
372 if (Arg.isPoison()) {
373 Executor.reportImmediateUB()
374 <<
"Poison argument passed to a library call at argument index "
395 return executeFree(Args,
399 return executeMemTransfer(Args, Intrinsic::memcpy);
401 case LibFunc_memmove:
402 return executeMemTransfer(Args, Intrinsic::memmove);
405 return executeMemset(Args);
408 return executePuts(Args);
411 return executePrintf(Args);
414 return executeExit(Args);
417 return executeAbort();
419 case LibFunc_terminate:
420 return executeTerminate();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
static constexpr const fltSemantics & IEEEdouble()
Class for arbitrary precision integers.
void toStringUnsigned(SmallVectorImpl< char > &Str, unsigned Radix=10) const
Considers the APInt to be unsigned and converts it into a string in the radix given.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
A parsed version of the target data layout string in and methods for querying it.
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
Represent a constant reference to a string, i.e.
static Twine utohexstr(uint64_t Val)
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static AnyValue poison()
Use getPoisonValue unless you know the scalar type is integer/fp/ptr!
static LLVM_ABI AnyValue getNullValue(Context &Ctx, Type *Ty)
The global context for the interpreter.
An interface for handling events and managing outputs during interpretation.
std::pair< MemoryObject *, uint64_t > verifyMemAccess(const Pointer &Ptr, uint64_t AccessSize, Align Alignment, bool IsStore)
Check if the upcoming memory access is valid.
DiagnosticReporter reportImmediateUB()
std::optional< AnyValue > executeLibcall(LibFunc LF, StringRef Name, FunctionType *FuncType, ArrayRef< AnyValue > Args)
Simulates a libcall.
Library(Context &Ctx, EventHandler &Handler, const DataLayout &DL, ExecutorBase &Executor)
const APInt & address() const
Pointer getWithNewAddr(const APInt &NewAddr) const
LLVM_ABI bool isNullPtr(unsigned AS, const DataLayout &DL) const
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static uint64_t getMaxAlign(const DataLayout &DL, unsigned AS)
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
ArrayRef(const T &OneElt) -> ArrayRef< T >
This struct is a compact representation of a valid (non-zero power of two) alignment.
Representation of a byte in memory.