jsre.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package jsre provides execution environment for JavaScript.
  17. package jsre
  18. import (
  19. crand "crypto/rand"
  20. "encoding/binary"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "math/rand"
  25. "time"
  26. "github.com/dop251/goja"
  27. "github.com/ethereum/go-ethereum/common"
  28. )
  29. // JSRE is a JS runtime environment embedding the goja interpreter.
  30. // It provides helper functions to load code from files, run code snippets
  31. // and bind native go objects to JS.
  32. //
  33. // The runtime runs all code on a dedicated event loop and does not expose the underlying
  34. // goja runtime directly. To use the runtime, call JSRE.Do. When binding a Go function,
  35. // use the Call type to gain access to the runtime.
  36. type JSRE struct {
  37. assetPath string
  38. output io.Writer
  39. evalQueue chan *evalReq
  40. stopEventLoop chan bool
  41. closed chan struct{}
  42. vm *goja.Runtime
  43. }
  44. // Call is the argument type of Go functions which are callable from JS.
  45. type Call struct {
  46. goja.FunctionCall
  47. VM *goja.Runtime
  48. }
  49. // jsTimer is a single timer instance with a callback function
  50. type jsTimer struct {
  51. timer *time.Timer
  52. duration time.Duration
  53. interval bool
  54. call goja.FunctionCall
  55. }
  56. // evalReq is a serialized vm execution request processed by runEventLoop.
  57. type evalReq struct {
  58. fn func(vm *goja.Runtime)
  59. done chan bool
  60. }
  61. // runtime must be stopped with Stop() after use and cannot be used after stopping
  62. func New(assetPath string, output io.Writer) *JSRE {
  63. re := &JSRE{
  64. assetPath: assetPath,
  65. output: output,
  66. closed: make(chan struct{}),
  67. evalQueue: make(chan *evalReq),
  68. stopEventLoop: make(chan bool),
  69. vm: goja.New(),
  70. }
  71. go re.runEventLoop()
  72. re.Set("loadScript", MakeCallback(re.vm, re.loadScript))
  73. re.Set("inspect", re.prettyPrintJS)
  74. return re
  75. }
  76. // randomSource returns a pseudo random value generator.
  77. func randomSource() *rand.Rand {
  78. bytes := make([]byte, 8)
  79. seed := time.Now().UnixNano()
  80. if _, err := crand.Read(bytes); err == nil {
  81. seed = int64(binary.LittleEndian.Uint64(bytes))
  82. }
  83. src := rand.NewSource(seed)
  84. return rand.New(src)
  85. }
  86. // This function runs the main event loop from a goroutine that is started
  87. // when JSRE is created. Use Stop() before exiting to properly stop it.
  88. // The event loop processes vm access requests from the evalQueue in a
  89. // serialized way and calls timer callback functions at the appropriate time.
  90. // Exported functions always access the vm through the event queue. You can
  91. // call the functions of the goja vm directly to circumvent the queue. These
  92. // functions should be used if and only if running a routine that was already
  93. // called from JS through an RPC call.
  94. func (re *JSRE) runEventLoop() {
  95. defer close(re.closed)
  96. r := randomSource()
  97. re.vm.SetRandSource(r.Float64)
  98. registry := map[*jsTimer]*jsTimer{}
  99. ready := make(chan *jsTimer)
  100. newTimer := func(call goja.FunctionCall, interval bool) (*jsTimer, goja.Value) {
  101. delay := call.Argument(1).ToInteger()
  102. if 0 >= delay {
  103. delay = 1
  104. }
  105. timer := &jsTimer{
  106. duration: time.Duration(delay) * time.Millisecond,
  107. call: call,
  108. interval: interval,
  109. }
  110. registry[timer] = timer
  111. timer.timer = time.AfterFunc(timer.duration, func() {
  112. ready <- timer
  113. })
  114. return timer, re.vm.ToValue(timer)
  115. }
  116. setTimeout := func(call goja.FunctionCall) goja.Value {
  117. _, value := newTimer(call, false)
  118. return value
  119. }
  120. setInterval := func(call goja.FunctionCall) goja.Value {
  121. _, value := newTimer(call, true)
  122. return value
  123. }
  124. clearTimeout := func(call goja.FunctionCall) goja.Value {
  125. timer := call.Argument(0).Export()
  126. if timer, ok := timer.(*jsTimer); ok {
  127. timer.timer.Stop()
  128. delete(registry, timer)
  129. }
  130. return goja.Undefined()
  131. }
  132. re.vm.Set("_setTimeout", setTimeout)
  133. re.vm.Set("_setInterval", setInterval)
  134. re.vm.RunString(`var setTimeout = function(args) {
  135. if (arguments.length < 1) {
  136. throw TypeError("Failed to execute 'setTimeout': 1 argument required, but only 0 present.");
  137. }
  138. return _setTimeout.apply(this, arguments);
  139. }`)
  140. re.vm.RunString(`var setInterval = function(args) {
  141. if (arguments.length < 1) {
  142. throw TypeError("Failed to execute 'setInterval': 1 argument required, but only 0 present.");
  143. }
  144. return _setInterval.apply(this, arguments);
  145. }`)
  146. re.vm.Set("clearTimeout", clearTimeout)
  147. re.vm.Set("clearInterval", clearTimeout)
  148. var waitForCallbacks bool
  149. loop:
  150. for {
  151. select {
  152. case timer := <-ready:
  153. // execute callback, remove/reschedule the timer
  154. var arguments []interface{}
  155. if len(timer.call.Arguments) > 2 {
  156. tmp := timer.call.Arguments[2:]
  157. arguments = make([]interface{}, 2+len(tmp))
  158. for i, value := range tmp {
  159. arguments[i+2] = value
  160. }
  161. } else {
  162. arguments = make([]interface{}, 1)
  163. }
  164. arguments[0] = timer.call.Arguments[0]
  165. call, isFunc := goja.AssertFunction(timer.call.Arguments[0])
  166. if !isFunc {
  167. panic(re.vm.ToValue("js error: timer/timeout callback is not a function"))
  168. }
  169. call(goja.Null(), timer.call.Arguments...)
  170. _, inreg := registry[timer] // when clearInterval is called from within the callback don't reset it
  171. if timer.interval && inreg {
  172. timer.timer.Reset(timer.duration)
  173. } else {
  174. delete(registry, timer)
  175. if waitForCallbacks && (len(registry) == 0) {
  176. break loop
  177. }
  178. }
  179. case req := <-re.evalQueue:
  180. // run the code, send the result back
  181. req.fn(re.vm)
  182. close(req.done)
  183. if waitForCallbacks && (len(registry) == 0) {
  184. break loop
  185. }
  186. case waitForCallbacks = <-re.stopEventLoop:
  187. if !waitForCallbacks || (len(registry) == 0) {
  188. break loop
  189. }
  190. }
  191. }
  192. for _, timer := range registry {
  193. timer.timer.Stop()
  194. delete(registry, timer)
  195. }
  196. }
  197. // Do executes the given function on the JS event loop.
  198. func (re *JSRE) Do(fn func(*goja.Runtime)) {
  199. done := make(chan bool)
  200. req := &evalReq{fn, done}
  201. re.evalQueue <- req
  202. <-done
  203. }
  204. // stops the event loop before exit, optionally waits for all timers to expire
  205. func (re *JSRE) Stop(waitForCallbacks bool) {
  206. select {
  207. case <-re.closed:
  208. case re.stopEventLoop <- waitForCallbacks:
  209. <-re.closed
  210. }
  211. }
  212. // Exec(file) loads and runs the contents of a file
  213. // if a relative path is given, the jsre's assetPath is used
  214. func (re *JSRE) Exec(file string) error {
  215. code, err := ioutil.ReadFile(common.AbsolutePath(re.assetPath, file))
  216. if err != nil {
  217. return err
  218. }
  219. return re.Compile(file, string(code))
  220. }
  221. // Run runs a piece of JS code.
  222. func (re *JSRE) Run(code string) (v goja.Value, err error) {
  223. re.Do(func(vm *goja.Runtime) { v, err = vm.RunString(code) })
  224. return v, err
  225. }
  226. // Set assigns value v to a variable in the JS environment.
  227. func (re *JSRE) Set(ns string, v interface{}) (err error) {
  228. re.Do(func(vm *goja.Runtime) { vm.Set(ns, v) })
  229. return err
  230. }
  231. // MakeCallback turns the given function into a function that's callable by JS.
  232. func MakeCallback(vm *goja.Runtime, fn func(Call) (goja.Value, error)) goja.Value {
  233. return vm.ToValue(func(call goja.FunctionCall) goja.Value {
  234. result, err := fn(Call{call, vm})
  235. if err != nil {
  236. panic(vm.NewGoError(err))
  237. }
  238. return result
  239. })
  240. }
  241. // Evaluate executes code and pretty prints the result to the specified output stream.
  242. func (re *JSRE) Evaluate(code string, w io.Writer) {
  243. re.Do(func(vm *goja.Runtime) {
  244. val, err := vm.RunString(code)
  245. if err != nil {
  246. prettyError(vm, err, w)
  247. } else {
  248. prettyPrint(vm, val, w)
  249. }
  250. fmt.Fprintln(w)
  251. })
  252. }
  253. // Compile compiles and then runs a piece of JS code.
  254. func (re *JSRE) Compile(filename string, src string) (err error) {
  255. re.Do(func(vm *goja.Runtime) { _, err = compileAndRun(vm, filename, src) })
  256. return err
  257. }
  258. // loadScript loads and executes a JS file.
  259. func (re *JSRE) loadScript(call Call) (goja.Value, error) {
  260. file := call.Argument(0).ToString().String()
  261. file = common.AbsolutePath(re.assetPath, file)
  262. source, err := ioutil.ReadFile(file)
  263. if err != nil {
  264. return nil, fmt.Errorf("Could not read file %s: %v", file, err)
  265. }
  266. value, err := compileAndRun(re.vm, file, string(source))
  267. if err != nil {
  268. return nil, fmt.Errorf("Error while compiling or running script: %v", err)
  269. }
  270. return value, nil
  271. }
  272. func compileAndRun(vm *goja.Runtime, filename string, src string) (goja.Value, error) {
  273. script, err := goja.Compile(filename, src, false)
  274. if err != nil {
  275. return goja.Null(), err
  276. }
  277. return vm.RunProgram(script)
  278. }