LLVM 24.0.0git
Library.cpp
Go to the documentation of this file.
1//===- Library.cpp - Library calls for llubi ------------------------------===//
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 file implements common libcalls for llubi.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Library.h"
14#include "llvm/ADT/STLExtras.h"
16#include "llvm/IR/InstrTypes.h"
17#include "llvm/Support/Format.h"
19
20namespace llvm::ubi {
21
22static uint64_t getMaxAlign(const DataLayout &DL, unsigned AS) {
23 // Return an alignment of 16 for 64-bit platforms, and 8 for 32-bit ones.
24 return DL.getPointerABIAlignment(AS).value() >= 8 ? 16 : 8;
25}
26
28 ExecutorBase &Executor)
29 : Ctx(Ctx), Handler(Handler), DL(DL), Executor(Executor) {}
30
31std::optional<std::string> Library::readStringFromMemory(const Pointer &Ptr) {
32 std::string Result;
33 const APInt &Address = Ptr.address();
34 uint64_t Offset = 0;
35
36 while (true) {
37 auto [MO, ValidOffset] = Executor.verifyMemAccess(
38 Ptr.getWithNewAddr(Address + Offset), 1, Align(1), /*IsStore=*/false);
39 if (!MO)
40 return std::nullopt;
41
42 Byte B = (*MO)[ValidOffset];
43 if (B.ConcreteMask != 0xFF) {
44 Executor.reportImmediateUB()
45 << "Read uninitialized or poison memory while "
46 "parsing C-string at offset "
47 << Offset << ".";
48 return std::nullopt;
49 }
50
51 if (B.Value == 0)
52 break;
53
54 Result.push_back(static_cast<char>(B.Value));
55 ++Offset;
56 }
57
58 return Result;
59}
60
61AnyValue Library::executeMalloc(StringRef Name, Type *Type,
63 MemAllocKind AllocKind) {
64 assert((AllocKind == MemAllocKind::Malloc || AllocKind == MemAllocKind::New ||
65 AllocKind == MemAllocKind::NewArray) &&
66 "Unexpected MemAllocKind for malloc()/new/new[]");
67
68 const auto &SizeVal = Args[0];
69
70 const uint64_t AllocSize = SizeVal.asInteger().getLimitedValue();
71 const unsigned AS = Type->getPointerAddressSpace();
72
73 const IntrusiveRefCntPtr<MemoryObject> Obj =
74 Ctx.allocate(AllocSize, getMaxAlign(DL, AS), Name, AS,
76
77 if (!Obj) {
78 if (AllocKind == MemAllocKind::New || AllocKind == MemAllocKind::NewArray) {
79 // FIXME: As llubi doesn't support stack unwinding yet, we report an error
80 // when new/new[] fails.
81 Executor.reportError() << "Insufficient heap space.";
82 return AnyValue::poison();
83 }
84 return AnyValue::getNullValue(Ctx, Type);
85 }
86
87 return Ctx.deriveFromMemoryObject(Obj);
88}
89
90AnyValue Library::executeCalloc(StringRef Name, Type *Type,
92 MemAllocKind AllocKind) {
93 assert(AllocKind == MemAllocKind::Malloc &&
94 "Unexpected MemAllocKind for calloc()");
95
96 const auto &CountVal = Args[0];
97 const auto &SizeVal = Args[1];
98
99 const APInt &Count = CountVal.asInteger();
100 const APInt &Size = SizeVal.asInteger();
101
102 bool Overflow = false;
103 const APInt AllocSize = Count.umul_ov(Size, Overflow);
104 if (Overflow)
105 return AnyValue::getNullValue(Ctx, Type);
106 const unsigned AS = Type->getPointerAddressSpace();
107
108 const IntrusiveRefCntPtr<MemoryObject> Obj =
109 Ctx.allocate(AllocSize.getLimitedValue(), getMaxAlign(DL, AS), Name, AS,
110 MemInitKind::Zeroed, AllocKind);
111
112 if (!Obj)
113 return AnyValue::getNullValue(Ctx, Type);
114
115 return Ctx.deriveFromMemoryObject(Obj);
116}
117
118AnyValue Library::executeFree(ArrayRef<AnyValue> Args, unsigned AS) {
119 const auto &PtrVal = Args[0];
120
121 auto &Ptr = PtrVal.asPointer();
122 // no-op when free is called with a null pointer.
123 if (Ptr.isNullPtr(AS, DL))
124 return AnyValue();
125
126 MemoryObject *Obj = Ctx.checkProvenance(Ptr, [](const Provenance &) {
127 // TODO: check nofree
128 return true;
129 });
130 if (!Obj) {
131 Executor.reportImmediateUB()
132 << "freeing a pointer with nullary provenance.";
133 return AnyValue();
134 }
135
136 if (Ptr.address() != Obj->getAddress()) {
137 SmallString<32> AddrStr;
138 Ptr.address().toStringUnsigned(AddrStr, 16);
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"
143 << Twine::utohexstr(Obj->getAddress()) << ".";
144 return AnyValue();
145 }
146
147 if (Obj->getState() == MemoryObjectState::Freed) {
148 Executor.reportImmediateUB()
149 << "double-freeing a memory object allocated at 0x"
150 << Twine::utohexstr(Obj->getAddress()) << ".";
151 return AnyValue();
152 }
153
154 if (!Obj->isHeapAllocated()) {
155 Executor.reportImmediateUB() << "freeing a non-heap allocation at 0x"
156 << Twine::utohexstr(Obj->getAddress()) << ".";
157 return AnyValue();
158 }
159
160 // Currently we don't check for cases where a memory allocated with C
161 // allocation family (malloc, calloc, etc.) is freed with a different free
162 // function comes from a different family (C++ delete, etc.)
163
164 if (!Ctx.free(*Obj)) {
165 Executor.reportImmediateUB() << "freeing an invalid pointer at 0x"
166 << Twine::utohexstr(Obj->getAddress()) << ".";
167 return AnyValue::poison();
168 }
169
170 return AnyValue();
171}
172
173AnyValue Library::executeMemTransfer(ArrayRef<AnyValue> Args,
174 Intrinsic::ID IID) {
175 const AnyValue &Dest = Args[0];
176 Executor.executeMemTransfer(Dest, Args[1], Args[2], IID,
177 /*IsLibCall=*/true);
178 return Dest;
179}
180
181AnyValue Library::executeMemset(ArrayRef<AnyValue> Args) {
182 const AnyValue &Dest = Args[0];
183 Executor.executeMemSet(Dest, Args[1], Args[2]);
184 return Dest;
185}
186
187AnyValue Library::executePuts(ArrayRef<AnyValue> Args) {
188 const auto &PtrVal = Args[0];
189
190 const auto StrOpt = readStringFromMemory(PtrVal.asPointer());
191 if (!StrOpt)
192 return AnyValue::poison();
193
194 Handler.onPrint(*StrOpt + "\n");
195 return AnyValue(APInt(Executor.getIntSize(), 1));
196}
197
198AnyValue Library::executePrintf(ArrayRef<AnyValue> Args) {
199 const auto &FormatPtrVal = Args[0];
200
201 const auto FormatStrOpt = readStringFromMemory(FormatPtrVal.asPointer());
202 if (!FormatStrOpt)
203 return AnyValue::poison();
204
205 const std::string &FormatStr = *FormatStrOpt;
206 std::string Output;
207 raw_string_ostream OS(Output);
208 unsigned ArgIndex = 1; // Start from 1 since 0 is the format string.
209
210 for (unsigned I = 0; I < FormatStr.size();) {
211 if (FormatStr[I] != '%') {
212 OS << FormatStr[I++];
213 continue;
214 }
215
216 const size_t Start = I++;
217 if (I < FormatStr.size() && FormatStr[I] == '%') {
218 OS << '%';
219 ++I;
220 continue;
221 }
222
223 while (I < FormatStr.size() &&
224 StringRef("-= #0123456789").contains(FormatStr[I]))
225 ++I;
226
227 while (I < FormatStr.size() && StringRef("hljzt").contains(FormatStr[I]))
228 ++I;
229
230 if (I >= FormatStr.size()) {
231 Executor.reportImmediateUB()
232 << "Invalid format string in printf: missing conversion specifier.";
233 return AnyValue::poison();
234 }
235
236 char Specifier = FormatStr[I++];
237 std::string CleanChunk = FormatStr.substr(Start, I - Start - 1);
238 CleanChunk.erase(
239 llvm::remove_if(CleanChunk,
240 [](char C) { return StringRef("hljzt").contains(C); }),
241 CleanChunk.end());
242
243 if (ArgIndex >= Args.size()) {
244 Executor.reportImmediateUB() << "Not enough arguments provided for the "
245 "format string. Required argument for '"
246 << Specifier << "'.";
247 return AnyValue::poison();
248 }
249
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 << ".";
255 return AnyValue::poison();
256 }
257
258 bool TypeMismatch =
259 (StringRef("diuoxXc").contains(Specifier) &&
260 !(Arg.isInteger() && (Arg.asInteger().getBitWidth() == 32 ||
261 Arg.asInteger().getBitWidth() == 64))) ||
262 (StringRef("fFeEgGaA").contains(Specifier) &&
263 !(Arg.isFloat() &&
264 &Arg.asFloat().getSemantics() == &APFloat::IEEEdouble())) ||
265 (StringRef("nps").contains(Specifier) &&
266 !(Arg.isPointer() && Arg.asPointer().address().getBitWidth() <= 64));
267
268 if (TypeMismatch) {
269 Executor.reportImmediateUB()
270 << "Argument type mismatch in printf for format specifier '"
271 << Specifier << "' at argument index " << (ArgIndex - 1) << ".";
272 return AnyValue::poison();
273 }
274
275 switch (Specifier) {
276 case 'd':
277 case 'i': {
278 std::string HostFmt = CleanChunk + "ll" + Specifier;
279 OS << format(HostFmt.c_str(),
280 static_cast<long long>(Arg.asInteger().getSExtValue()));
281 break;
282 }
283 case 'u':
284 case 'o':
285 case 'x':
286 case 'X': {
287 // FIXME: The format specifiers "b" and "B" are not implemented here
288 // since currently MSVC doesn't support it.
289 std::string HostFmt = CleanChunk + "ll" + Specifier;
290 OS << format(HostFmt.c_str(), static_cast<unsigned long long>(
291 Arg.asInteger().getZExtValue()));
292 break;
293 }
294 case 'c': {
295 std::string HostFmt = CleanChunk + Specifier;
296 OS << format(HostFmt.c_str(),
297 static_cast<int>(Arg.asInteger().getZExtValue()));
298 break;
299 }
300 case 'f':
301 case 'F':
302 case 'e':
303 case 'E':
304 case 'g':
305 case 'G':
306 case 'a':
307 case 'A': {
308 std::string HostFmt = CleanChunk + Specifier;
309 OS << format(HostFmt.c_str(), Arg.asFloat().convertToDouble());
310 break;
311 }
312 case 'n': {
313 OS.flush();
314 Executor.store(Arg, Align(4), AnyValue(APInt(32, Output.size())),
315 Type::getInt32Ty(Ctx.getContext()));
316 break;
317 }
318 case 'p': {
319 std::string HostFmt = CleanChunk + "llx";
320 OS << "0x"
321 << format(HostFmt.c_str(),
322 static_cast<unsigned long long>(
323 Arg.asPointer().address().getZExtValue()));
324 break;
325 }
326 case 's': {
327 auto StrOpt = readStringFromMemory(Arg.asPointer());
328 if (!StrOpt)
329 return AnyValue::poison();
330 std::string HostFmt = CleanChunk + "s";
331 OS << format(HostFmt.c_str(), StrOpt->c_str());
332 break;
333 }
334 default:
335 Executor.reportImmediateUB()
336 << "Unknown or unsupported format specifier '" << Specifier
337 << "' in printf.";
338 return AnyValue::poison();
339 }
340 }
341
342 OS.flush();
343 Handler.onPrint(Output);
344 return AnyValue(APInt(Executor.getIntSize(), Output.size()));
345}
346
347AnyValue Library::executeExit(ArrayRef<AnyValue> Args) {
348 const auto &RetCodeVal = Args[0];
349
350 Executor.requestProgramExit(ProgramExitInfo::ProgramExitKind::Exited,
351 RetCodeVal.asInteger().getZExtValue());
352 return AnyValue();
353}
354
355AnyValue Library::executeAbort() {
356 Executor.requestProgramExit(ProgramExitInfo::ProgramExitKind::Aborted);
357 return AnyValue();
358}
359
360AnyValue Library::executeTerminate() {
361 Executor.requestProgramExit(ProgramExitInfo::ProgramExitKind::Terminated);
362 return AnyValue();
363}
364
365std::optional<AnyValue> Library::executeLibcall(LibFunc LF, StringRef Name,
366 FunctionType *FuncType,
367 ArrayRef<AnyValue> Args) {
368 Type *Type = FuncType->getReturnType();
369
370 unsigned Index = 0;
371 for (const AnyValue &Arg : Args) {
372 if (Arg.isPoison()) {
373 Executor.reportImmediateUB()
374 << "Poison argument passed to a library call at argument index "
375 << Index << ".";
376 return AnyValue::poison();
377 }
378 ++Index;
379 }
380
381 switch (LF) {
382 case LibFunc_malloc:
383 return executeMalloc(Name, Type, Args, MemAllocKind::Malloc);
384 case LibFunc_Znwm:
385 return executeMalloc(Name, Type, Args, MemAllocKind::New);
386 case LibFunc_Znam:
387 return executeMalloc(Name, Type, Args, MemAllocKind::NewArray);
388
389 case LibFunc_calloc:
390 return executeCalloc(Name, Type, Args, MemAllocKind::Malloc);
391
392 case LibFunc_free:
393 case LibFunc_ZdaPv:
394 case LibFunc_ZdlPv:
395 return executeFree(Args,
396 FuncType->getParamType(0)->getPointerAddressSpace());
397
398 case LibFunc_memcpy:
399 return executeMemTransfer(Args, Intrinsic::memcpy);
400
401 case LibFunc_memmove:
402 return executeMemTransfer(Args, Intrinsic::memmove);
403
404 case LibFunc_memset:
405 return executeMemset(Args);
406
407 case LibFunc_puts:
408 return executePuts(Args);
409
410 case LibFunc_printf:
411 return executePrintf(Args);
412
413 case LibFunc_exit:
414 return executeExit(Args);
415
416 case LibFunc_abort:
417 return executeAbort();
418
419 case LibFunc_terminate:
420 return executeTerminate();
421
422 default:
423 return std::nullopt;
424 }
425}
426} // namespace llvm::ubi
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
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")
#define I(x, y, z)
Definition MD5.cpp:57
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:305
Class for arbitrary precision integers.
Definition APInt.h:78
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.
Definition APInt.h:1711
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
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.
Definition StringRef.h:56
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
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!
Definition Value.h:366
static LLVM_ABI AnyValue getNullValue(Context &Ctx, Type *Ty)
Definition Value.cpp:295
The global context for the interpreter.
Definition Context.h:227
An interface for handling events and managing outputs during interpretation.
Definition Context.h:166
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.
Definition Library.cpp:365
Library(Context &Ctx, EventHandler &Handler, const DataLayout &DL, ExecutorBase &Executor)
Definition Library.cpp:27
const APInt & address() const
Definition Value.h:247
Pointer getWithNewAddr(const APInt &NewAddr) const
Definition Value.h:238
LLVM_ABI bool isNullPtr(unsigned AS, const DataLayout &DL) const
Definition Value.cpp:60
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)
Definition Library.cpp:22
@ Offset
Definition DWP.cpp:577
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1800
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
ArrayRef(const T &OneElt) -> ArrayRef< T >
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Representation of a byte in memory.
Definition Value.h:43