Created
June 27, 2017 20:45
-
-
Save strazzere/69a57c2c71a54ab8d510b67b68dcc7a3 to your computer and use it in GitHub Desktop.
safer unsafe otto run
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"os" | |
"time" | |
"github.com/robertkrimen/otto" | |
) | |
var halt = errors.New("Stahp") | |
func main() { | |
runUnsafe("(0)(eval&^=(eval))") | |
} | |
func runUnsafe(unsafe string) { | |
defer func() { | |
if caught := recover(); caught != nil { | |
fmt.Println("Recovered inside runUnsafe : ", caught) | |
} | |
}() | |
runUnsafeVM(unsafe) | |
} | |
func runUnsafeVM(unsafe string) { | |
start := time.Now() | |
defer func() { | |
duration := time.Since(start) | |
if caught := recover(); caught != nil { | |
if caught == halt { | |
fmt.Fprintf(os.Stderr, "Some code took to long! Stopping after: %v\n", duration) | |
return | |
} | |
panic(caught) // Something else happened, repanic! | |
} | |
fmt.Fprintf(os.Stderr, "Ran code successfully: %v\n", duration) | |
}() | |
vm := otto.New() | |
vm.Interrupt = make(chan func(), 1) // The buffer prevents blocking | |
go func() { | |
time.Sleep(2 * time.Second) // Stop after two seconds | |
vm.Interrupt <- func() { | |
panic(halt) | |
} | |
}() | |
vm.Run(unsafe) // Here be dragons (risky code) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment