Skip to content

Commit

Permalink
Merge d52ae56 into 6bb5ffd
Browse files Browse the repository at this point in the history
  • Loading branch information
rohanchandra committed Dec 19, 2019
2 parents 6bb5ffd + d52ae56 commit edb0b45
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/index.ts
Expand Up @@ -10,19 +10,23 @@ import { hoist } from './compile/helper'

export interface SvalOptions {
ecmaVer?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 2015 | 2016 | 2017 | 2018 | 2019
sandBox?: boolean
sandBox?: boolean,
stepLimit?: number
}

class Sval {
static version: string = version

private options: Options = {}
private state = new State()
private stepLimit: number | null

exports: { [name: string]: any } = {}

constructor(options: SvalOptions = {}) {
let { ecmaVer = 9, sandBox = true } = options
let { ecmaVer = 9, sandBox = true, stepLimit = null } = options

this.stepLimit = stepLimit;

ecmaVer -= ecmaVer < 2015 ? 0 : 2009 // format ecma edition

Expand Down Expand Up @@ -74,7 +78,7 @@ class Sval {
// const opCode = this.state.opCodes[i]
// console.log(i, (OP as any)[opCode.op], typeof opCode.val === 'undefined' ? '' : opCode.val)
// }
execute(this.state)
execute(this.state, this.stepLimit)
}
}

Expand Down
16 changes: 15 additions & 1 deletion src/jsvm/index.ts
Expand Up @@ -522,6 +522,20 @@ function step(state: State) {
return signal
}

export default function execute(state: State) {
export default function execute(state: State, stepLimit: number | null) {
if (stepLimit === null) {
while (state.pc < state.opCodes.length) step(state)
} else {
// Restrict number of steps.
let stepCounter: number = 0

while (state.pc < state.opCodes.length && stepCounter < stepLimit) {
step(state)
stepCounter++
}

if (stepCounter >= stepLimit) {
throw new Error('Execution limit exceeded')
}
}
}
12 changes: 12 additions & 0 deletions tests/bootstrap.test1.ts
Expand Up @@ -22,6 +22,18 @@ describe('testing src/index.ts', () => {
interpreter.run(`!async function(){${code}}()`)
})

it('should support execution limit', () => {
const interpreter = new Sval({
stepLimit: 100
})

try {
interpreter.run(`while(true){}`);
} catch (ex) {
expect(ex.message).toBe('Execution limit exceeded')
}
})

it('should support global mode', () => {
const interpreter = new Sval({
sandBox: false
Expand Down

0 comments on commit edb0b45

Please sign in to comment.