1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
#[allow(unused_imports)]
use crate::error::bail;
use crate::error::Error;
use crate::gas::CostModelRef;
use alloc::sync::Arc;
use polkavm_assembler::Assembler;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum BackendKind {
Compiler,
Interpreter,
}
impl core::fmt::Display for BackendKind {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
let name = match self {
BackendKind::Compiler => "compiler",
BackendKind::Interpreter => "interpreter",
};
fmt.write_str(name)
}
}
impl BackendKind {
#[cfg(feature = "std")]
fn from_os_str(s: &std::ffi::OsStr) -> Result<Option<BackendKind>, Error> {
if s == "auto" {
Ok(None)
} else if s == "interpreter" {
Ok(Some(BackendKind::Interpreter))
} else if s == "compiler" {
Ok(Some(BackendKind::Compiler))
} else {
Err(Error::from_static_str(
"invalid value of POLKAVM_BACKEND; supported values are: 'interpreter', 'compiler'",
))
}
}
}
impl BackendKind {
pub fn is_supported(self) -> bool {
match self {
BackendKind::Interpreter => true,
BackendKind::Compiler => if_compiler_is_supported! {
{ true } else { false }
},
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum SandboxKind {
Linux,
Generic,
}
impl core::fmt::Display for SandboxKind {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
let name = match self {
SandboxKind::Linux => "linux",
SandboxKind::Generic => "generic",
};
fmt.write_str(name)
}
}
impl SandboxKind {
#[cfg(feature = "std")]
fn from_os_str(s: &std::ffi::OsStr) -> Result<Option<SandboxKind>, Error> {
if s == "auto" {
Ok(None)
} else if s == "linux" {
Ok(Some(SandboxKind::Linux))
} else if s == "generic" {
Ok(Some(SandboxKind::Generic))
} else {
Err(Error::from_static_str(
"invalid value of POLKAVM_SANDBOX; supported values are: 'linux', 'generic'",
))
}
}
}
impl SandboxKind {
pub fn is_supported(self) -> bool {
if_compiler_is_supported! {
{
match self {
SandboxKind::Linux => cfg!(target_os = "linux"),
SandboxKind::Generic => cfg!(feature = "generic-sandbox"),
}
} else {
false
}
}
}
}
#[derive(Clone)]
pub struct Config {
pub(crate) backend: Option<BackendKind>,
pub(crate) sandbox: Option<SandboxKind>,
pub(crate) crosscheck: bool,
pub(crate) allow_experimental: bool,
pub(crate) allow_dynamic_paging: bool,
pub(crate) worker_count: usize,
pub(crate) cache_enabled: bool,
pub(crate) lru_cache_size: u32,
pub(crate) sandboxing_enabled: bool,
pub(crate) default_cost_model: Option<CostModelRef>,
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "std")]
fn env_bool(name: &str) -> Result<Option<bool>, Error> {
if let Some(value) = std::env::var_os(name) {
if value == "1" || value == "true" {
Ok(Some(true))
} else if value == "0" || value == "false" {
Ok(Some(false))
} else {
bail!("invalid value of {name}; must be either '1' or '0'")
}
} else {
Ok(None)
}
}
#[cfg(feature = "std")]
fn env_usize(name: &str) -> Result<Option<usize>, Error> {
if let Some(value) = std::env::var_os(name) {
if let Ok(value) = value.into_string() {
if let Ok(value) = value.parse() {
Ok(Some(value))
} else {
bail!("invalid value of {name}; must be a positive integer")
}
} else {
bail!("invalid value of {name}; must be a positive integer")
}
} else {
Ok(None)
}
}
impl Config {
/// Creates a new default configuration.
pub fn new() -> Self {
Config {
backend: None,
sandbox: None,
crosscheck: false,
allow_experimental: false,
allow_dynamic_paging: false,
worker_count: 2,
cache_enabled: cfg!(feature = "module-cache"),
lru_cache_size: 0,
sandboxing_enabled: true,
default_cost_model: None,
}
}
/// Creates a new default configuration and seeds it from the environment variables.
pub fn from_env() -> Result<Self, Error> {
#[allow(unused_mut)]
let mut config = Self::new();
#[cfg(feature = "std")]
{
if let Some(value) = std::env::var_os("POLKAVM_BACKEND") {
config.backend = BackendKind::from_os_str(&value)?;
}
if let Some(value) = std::env::var_os("POLKAVM_SANDBOX") {
config.sandbox = SandboxKind::from_os_str(&value)?;
}
if let Some(value) = env_bool("POLKAVM_CROSSCHECK")? {
config.crosscheck = value;
}
if let Some(value) = env_bool("POLKAVM_ALLOW_EXPERIMENTAL")? {
config.allow_experimental = value;
}
if let Some(value) = env_usize("POLKAVM_WORKER_COUNT")? {
config.worker_count = value;
}
if let Some(value) = env_bool("POLKAVM_CACHE_ENABLED")? {
config.cache_enabled = value;
}
if let Some(value) = env_usize("POLKAVM_LRU_CACHE_SIZE")? {
config.lru_cache_size = if value > u32::MAX as usize { u32::MAX } else { value as u32 };
}
if let Some(value) = env_bool("POLKAVM_SANDBOXING_ENABLED")? {
config.sandboxing_enabled = value;
}
use crate::gas::CostModel;
if let Some(value) = std::env::var_os("POLKAVM_DEFAULT_COST_MODEL") {
if value == "naive" {
config.default_cost_model = Some(CostModel::naive_ref());
} else {
let blob = match std::fs::read(&value) {
Ok(blob) => blob,
Err(error) => {
bail!("failed to read gas cost model from {:?}: {}", value, error);
}
};
let Some(cost_model) = CostModel::deserialize(&blob) else {
bail!("failed to read gas cost model from {:?}: the cost model blob is invalid", value);
};
config.default_cost_model = Some(CostModelRef::from(Arc::new(cost_model)));
}
}
}
Ok(config)
}
/// Forces the use of a given backend.
///
/// Default: `None` (automatically pick the best available backend)
///
/// Corresponding environment variable: `POLKAVM_BACKEND` (`auto`, `compiler`, `interpreter`)
pub fn set_backend(&mut self, backend: Option<BackendKind>) -> &mut Self {
self.backend = backend;
self
}
/// Gets the currently set backend, if any.
pub fn backend(&self) -> Option<BackendKind> {
self.backend
}
/// Forces the use of a given sandbox.
///
/// Default: `None` (automatically pick the best available sandbox)
///
/// Corresponding environment variable: `POLKAVM_SANDBOX` (`auto`, `linux`, `generic`)
pub fn set_sandbox(&mut self, sandbox: Option<SandboxKind>) -> &mut Self {
self.sandbox = sandbox;
self
}
/// Gets the currently set sandbox, if any.
pub fn sandbox(&self) -> Option<SandboxKind> {
self.sandbox
}
/// Enables execution cross-checking.
///
/// This will run an interpreter alongside the recompiler and cross-check their execution.
///
/// Should only be used for debugging purposes and *never* enabled by default in production.
///
/// Default: `false`
///
/// Corresponding environment variable: `POLKAVM_CROSSCHECK` (`false`, `true`)
pub fn set_crosscheck(&mut self, value: bool) -> &mut Self {
self.crosscheck = value;
self
}
/// Returns whether cross-checking is enabled.
pub fn crosscheck(&self) -> bool {
self.crosscheck
}
/// Enabling this makes it possible to enable other experimental settings
/// which are not meant for general use and can introduce unsafety,
/// break determinism, or just simply be totally broken.
///
/// This should NEVER be used in production unless you know what you're doing.
///
/// Default: `false`
///
/// Corresponding environment variable: `POLKAVM_ALLOW_EXPERIMENTAL` (`true`, `false`)
pub fn set_allow_experimental(&mut self, value: bool) -> &mut Self {
self.allow_experimental = value;
self
}
/// Sets the number of worker sandboxes that will be permanently kept alive by the engine.
///
/// This doesn't limit the number of instances that can be instantiated at the same time;
/// it will just tell the engine how many sandboxes should be cached between instantiations.
///
/// For the Linux sandbox this will decide how many worker processes are kept alive.
///
/// This only has an effect when using a recompiler. For the interpreter this setting will be ignored.
///
/// Default: `2`
///
/// Corresponding environment variable: `POLKAVM_WORKER_COUNT`
pub fn set_worker_count(&mut self, value: usize) -> &mut Self {
self.worker_count = value;
self
}
/// Returns the number of worker sandboxes that will be permanently kept alive by the engine.
pub fn worker_count(&self) -> usize {
self.worker_count
}
/// Returns whether dynamic paging is allowed.
pub fn allow_dynamic_paging(&self) -> bool {
self.allow_dynamic_paging
}
/// Sets whether dynamic paging is allowed.
///
/// Enabling this increases the minimum system requirements of the recompiler backend:
/// - At least Linux 6.7 is required.
/// - Unpriviledged `userfaultfd` must be enabled (`/proc/sys/vm/unprivileged_userfaultfd` must be set to `1`).
///
/// Default: `false`
pub fn set_allow_dynamic_paging(&mut self, value: bool) -> &mut Self {
self.allow_dynamic_paging = value;
self
}
/// Returns whether module caching is enabled.
pub fn cache_enabled(&self) -> bool {
self.cache_enabled
}
/// Sets whether module caching is enabled.
///
/// When set to `true` calling [`Module::new`](crate::Module::new) or [`Module::from_blob`](crate::Module::from_blob)
/// will return an already compiled module if such already exists.
///
/// Requires the `module-cache` compile time feature to be enabled, otherwise has no effect.
///
/// Default: `true` if compiled with `module-cache`, `false` otherwise
///
/// Corresponding environment variable: `POLKAVM_CACHE_ENABLED`
pub fn set_cache_enabled(&mut self, value: bool) -> &mut Self {
self.cache_enabled = value;
self
}
/// Returns the LRU cache size.
pub fn lru_cache_size(&self) -> u32 {
self.lru_cache_size
}
/// Sets the LRU cache size.
///
/// Requires the `module-cache` compile time feature and caching to be enabled, otherwise has no effect.
///
/// When the size of the LRU cache is non-zero then modules that are dropped will be added to the LRU cache,
/// and will be reused if a compilation of the same program is triggered.
///
/// Default: `0`
///
/// Corresponding environment variable: `POLKAVM_LRU_CACHE_SIZE`
pub fn set_lru_cache_size(&mut self, value: u32) -> &mut Self {
self.lru_cache_size = value;
self
}
/// Sets whether security sandboxing is enabled.
///
/// Should only be used for debugging purposes and *never* disabled in production.
///
/// Default: `true`
///
/// Corresponding environment variable: `POLKAVM_SANDBOXING_ENABLED`
pub fn set_sandboxing_enabled(&mut self, value: bool) -> &mut Self {
self.sandboxing_enabled = value;
self
}
/// Returns whether security sandboxing is enabled.
pub fn sandboxing_enabled(&self) -> bool {
self.sandboxing_enabled
}
/// Sets the default cost model.
///
/// Default: `None`
///
/// Corresponding environment variable: `POLKAVM_DEFAULT_COST_MODEL`
pub fn set_default_cost_model(&mut self, cost_model: Option<CostModelRef>) -> &mut Self {
self.default_cost_model = cost_model;
self
}
/// Returns the default cost model.
pub fn default_cost_model(&self) -> Option<CostModelRef> {
self.default_cost_model.clone()
}
}
/// The type of gas metering.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum GasMeteringKind {
/// Synchronous gas metering. This will immediately abort the execution if we run out of gas.
Sync,
/// Asynchronous gas metering. Has a lower performance overhead compared to synchronous gas metering,
/// but will only periodically and asynchronously check whether we still have gas remaining while
/// the program is running.
///
/// With asynchronous gas metering the program can run slightly longer than it would otherwise,
/// and the exact point *when* it is interrupted is not deterministic, but whether the computation
/// as a whole finishes under a given gas limit will still be strictly enforced and deterministic.
///
/// This is only a hint, and the VM might still fall back to using synchronous gas metering
/// if asynchronous metering is not available.
Async,
}
pub trait CustomCodegen: Send + Sync + 'static {
fn should_emit_ecalli(&self, number: u32, asm: &mut Assembler) -> bool;
}
/// The configuration for a module.
#[derive(Clone)]
pub struct ModuleConfig {
pub(crate) page_size: u32,
pub(crate) gas_metering: Option<GasMeteringKind>,
pub(crate) is_strict: bool,
pub(crate) step_tracing: bool,
pub(crate) dynamic_paging: bool,
pub(crate) aux_data_size: u32,
pub(crate) allow_sbrk: bool,
cache_by_hash: bool,
pub(crate) custom_codegen: Option<Arc<dyn CustomCodegen>>,
pub(crate) cost_model: Option<CostModelRef>,
pub(crate) is_per_instruction_metering: bool,
}
impl Default for ModuleConfig {
fn default() -> Self {
Self::new()
}
}
impl ModuleConfig {
/// Creates a new default module configuration.
pub fn new() -> Self {
ModuleConfig {
page_size: 0x1000,
gas_metering: None,
is_strict: false,
step_tracing: false,
dynamic_paging: false,
aux_data_size: 0,
allow_sbrk: true,
cache_by_hash: false,
custom_codegen: None,
cost_model: None,
is_per_instruction_metering: false,
}
}
/// Sets the page size used for the module.
///
/// Default: `4096` (4k)
pub fn set_page_size(&mut self, page_size: u32) -> &mut Self {
self.page_size = page_size;
self
}
/// Returns the size of the auxiliary data region.
pub fn aux_data_size(&self) -> u32 {
self.aux_data_size
}
/// Sets the size of the auxiliary data region.
///
/// Default: `0`
pub fn set_aux_data_size(&mut self, aux_data_size: u32) -> &mut Self {
self.aux_data_size = aux_data_size;
self
}
/// Sets the type of gas metering to enable for this module.
///
/// Default: `None`
pub fn set_gas_metering(&mut self, kind: Option<GasMeteringKind>) -> &mut Self {
self.gas_metering = kind;
self
}
/// Returns whether dynamic paging is enabled.
pub fn dynamic_paging(&self) -> bool {
self.dynamic_paging
}
/// Sets whether dynamic paging is enabled.
///
/// [`Config::allow_dynamic_paging`] also needs to be `true` for dynamic paging to be enabled.
///
/// Default: `false`
pub fn set_dynamic_paging(&mut self, value: bool) -> &mut Self {
self.dynamic_paging = value;
self
}
/// Sets whether step tracing is enabled.
///
/// When enabled [`InterruptKind::Step`](crate::InterruptKind::Step) will be returned by [`RawInstance::run`](crate::RawInstance::run)
/// for each executed instruction.
///
/// Should only be used for debugging.
///
/// Default: `false`
pub fn set_step_tracing(&mut self, enabled: bool) -> &mut Self {
self.step_tracing = enabled;
self
}
/// Sets the strict mode. When disabled it's guaranteed that the semantics
/// of lazy execution match the semantics of eager execution.
///
/// Should only be used for debugging.
///
/// Default: `false`
pub fn set_strict(&mut self, is_strict: bool) -> &mut Self {
self.is_strict = is_strict;
self
}
///
/// Sets whether sbrk instruction is allowed.
///
/// When enabled sbrk instruction is not allowed it will lead to a trap, otherwise
/// sbrk instruction is emulated.
///
/// Default: `true`
pub fn set_allow_sbrk(&mut self, enabled: bool) -> &mut Self {
self.allow_sbrk = enabled;
self
}
/// Returns whether the module will be cached by hash.
pub fn cache_by_hash(&self) -> bool {
self.cache_by_hash
}
/// Sets whether the module will be cached by hash.
///
/// This introduces extra overhead as every time a module compilation is triggered the hash
/// of the program must be calculated, and in general it is faster to recompile a module
/// from scratch rather than compile its hash.
///
/// Default: `true`
pub fn set_cache_by_hash(&mut self, enabled: bool) -> &mut Self {
self.cache_by_hash = enabled;
self
}
/// Sets a custom codegen handler.
pub fn set_custom_codegen(&mut self, custom_codegen: impl CustomCodegen) -> &mut Self {
self.custom_codegen = Some(Arc::new(custom_codegen));
self
}
/// Gets the currently set gas cost model.
pub fn cost_model(&self) -> Option<&CostModelRef> {
self.cost_model.as_ref()
}
/// Sets a custom gas cost model.
pub fn set_cost_model(&mut self, cost_model: Option<CostModelRef>) -> &mut Self {
self.cost_model = cost_model;
self
}
/// Returns whether per-instruction gas metering is enabled.
pub fn per_instruction_metering(&self) -> bool {
self.is_per_instruction_metering
}
/// Sets whether per-instruction gas metering is enabled.
///
/// This can only be used with the interpreter and with the default gas cost model.
/// This option is DEPRECATED and will be removed in the future!
///
/// Default: `false`
pub fn set_per_instruction_metering(&mut self, value: bool) -> &mut Self {
self.is_per_instruction_metering = value;
self
}
#[cfg(feature = "module-cache")]
pub(crate) fn hash(&self, cost_model: &CostModelRef) -> Option<polkavm_common::hasher::Hash> {
if self.custom_codegen.is_some() {
return None;
}
let &ModuleConfig {
page_size,
aux_data_size,
gas_metering,
is_strict,
step_tracing,
dynamic_paging,
allow_sbrk,
is_per_instruction_metering,
// Deliberately ignored.
cost_model: _,
cache_by_hash: _,
custom_codegen: _,
} = self;
let mut hasher = polkavm_common::hasher::Hasher::new();
hasher.update_u32_array([
page_size,
aux_data_size,
match gas_metering {
None => 0,
Some(GasMeteringKind::Sync) => 1,
Some(GasMeteringKind::Async) => 2,
},
u32::from(is_strict),
u32::from(step_tracing),
u32::from(dynamic_paging),
u32::from(allow_sbrk),
u32::from(is_per_instruction_metering),
]);
use core::hash::Hash;
cost_model.hash(&mut hasher);
Some(hasher.finalize())
}
}