Line data Source code
1 : #ifndef HEADER_fd_src_flamenco_vm_fd_vm_h
2 : #define HEADER_fd_src_flamenco_vm_fd_vm_h
3 :
4 : #include "fd_vm_base.h"
5 : #include "../../ballet/sha256/fd_sha256.h"
6 :
7 : /* A fd_vm_t is an opaque handle of a virtual machine that can execute
8 : sBPF programs. */
9 :
10 : struct fd_vm;
11 : typedef struct fd_vm fd_vm_t;
12 :
13 : /**********************************************************************/
14 : /* FIXME: MOVE TO FD_VM_PRIVATE WHEN CONSTRUCTORS READY */
15 :
16 : /* A fd_vm_shadow_t holds stack frame information not accessible from
17 : within a program. */
18 :
19 : struct fd_vm_shadow { ulong r6; ulong r7; ulong r8; ulong r9; ulong r10; ulong pc; };
20 : typedef struct fd_vm_shadow fd_vm_shadow_t;
21 :
22 : /* fd_vm_input_region_t holds information about fragmented memory regions
23 : within the larger input region. */
24 :
25 : struct __attribute__((aligned(8UL))) fd_vm_input_region {
26 : ulong vaddr_offset; /* Represents offset from the start of the input region. */
27 : ulong haddr; /* Host address corresponding to the start of the mem region. */
28 : uint region_sz; /* Size of the memory region. */
29 : ulong address_space_reserved; /* The amount of address space reserved for the region. */
30 : uchar is_writable; /* If the region can be written to or is read-only */
31 : ulong acc_region_meta_idx; /* Index of the acc_region_meta_t struct for the account corresponding to this region. */
32 : };
33 : typedef struct fd_vm_input_region fd_vm_input_region_t;
34 :
35 : /* fd_vm_acc_region_meta_t holds metadata about a given account. An array of these
36 : structs will map an instruction account index to its respective input memory
37 : region location. */
38 :
39 : struct __attribute((aligned(8UL))) fd_vm_acc_region_meta {
40 : uint region_idx;
41 : /* FIXME: We can get rid of this field once DM is activated. This is
42 : only a hack to make the non-DM code path happy. When DM is
43 : activated, we could query the input_mem_region array for the
44 : original data len. */
45 : ulong original_data_len;
46 : /* The transaction account corresponding to this account. */
47 : fd_acc_t * acc;
48 : /* The transaction's touched flag for this account. */
49 : uchar * touched;
50 :
51 : /* The expected virtual addresses of the serialized pubkey, lamports, owner,
52 : and data for this account in VM address space.
53 : Used for CPI security checks. */
54 : ulong vm_addr;
55 : ulong vm_key_addr;
56 : ulong vm_lamports_addr;
57 : ulong vm_owner_addr;
58 : ulong vm_data_addr;
59 : };
60 : typedef struct fd_vm_acc_region_meta fd_vm_acc_region_meta_t;
61 :
62 : /* In Agave, all the regions are 16-byte aligned in host address space. There is then an alignment check
63 : which is done inside each syscall memory translation, checking if the data is aligned in host address
64 : space. This is a layering violation, as it leaks the host address layout into the consensus model.
65 :
66 : In the future we will change this alignment check in the vm to purely operate on the virtual address space,
67 : taking advantage of the fact that Agave regions are known to be aligned. For now, we align our regions to
68 : either 8 or 16 bytes, as there are no 16-byte alignment translations in the syscalls currently:
69 : stack: 16 byte aligned
70 : heap: 16 byte aligned
71 : input: 8 byte aligned
72 : rodata: 8 byte aligned
73 :
74 : https://github.com/solana-labs/rbpf/blob/cd19a25c17ec474e6fa01a3cc3efa325f44cd111/src/ebpf.rs#L39-L40 */
75 39665 : #define FD_VM_HOST_REGION_ALIGN (16UL)
76 :
77 : struct __attribute__((aligned(FD_VM_HOST_REGION_ALIGN))) fd_vm {
78 :
79 : /* VM configuration */
80 :
81 : /* FIXME: suspect these three should be replaced by some kind of VM
82 : enabled feature struct (though syscalls do seem to make additional
83 : non-trivial use of instr_ctx). */
84 :
85 : fd_exec_instr_ctx_t * instr_ctx; /* FIXME: DOCUMENT */
86 :
87 : /* FIXME: frame_max should be run time configurable by compute budget.
88 : If there is no reasonable upper bound on this, shadow and stack
89 : will need to be provided by users. */
90 :
91 : //ulong frame_max; /* Maximum number of stack frames, in [0,FD_VM_STACK_FRAME_MAX] */
92 : ulong heap_max; /* Maximum amount of heap in bytes, in [0,FD_VM_HEAP_MAX] */
93 : ulong entry_cu; /* Initial number of compute units for this program, in [0,FD_VM_COMPUTE_UNIT_LIMIT] */
94 :
95 : /* FIXME: The below are practically an exact match to the
96 : fields of an fd_sbpf_program_t (sans ELF info) */
97 :
98 : uchar const * rodata; /* Program read only data, indexed [0,rodata_sz), aligned 8 */
99 : ulong rodata_sz; /* Program read only data size in bytes, FIXME: BOUNDS? */
100 : ulong const * text; /* Program sBPF words, indexed [0,text_cnt), aligned 8 */
101 : ulong text_cnt; /* Program sBPF word count, all text words are inside the rodata */
102 : ulong text_off; /* CALLX virtual address offset in bytes (NOT words).
103 : SBPF V0-V2: ==(ulong)text - (ulong)rodata (file offset of text within ELF).
104 : SBPF V3: ==0 (bytecode starts at vaddr 0x100000000 exactly) */
105 : ulong text_sz; /* Program sBPF size in bytes, == text_cnt*8 */
106 :
107 : ulong entry_pc; /* Initial program counter, in [0,text_cnt)
108 : FIXME: MAKE SURE NOT INTO MW INSTRUCTION, MAKE SURE VALID CALLDEST? */
109 : ulong const * calldests; /* Bit vector of local functions that can be called into, bit indexed in [0,text_cnt) */
110 : /* FIXME: ADD BIT VECTOR OF FORBIDDEN BRANCH TARGETS (E.G.
111 : INTO THE MIDDLE OF A MULTIWORD INSTRUCTION) */
112 :
113 : fd_sbpf_syscalls_t const * syscalls; /* The map of syscalls (sharable over multiple concurrently running vm) */
114 :
115 : fd_vm_trace_t * trace; /* Location to stream traces (no tracing if NULL) */
116 :
117 : /* VM execution and syscall state */
118 :
119 : /* These are used to communicate the execution and syscall state to
120 : users and syscalls. These are initialized based on the above when
121 : a program starts executing. When program halts or faults, these
122 : provide precise execution diagnostics to the user (and potential
123 : breakpoint/continue functionality in the future). When the vm
124 : makes a syscall, the vm will set these precisely and, when a
125 : syscall returns, the vm will update its internal execution state
126 : appropriately. */
127 :
128 : /* IMPORTANT SAFETY TIP! THE BEHAVIOR OF THE SYSCALL ALLOCATOR FOR
129 : HEAP_SZ MUST EXACTLY MATCH THE SOLANA VALIDATOR ALLOCATOR:
130 :
131 : https://github.com/solana-labs/solana/blob/v1.17.23/program-runtime/src/invoke_context.rs#L122-L148
132 :
133 : BIT-FOR-BIT AND BUG-FOR-BUG. SEE THE SYSCALL_ALLOC_FREE FOR MORE
134 : DETAILS. */
135 :
136 : ulong pc; /* The current instruction, in [0,text_cnt) in normal execution, may be out of bounds in a fault */
137 : ulong ic; /* The number of instructions which have been executed */
138 : ulong cu; /* The remaining CUs left for the transaction, positive in normal execution, may be zero in a fault */
139 : ulong frame_cnt; /* The current number of stack frames pushed, in [0,frame_max] */
140 :
141 : ulong heap_sz; /* Heap size in bytes, in [0,heap_max] */
142 : ulong heap_clean; /* Initialized part of the heap in bytes, in [0,heap_max] */
143 : ulong stack_clean; /* Initialized part of the stack in bytes, in [0,FD_VM_STACK_MAX] */
144 :
145 : /* VM memory */
146 :
147 : /* The vm classifies the 64-bit vm address space into 6 regions:
148 :
149 : 0 - unmapped lo
150 : 1 - program -> [FD_VM_MEM_MAP_PROGRAM_REGION_START,FD_VM_MEM_MAP_PROGRAM_REGION_START+4GiB)
151 : 2 - stack -> [FD_VM_MEM_MAP_STACK_REGION_START, FD_VM_MEM_MAP_STACK_REGION_START +4GiB)
152 : 3 - heap -> [FD_VM_MEM_MAP_HEAP_REGION_START, FD_VM_MEM_MAP_HEAP_REGION_START +4GiB)
153 : 4 - input -> [FD_VM_MEM_MAP_INPUT_REGION_START, FD_VM_MEM_MAP_INPUT_REGION_START +4GiB)
154 : 5 - unmapped hi
155 :
156 : These mappings are encoded in a software TLB consisting of three
157 : 6-element arrays: region_haddr, region_ld_sz and region_st_sz.
158 :
159 : region_haddr[i] gives the location in host address space of the
160 : first byte in region i. region_{ld,st}_sz[i] gives the number of
161 : mappable bytes in this region for {loads,stores}. Note that
162 : region_{ld,st}_sz[i]<2^32. Further note that
163 : [region_haddr[i],region_haddr[i]+region_{ld,st}_sz[i]) does not
164 : wrap around in host address space and does not overlap with any
165 : other usages.
166 :
167 : region_{ld,st}_sz[0] and region_{ld,st}_sz[5] are zero such that
168 : requests to access data from a positive sz range in these regions
169 : will fail, making regions 0 and 5 unreadable and unwritable. As
170 : such, region_haddr[0] and region_haddr[5] are arbitrary; NULL is
171 : used as the obvious default.
172 :
173 : region_st_sz[1] is also zero such that requests to store data to
174 : any positive sz range in this region will fail, making region 1
175 : unwritable.
176 :
177 : When the direct mapping feature is enabled, the input region will
178 : no longer be a contiguous buffer of host memory. Instead
179 : it will compose of several fragmented regions of memory each with
180 : its own read/write privileges and size. Address translation to the
181 : input region will now have to rely on a binary search lookup of the
182 : start of the appropriate area of physical memory. It also involves
183 : doing a check against if the region can be written to. */
184 :
185 : /* FIXME: If accessing memory beyond the end of the current heap
186 : region is not allowed, sol_alloc_free will need to update the tlb
187 : arrays during program execution (this is trivial). At the same
188 : time, given sol_alloc_free is deprecated, this is unlikely to be
189 : the case. */
190 :
191 : ulong region_haddr[6];
192 : uint region_ld_sz[6];
193 : uint region_st_sz[6];
194 :
195 : /* fd_vm_input_region_t and fd_vm_acc_to_mem arrays are passed in by the bpf
196 : loaders into fd_vm_init.
197 : TODO: It might make more sense to allocate space for these in the VM. */
198 : fd_vm_input_region_t * input_mem_regions; /* An array of input mem regions represent the input region.
199 : The virtual addresses of each region are contiguous and
200 : strictly increasing. */
201 : uint input_mem_regions_cnt;
202 : fd_vm_acc_region_meta_t * acc_region_metas; /* Represents a mapping from the instruction account indices
203 : from the instruction context to the input memory region index
204 : of the account's data region in the input space. */
205 : uchar is_deprecated; /* The vm requires additional checks in certain CPIs if the
206 : vm's current instance was initialized by a deprecated program. */
207 :
208 : ulong reg [ FD_VM_REG_MAX ]; /* registers, indexed [0,FD_VM_REG_CNT). Note that FD_VM_REG_MAX>FD_VM_REG_CNT.
209 : As such, malformed instructions, which can have src/dst reg index in
210 : [0,FD_VM_REG_MAX), cannot access info outside reg. Aligned 8. */
211 : fd_sha256_t * sha; /* Pre-joined SHA instance. This should be re-initialised before every use. */
212 :
213 : ulong magic; /* ==FD_VM_MAGIC */
214 :
215 : int direct_mapping; /* If direct mapping feature flag is enabled */
216 : int syscall_parameter_address_restrictions; /* If syscall_parameter_address_restrictions feature flag is enabled */
217 : int virtual_address_space_adjustments; /* If virtual_address_space_adjustments feature flag is enabled */
218 :
219 : ulong stack_frame_sz; /* The size of a stack frame gap, in bytes. 0 if this is variable */
220 : ulong stack_push_frame_count; /* The number of stack frames to adjust the stack by on every stack push */
221 :
222 : /* Agave uses the segv vaddr in several different cases, including:
223 : - Determining whether or not to return a regular or stack access violation
224 : - (If direct mapping is enabled) determining the instruction error
225 : code to return on store operations. */
226 : ulong segv_vaddr;
227 : ulong segv_access_len;
228 : uchar segv_access_type;
229 :
230 : ulong sbpf_version; /* SBPF version, SIMD-0161 */
231 :
232 : int dump_syscall_to_pb; /* If true, syscalls will be dumped to the specified output directory */
233 :
234 : /* fd_vm_new zero-initializes up to this point only */
235 :
236 : /* shadow stack, indexed [0,frame_cnt), if frame_cnt>0, 0/frame_cnt-1 is
237 : bottom/top. Lazily initialized. */
238 : fd_vm_shadow_t shadow[ FD_VM_STACK_FRAME_MAX ] __attribute__((aligned(16)));
239 :
240 : /* stack, indexed [0,FD_VM_STACK_MAX). Divided into FD_VM_STACK_FRAME_MAX
241 : frames. Each frame has a FD_VM_STACK_GUARD_SZ region followed by a
242 : FD_VM_STACK_FRAME_SZ region. reg[10] gives the offset of the start of the
243 : current stack frame. */
244 : uchar stack[ FD_VM_STACK_MAX ] __attribute__((aligned(FD_VM_HOST_REGION_ALIGN)));
245 :
246 : /* syscall heap, [0,heap_sz) used, [heap_sz,heap_max) free. */
247 : uchar heap[ FD_VM_HEAP_MAX ] __attribute__((aligned(FD_VM_HOST_REGION_ALIGN)));
248 : };
249 :
250 : /* FIXME: MOVE ABOVE INTO PRIVATE WHEN CONSTRUCTORS READY */
251 : /**********************************************************************/
252 :
253 : FD_PROTOTYPES_BEGIN
254 :
255 : /* FIXME: FD_VM_T NEEDS PROPER CONSTRUCTORS */
256 :
257 : /* FD_VM_{ALIGN,FOOTPRINT} describe the alignment and footprint needed
258 : for a memory region to hold a fd_vm_t. ALIGN is a positive
259 : integer power of 2. FOOTPRINT is a multiple of align.
260 : These are provided to facilitate compile time declarations. */
261 39665 : #define FD_VM_ALIGN FD_VM_HOST_REGION_ALIGN
262 7538 : #define FD_VM_FOOTPRINT (527872UL)
263 :
264 : /* fd_vm_{align,footprint} give the needed alignment and footprint
265 : of a memory region suitable to hold an fd_vm_t.
266 : Declaration / aligned_alloc / fd_alloca friendly (e.g. a memory
267 : region declared as "fd_vm_t _vm[1];", or created by
268 : "aligned_alloc(alignof(fd_vm_t),sizeof(fd_vm_t))" or created
269 : by "fd_alloca(alignof(fd_vm_t),sizeof(fd_vm_t))" will all
270 : automatically have the needed alignment and footprint).
271 : fd_vm_{align,footprint} return the same value as
272 : FD_VM_{ALIGN,FOOTPRINT}. */
273 : FD_FN_CONST ulong
274 : fd_vm_align( void );
275 :
276 : FD_FN_CONST ulong
277 : fd_vm_footprint( void );
278 :
279 16079 : #define FD_VM_MAGIC (0xF17EDA2CEF0) /* FIREDANCE SBPF V0 */
280 :
281 : /* fd_vm_new formats memory region with suitable alignment and
282 : footprint suitable for holding a fd_vm_t. Assumes
283 : shmem points on the caller to the first byte of the memory region
284 : owned by the caller to use. Returns shmem on success and NULL on
285 : failure (logs details). The memory region will be owned by the state
286 : on successful return. The caller is not joined on return. */
287 :
288 : void *
289 : fd_vm_new( void * shmem );
290 :
291 : /* fd_vm_join joins the caller to a vm.
292 : Assumes shmem points to the first byte of the memory region holding
293 : the vm. Returns a local handle to the join on success (this is
294 : not necessarily a simple cast of the address) and NULL on failure
295 : (logs details). */
296 : fd_vm_t *
297 : fd_vm_join( void * shmem );
298 :
299 : /* fd_vm_init initializes the given fd_vm_t struct, checking that it is
300 : not null and has the correct magic value.
301 :
302 : It modifies the vm object and also returns the object for convenience.
303 :
304 : FIXME: we should split out the memory mapping setup from this function
305 : to handle those errors separately. */
306 : fd_vm_t *
307 : fd_vm_init(
308 : fd_vm_t * vm,
309 : fd_exec_instr_ctx_t * instr_ctx,
310 : ulong heap_max,
311 : ulong entry_cu,
312 : uchar const * rodata,
313 : ulong rodata_sz,
314 : ulong const * text,
315 : ulong text_cnt,
316 : ulong text_off,
317 : ulong text_sz,
318 : ulong entry_pc,
319 : ulong const * calldests,
320 : ulong sbpf_version,
321 : fd_sbpf_syscalls_t * syscalls,
322 : fd_vm_trace_t * trace,
323 : fd_sha256_t * sha,
324 : fd_vm_input_region_t * mem_regions,
325 : uint mem_regions_cnt,
326 : fd_vm_acc_region_meta_t * acc_region_metas,
327 : uchar is_deprecated,
328 : int direct_mapping,
329 : int syscall_parameter_address_restrictions,
330 : int virtual_address_space_adjustments,
331 : int dump_syscall_to_pb,
332 : ulong r2_initial_value );
333 :
334 : /* fd_vm_leave leaves the caller's current local join to a vm.
335 : Returns a pointer to the memory region holding the vm on success
336 : (this is not necessarily a simple cast of the
337 : address) and NULL on failure (logs details). The caller is not
338 : joined on successful return. */
339 : void *
340 : fd_vm_leave( fd_vm_t * vm );
341 :
342 : /* fd_vm_delete unformats a memory region that holds a vm.
343 : Assumes shmem points on the caller to the first
344 : byte of the memory region holding the state and that nobody is
345 : joined. Returns a pointer to the memory region on success and NULL
346 : on failure (logs details). The caller has ownership of the memory
347 : region on successful return. */
348 : void *
349 : fd_vm_delete( void * shmem );
350 :
351 : /* fd_vm_validate validates the sBPF program in the given vm. Returns
352 : success or an error code. Called before executing a sBPF program.
353 : FIXME: DOCUMENT BETTER */
354 :
355 : FD_FN_PURE int
356 : fd_vm_validate( fd_vm_t const * vm );
357 :
358 : /* fd_vm_is_check_align_enabled returns 1 if the vm should check alignment
359 : when doing memory translation. */
360 : FD_FN_PURE static inline int
361 66920 : fd_vm_is_check_align_enabled( fd_vm_t const * vm ) {
362 66920 : return !vm->is_deprecated;
363 66920 : }
364 :
365 : /* fd_vm_is_check_size_enabled returns 1 if the vm should check size
366 : when doing memory translation. */
367 : FD_FN_PURE static inline int
368 0 : fd_vm_is_check_size_enabled( fd_vm_t const * vm ) {
369 0 : return !vm->is_deprecated;
370 0 : }
371 :
372 : /* fd_vm_exec runs vm from program start to program halt or program
373 : fault, appending an execution trace if vm is attached to a trace.
374 : vm must be initialized with fd_vm_init before each call.
375 :
376 : Returns FD_VM_SUCCESS (0) on success and an FD_VM_ERR code (negative)
377 : on failure. Reasons for failure include:
378 :
379 : INVAL - NULL vm (or, for fd_vm_exec_trace, the vm is not
380 : attached to trace). FIXME: ADD OTHER INPUT ARG CHECKS?
381 :
382 : SIGTEXT - A jump/call set the program counter outside the text
383 : region or the program counter incremented beyond the
384 : text region. pc will be at the out of bounds location.
385 : ic and cu will not include the out of bounds location.
386 : For a call, the call stack frame was allocated.
387 :
388 : SIGSPLIT - A jump/call set the program counter into the middle of
389 : a multiword instruction or a multiword instruction went
390 : past the text region end. pc will be at the split. ic
391 : and cu will not include the split. For a call, the
392 : call stack frame was allocated.
393 :
394 : SIGCALL - A call set the program counter to a non-function
395 : location. pc will be at the non-function location. ic
396 : and cu will include the call but not include the
397 : non-function location. The call stack frame was
398 : allocated.
399 :
400 : SIGSTACK - The call depth limit was exceeded. pc will be at the
401 : call. ic and cu will include the call but not the call
402 : target. The call stack frame was not allocated.
403 :
404 : SIGILL - An invalid instruction was encountered (including an
405 : invalid opcode and an endian swap with an invalid bit
406 : width). pc will be at the invalid instruction. ic and
407 : cu will not include the invalid instruction.
408 :
409 : SIGSEGV - An invalid memory access (outside the program memory
410 : map) was encountered. pc will be at the faulting
411 : instruction. ic and cu will not include the faulting
412 : instruction.
413 :
414 : SIGBUS - An unaligned memory access was encountered. pc will be
415 : at the faulting instruction. ic and cu will not
416 : include the faulting instruction. (Note: currently
417 : mapped to SIGSEGV and then only if check_align is
418 : enabled.)
419 :
420 : SIGRDONLY - A write to read-only memory address was encountered.
421 : pc will be at the faulting instruction. ic and cu will
422 : not include the faulting instruction. (Note: currently
423 : mapped to SIGSEGV.)
424 :
425 : SIGCOST - The compute limit was exceeded. pc will be at the
426 : first non-executed instruction (if pc is a syscall, the
427 : syscall might have been partially executed when it ran
428 : out of budget .. see safety tip below). ic will cover
429 : all executed instructions. cu will be zero.
430 :
431 : This will considers any error returned by a syscall as a fault and
432 : returns the syscall error code here. See syscall documentation for
433 : details here. When a syscall faults, pc will be at the syscall, ic
434 : will include the syscall and cu will include the syscall and any
435 : additional costs the syscall might have incurred up to that point of
436 : the fault.
437 :
438 : IMPORTANT SAFETY TIP! Ideally, a syscall should only modify vm's
439 : state when it knows its overall syscall will be successful.
440 : Unfortunately, this is often not practical (e.g. a syscall starts
441 : processing a list of user provided commands and discovers an error
442 : condition late in the command list that did not exist at syscall
443 : start because the error condition was created by successfully
444 : executed commands earlier in the list). As such, vm's state on a
445 : faulting syscall may not be clean.
446 :
447 : FIXME: SINCE MOST SYSCALLS CAN BE IMPLEMENTED TO HAVE CLEAN FAULTING
448 : BEHAVIOR, PROVIDE A MECHANISM SO USERS CAN EASILY DETECT UNCLEAN
449 : SYSCALL FAULTS?
450 :
451 : For SIGCOST, note that the vm can speculate ahead when processing
452 : instructions. This makes it is possible to have a situation where
453 : a vm faults with, for example, SIGSEGV from a speculatively
454 : executed memory access while a non-speculative execution would have
455 : faulted with SIGCOST on an earlier instruction. In these situations,
456 : pc will be at the faulting speculatively executed instruction, ic
457 : will include all the speculatively executed instructions, cu will be
458 : zero and vm's state will include the impact of all the speculation.
459 :
460 : IMPORTANT SAFETY TIP! While different vm implementations can
461 : disagree on why a program faulted (e.g. SIGCOST versus SIGSEGV in the
462 : example above), they cannot disagree on whether or not a program
463 : faulted. As a result, the specific fault reason must never be
464 : allowed to be part of consensus.
465 :
466 : fd_vm_exec_trace runs with tracing and requires vm to be attached to
467 : a trace. fd_vm_exec_notrace runs without without tracing even if vm
468 : is attached to a trace. */
469 :
470 : int
471 : fd_vm_exec_trace( fd_vm_t * vm );
472 :
473 : int
474 : fd_vm_exec_notrace( fd_vm_t * vm );
475 :
476 : static inline int
477 4223 : fd_vm_exec( fd_vm_t * vm ) {
478 4223 : if( FD_UNLIKELY( vm->trace ) ) return fd_vm_exec_trace ( vm );
479 4223 : else return fd_vm_exec_notrace( vm );
480 4223 : }
481 :
482 : FD_PROTOTYPES_END
483 :
484 : #endif /* HEADER_fd_src_flamenco_vm_fd_vm_h */
|