-
Notifications
You must be signed in to change notification settings - Fork 12
/
memory.ts
63 lines (49 loc) · 1.55 KB
/
memory.ts
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
import { IMachineState, IEnvironment } from "../VM";
import { Opcode } from "./common";
import { arrayCopy } from "../utils/arrays";
import { BN } from "bn.js";
/**
* Stores full word in memory.
*/
export class MStoreOpcode extends Opcode {
static id = 0x52;
static type = "MSTORE";
run(state: IMachineState): void {
const address = state.stack.pop().toNumber();
const value = state.stack.pop();
const valueEncoded = value.toArray("be", 32); // @todo this will probably overflow
const newMemory = arrayCopy(state.memory, valueEncoded, address);
state.memory = newMemory;
state.pc += 1;
}
}
/**
* Loads full word from memory.
*/
export class MLoadOpcode extends Opcode {
static id = 0x51;
static type = "MLOAD";
run(state: IMachineState): void {
const address = state.stack.pop().toNumber();
const valueRaw = state.memory.slice(address, address + 32);
const value = new BN(valueRaw, undefined, "be");
state.stack.push(value);
state.pc += 1;
}
}
/**
* Copy code running in current environment to memory
*/
export class CodeCopyOpcode extends Opcode {
static id = 0x39;
static type = "CODECOPY";
run(state: IMachineState, env: IEnvironment): void {
const memOffset = state.stack.pop().toNumber();
const codeOffset = state.stack.pop().toNumber();
const length = state.stack.pop().toNumber();
const codeToCopy = env.code.slice(codeOffset, codeOffset + length);
const newMemory = arrayCopy(state.memory, codeToCopy, memOffset);
state.memory = newMemory;
state.pc += 1;
}
}