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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

//! This file implements the orchestration part of the stackless bytecode interpreter and also
//! provides outside-facing interfaces for the clients of stackless bytecode interpreter. Clients
//! of the interpreter should never directly interact with the statement player (in `player.rs`) nor
//! the expression evaluator (in `evaluator.rs`).

use bytecode::{function_target::FunctionTarget, function_target_pipeline::FunctionTargetsHolder};
use move_binary_format::errors::{Location, PartialVMError, PartialVMResult, VMResult};
use move_core_types::{
    language_storage::{StructTag, TypeTag},
    value::MoveValue,
    vm_status::StatusCode,
};
use move_model::{
    model::{AbilitySet, FunctionEnv, GlobalEnv, TypeParameter},
    ty as MT,
};

use crate::{
    concrete::{
        player,
        settings::InterpreterSettings,
        ty::{
            convert_model_base_type, BaseType, IntType, PrimitiveType, StructField,
            StructInstantiation,
        },
        value::{GlobalState, TypedValue},
    },
    shared::{ident::StructIdent, variant::choose_variant},
};

/// A stackless bytecode runtime in charge of pre- and post-execution checking, conversion, and
/// monitoring. The main, step-by-step interpretation loop is delegated to the `Player` instance.
pub struct Runtime<'env> {
    env: &'env GlobalEnv,
    functions: &'env FunctionTargetsHolder,
}

impl<'env> Runtime<'env> {
    //
    // public interfaces
    //

    /// Construct a runtime with all information pre-loaded.
    pub fn new(env: &'env GlobalEnv, functions: &'env FunctionTargetsHolder) -> Self {
        Self { env, functions }
    }

    /// Execute a function (identified by `fun_id`) with given type arguments, arguments, and a
    /// mutable reference of the global state. Returns the result of the execution. Any updates to
    /// the global states is recorded in the mutable reference.
    pub fn execute(
        &self,
        fun_env: &FunctionEnv,
        ty_args: &[TypeTag],
        args: &[MoveValue],
        global_state: &mut GlobalState,
    ) -> VMResult<Vec<TypedValue>> {
        let (converted_ty_args, converted_args) =
            check_and_convert_type_args_and_args(fun_env, ty_args, args)
                .map_err(|e| e.finish(Location::Undefined))?;
        let fun_target = choose_variant(self.functions, fun_env);
        self.execute_target(
            fun_target,
            &converted_ty_args,
            &converted_args,
            global_state,
        )
    }

    //
    // execution internals
    //

    fn execute_target(
        &self,
        fun_target: FunctionTarget,
        ty_args: &[BaseType],
        args: &[TypedValue],
        global_state: &mut GlobalState,
    ) -> VMResult<Vec<TypedValue>> {
        let settings = self
            .env
            .get_extension::<InterpreterSettings>()
            .unwrap_or_default();
        player::entrypoint(
            self.functions,
            fun_target,
            ty_args,
            args.to_vec(),
            settings.no_expr_check,
            /* level */ 1,
            global_state,
        )
        .map_err(|abort_info| abort_info.into_err())
    }
}

//**************************************************************************************************
// Utilities
//**************************************************************************************************

fn check_and_convert_type_args_and_args(
    fun_env: &FunctionEnv,
    ty_args: &[TypeTag],
    args: &[MoveValue],
) -> PartialVMResult<(Vec<BaseType>, Vec<TypedValue>)> {
    let env = fun_env.module_env.env;

    // check and convert type arguments
    check_type_instantiation(env, &fun_env.get_type_parameters(), ty_args)?;
    let mut converted_ty_args = vec![];
    for ty_arg in ty_args {
        let converted = convert_move_type_tag(env, ty_arg)?;
        converted_ty_args.push(converted);
    }

    // check and convert value arguments
    let params = fun_env.get_parameters();
    if params.len() != args.len() {
        return Err(PartialVMError::new(
            StatusCode::NUMBER_OF_ARGUMENTS_MISMATCH,
        ));
    }
    let mut converted_args = vec![];
    for (i, (arg, param)) in args.iter().zip(params.into_iter()).enumerate() {
        let local_ty = fun_env.get_local_type(i);
        debug_assert_eq!(local_ty, param.1);

        // NOTE: for historical reasons, we may receive `&signer` as arguments
        // TODO (mengxu): clean this up when we no longer accept `&signer` as valid arguments
        // for transaction scripts and `public(script)` functions.
        match local_ty {
            MT::Type::Reference(false, base_ty)
                if matches!(*base_ty, MT::Type::Primitive(MT::PrimitiveType::Signer)) =>
            {
                match arg {
                    MoveValue::Address(v) => {
                        converted_args.push(TypedValue::mk_signer(*v));
                    }
                    _ => {
                        return Err(PartialVMError::new(StatusCode::TYPE_MISMATCH));
                    }
                }
            }
            _ => {
                let base_ty = convert_model_base_type(env, &local_ty, &converted_ty_args);
                let converted = convert_move_value(env, arg, &base_ty)?;
                converted_args.push(converted);
            }
        }
    }

    Ok((converted_ty_args, converted_args))
}

pub fn convert_move_type_tag(env: &GlobalEnv, tag: &TypeTag) -> PartialVMResult<BaseType> {
    let converted = match tag {
        TypeTag::Bool => BaseType::mk_bool(),
        TypeTag::U8 => BaseType::mk_u8(),
        TypeTag::U64 => BaseType::mk_u64(),
        TypeTag::U128 => BaseType::mk_u128(),
        TypeTag::Address => BaseType::mk_address(),
        TypeTag::Signer => BaseType::mk_signer(),
        TypeTag::Vector(elem_tag) => BaseType::mk_vector(convert_move_type_tag(env, elem_tag)?),
        TypeTag::Struct(struct_tag) => {
            BaseType::mk_struct(convert_move_struct_tag(env, struct_tag)?)
        }
    };
    Ok(converted)
}

pub fn convert_move_struct_tag(
    env: &GlobalEnv,
    struct_tag: &StructTag,
) -> PartialVMResult<StructInstantiation> {
    // get struct env
    let struct_id = env.find_struct_by_tag(struct_tag).ok_or_else(|| {
        PartialVMError::new(StatusCode::TYPE_RESOLUTION_FAILURE).with_message(format!(
            "Cannot find struct `{}::{}::{}`",
            struct_tag.address.short_str_lossless(),
            struct_tag.module,
            struct_tag.name,
        ))
    })?;
    let struct_env = env.get_struct(struct_id);
    let ident = StructIdent::new(&struct_env);

    // check and convert type args
    check_type_instantiation(
        env,
        &struct_env.get_type_parameters(),
        &struct_tag.type_params,
    )?;
    let insts = struct_tag
        .type_params
        .iter()
        .map(|ty_arg| convert_move_type_tag(env, ty_arg))
        .collect::<PartialVMResult<Vec<_>>>()?;

    // collect fields
    let fields = struct_env
        .get_fields()
        .map(|field_env| {
            let field_name = env.symbol_pool().string(field_env.get_name()).to_string();
            let field_ty = convert_model_base_type(env, &field_env.get_type(), &insts);
            StructField {
                name: field_name,
                ty: field_ty,
            }
        })
        .collect();

    Ok(StructInstantiation {
        ident,
        insts,
        fields,
    })
}

pub fn convert_move_value(
    env: &GlobalEnv,
    val: &MoveValue,
    ty: &BaseType,
) -> PartialVMResult<TypedValue> {
    let converted = match (val, ty) {
        (MoveValue::Bool(v), BaseType::Primitive(PrimitiveType::Bool)) => TypedValue::mk_bool(*v),
        (MoveValue::U8(v), BaseType::Primitive(PrimitiveType::Int(IntType::U8))) => {
            TypedValue::mk_u8(*v)
        }
        (MoveValue::U64(v), BaseType::Primitive(PrimitiveType::Int(IntType::U64))) => {
            TypedValue::mk_u64(*v)
        }
        (MoveValue::U128(v), BaseType::Primitive(PrimitiveType::Int(IntType::U128))) => {
            TypedValue::mk_u128(*v)
        }
        (MoveValue::Address(v), BaseType::Primitive(PrimitiveType::Address)) => {
            TypedValue::mk_address(*v)
        }
        (MoveValue::Signer(v), BaseType::Primitive(PrimitiveType::Signer)) => {
            TypedValue::mk_signer(*v)
        }
        (MoveValue::Vector(v), BaseType::Vector(elem)) => {
            let converted = v
                .iter()
                .map(|e| convert_move_value(env, e, elem))
                .collect::<PartialVMResult<Vec<_>>>()?;
            TypedValue::mk_vector(*elem.clone(), converted)
        }
        (MoveValue::Struct(v), BaseType::Struct(inst)) => {
            let fields = v.fields();
            if fields.len() != inst.fields.len() {
                return Err(PartialVMError::new(StatusCode::TYPE_MISMATCH));
            }
            let converted = fields
                .iter()
                .zip(inst.fields.iter())
                .map(|(f, info)| convert_move_value(env, f, &info.ty))
                .collect::<PartialVMResult<Vec<_>>>()?;
            TypedValue::mk_struct(inst.clone(), converted)
        }
        _ => {
            return Err(PartialVMError::new(StatusCode::TYPE_MISMATCH));
        }
    };
    Ok(converted)
}

fn check_type_instantiation(
    env: &GlobalEnv,
    params: &[TypeParameter],
    args: &[TypeTag],
) -> PartialVMResult<()> {
    if params.len() != args.len() {
        return Err(PartialVMError::new(
            StatusCode::NUMBER_OF_TYPE_ARGUMENTS_MISMATCH,
        ));
    }
    for (arg, param) in args.iter().zip(params) {
        if !param.1 .0.is_subset(get_abilities(env, arg)?) {
            return Err(PartialVMError::new(StatusCode::CONSTRAINT_NOT_SATISFIED));
        }
    }
    Ok(())
}

fn get_abilities(env: &GlobalEnv, ty: &TypeTag) -> PartialVMResult<AbilitySet> {
    match ty {
        TypeTag::Bool | TypeTag::U8 | TypeTag::U64 | TypeTag::U128 | TypeTag::Address => {
            Ok(AbilitySet::PRIMITIVES)
        }
        TypeTag::Signer => Ok(AbilitySet::SIGNER),
        TypeTag::Vector(elem_ty) => AbilitySet::polymorphic_abilities(
            AbilitySet::VECTOR,
            vec![false],
            vec![get_abilities(env, elem_ty)?],
        ),
        TypeTag::Struct(struct_tag) => {
            let struct_id = env.find_struct_by_tag(struct_tag).ok_or_else(|| {
                PartialVMError::new(StatusCode::TYPE_RESOLUTION_FAILURE).with_message(format!(
                    "Cannot find struct `{}::{}::{}`",
                    struct_tag.address.short_str_lossless(),
                    struct_tag.module,
                    struct_tag.name,
                ))
            })?;
            let struct_env = env.get_struct(struct_id);
            let declared_phantom_parameters = (0..struct_env.get_type_parameters().len())
                .map(|idx| struct_env.is_phantom_parameter(idx));
            let ty_arg_abilities = struct_tag
                .type_params
                .iter()
                .map(|arg| get_abilities(env, arg))
                .collect::<PartialVMResult<Vec<_>>>()?;
            AbilitySet::polymorphic_abilities(
                struct_env.get_abilities(),
                declared_phantom_parameters,
                ty_arg_abilities,
            )
        }
    }
}