jsre.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. "fmt"
  20. "io/ioutil"
  21. "sync"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/robertkrimen/otto"
  25. )
  26. /*
  27. JSRE is a generic JS runtime environment embedding the otto JS interpreter.
  28. It provides some helper functions to
  29. - load code from files
  30. - run code snippets
  31. - require libraries
  32. - bind native go objects
  33. */
  34. type JSRE struct {
  35. assetPath string
  36. evalQueue chan *evalReq
  37. stopEventLoop chan bool
  38. loopWg sync.WaitGroup
  39. }
  40. // jsTimer is a single timer instance with a callback function
  41. type jsTimer struct {
  42. timer *time.Timer
  43. duration time.Duration
  44. interval bool
  45. call otto.FunctionCall
  46. }
  47. // evalReq is a serialized vm execution request processed by runEventLoop.
  48. type evalReq struct {
  49. fn func(vm *otto.Otto)
  50. done chan bool
  51. }
  52. // runtime must be stopped with Stop() after use and cannot be used after stopping
  53. func New(assetPath string) *JSRE {
  54. re := &JSRE{
  55. assetPath: assetPath,
  56. evalQueue: make(chan *evalReq),
  57. stopEventLoop: make(chan bool),
  58. }
  59. re.loopWg.Add(1)
  60. go re.runEventLoop()
  61. re.Set("loadScript", re.loadScript)
  62. re.Set("inspect", prettyPrintJS)
  63. return re
  64. }
  65. // This function runs the main event loop from a goroutine that is started
  66. // when JSRE is created. Use Stop() before exiting to properly stop it.
  67. // The event loop processes vm access requests from the evalQueue in a
  68. // serialized way and calls timer callback functions at the appropriate time.
  69. // Exported functions always access the vm through the event queue. You can
  70. // call the functions of the otto vm directly to circumvent the queue. These
  71. // functions should be used if and only if running a routine that was already
  72. // called from JS through an RPC call.
  73. func (self *JSRE) runEventLoop() {
  74. vm := otto.New()
  75. registry := map[*jsTimer]*jsTimer{}
  76. ready := make(chan *jsTimer)
  77. newTimer := func(call otto.FunctionCall, interval bool) (*jsTimer, otto.Value) {
  78. delay, _ := call.Argument(1).ToInteger()
  79. if 0 >= delay {
  80. delay = 1
  81. }
  82. timer := &jsTimer{
  83. duration: time.Duration(delay) * time.Millisecond,
  84. call: call,
  85. interval: interval,
  86. }
  87. registry[timer] = timer
  88. timer.timer = time.AfterFunc(timer.duration, func() {
  89. ready <- timer
  90. })
  91. value, err := call.Otto.ToValue(timer)
  92. if err != nil {
  93. panic(err)
  94. }
  95. return timer, value
  96. }
  97. setTimeout := func(call otto.FunctionCall) otto.Value {
  98. _, value := newTimer(call, false)
  99. return value
  100. }
  101. setInterval := func(call otto.FunctionCall) otto.Value {
  102. _, value := newTimer(call, true)
  103. return value
  104. }
  105. clearTimeout := func(call otto.FunctionCall) otto.Value {
  106. timer, _ := call.Argument(0).Export()
  107. if timer, ok := timer.(*jsTimer); ok {
  108. timer.timer.Stop()
  109. delete(registry, timer)
  110. }
  111. return otto.UndefinedValue()
  112. }
  113. vm.Set("_setTimeout", setTimeout)
  114. vm.Set("_setInterval", setInterval)
  115. vm.Run(`var setTimeout = function(args) {
  116. if (arguments.length < 1) {
  117. throw TypeError("Failed to execute 'setTimeout': 1 argument required, but only 0 present.");
  118. }
  119. return _setTimeout.apply(this, arguments);
  120. }`)
  121. vm.Run(`var setInterval = function(args) {
  122. if (arguments.length < 1) {
  123. throw TypeError("Failed to execute 'setInterval': 1 argument required, but only 0 present.");
  124. }
  125. return _setInterval.apply(this, arguments);
  126. }`)
  127. vm.Set("clearTimeout", clearTimeout)
  128. vm.Set("clearInterval", clearTimeout)
  129. var waitForCallbacks bool
  130. loop:
  131. for {
  132. select {
  133. case timer := <-ready:
  134. // execute callback, remove/reschedule the timer
  135. var arguments []interface{}
  136. if len(timer.call.ArgumentList) > 2 {
  137. tmp := timer.call.ArgumentList[2:]
  138. arguments = make([]interface{}, 2+len(tmp))
  139. for i, value := range tmp {
  140. arguments[i+2] = value
  141. }
  142. } else {
  143. arguments = make([]interface{}, 1)
  144. }
  145. arguments[0] = timer.call.ArgumentList[0]
  146. _, err := vm.Call(`Function.call.call`, nil, arguments...)
  147. if err != nil {
  148. fmt.Println("js error:", err, arguments)
  149. }
  150. _, inreg := registry[timer] // when clearInterval is called from within the callback don't reset it
  151. if timer.interval && inreg {
  152. timer.timer.Reset(timer.duration)
  153. } else {
  154. delete(registry, timer)
  155. if waitForCallbacks && (len(registry) == 0) {
  156. break loop
  157. }
  158. }
  159. case req := <-self.evalQueue:
  160. // run the code, send the result back
  161. req.fn(vm)
  162. close(req.done)
  163. if waitForCallbacks && (len(registry) == 0) {
  164. break loop
  165. }
  166. case waitForCallbacks = <-self.stopEventLoop:
  167. if !waitForCallbacks || (len(registry) == 0) {
  168. break loop
  169. }
  170. }
  171. }
  172. for _, timer := range registry {
  173. timer.timer.Stop()
  174. delete(registry, timer)
  175. }
  176. self.loopWg.Done()
  177. }
  178. // do schedules the given function on the event loop.
  179. func (self *JSRE) do(fn func(*otto.Otto)) {
  180. done := make(chan bool)
  181. req := &evalReq{fn, done}
  182. self.evalQueue <- req
  183. <-done
  184. }
  185. // stops the event loop before exit, optionally waits for all timers to expire
  186. func (self *JSRE) Stop(waitForCallbacks bool) {
  187. self.stopEventLoop <- waitForCallbacks
  188. self.loopWg.Wait()
  189. }
  190. // Exec(file) loads and runs the contents of a file
  191. // if a relative path is given, the jsre's assetPath is used
  192. func (self *JSRE) Exec(file string) error {
  193. code, err := ioutil.ReadFile(common.AbsolutePath(self.assetPath, file))
  194. if err != nil {
  195. return err
  196. }
  197. self.do(func(vm *otto.Otto) { _, err = vm.Run(code) })
  198. return err
  199. }
  200. // Bind assigns value v to a variable in the JS environment
  201. // This method is deprecated, use Set.
  202. func (self *JSRE) Bind(name string, v interface{}) error {
  203. return self.Set(name, v)
  204. }
  205. // Run runs a piece of JS code.
  206. func (self *JSRE) Run(code string) (v otto.Value, err error) {
  207. self.do(func(vm *otto.Otto) { v, err = vm.Run(code) })
  208. return v, err
  209. }
  210. // Get returns the value of a variable in the JS environment.
  211. func (self *JSRE) Get(ns string) (v otto.Value, err error) {
  212. self.do(func(vm *otto.Otto) { v, err = vm.Get(ns) })
  213. return v, err
  214. }
  215. // Set assigns value v to a variable in the JS environment.
  216. func (self *JSRE) Set(ns string, v interface{}) (err error) {
  217. self.do(func(vm *otto.Otto) { err = vm.Set(ns, v) })
  218. return err
  219. }
  220. // loadScript executes a JS script from inside the currently executing JS code.
  221. func (self *JSRE) loadScript(call otto.FunctionCall) otto.Value {
  222. file, err := call.Argument(0).ToString()
  223. if err != nil {
  224. // TODO: throw exception
  225. return otto.FalseValue()
  226. }
  227. file = common.AbsolutePath(self.assetPath, file)
  228. source, err := ioutil.ReadFile(file)
  229. if err != nil {
  230. // TODO: throw exception
  231. return otto.FalseValue()
  232. }
  233. if _, err := compileAndRun(call.Otto, file, source); err != nil {
  234. // TODO: throw exception
  235. fmt.Println("err:", err)
  236. return otto.FalseValue()
  237. }
  238. // TODO: return evaluation result
  239. return otto.TrueValue()
  240. }
  241. // EvalAndPrettyPrint evaluates code and pretty prints the result to
  242. // standard output.
  243. func (self *JSRE) EvalAndPrettyPrint(code string) (err error) {
  244. self.do(func(vm *otto.Otto) {
  245. var val otto.Value
  246. val, err = vm.Run(code)
  247. if err != nil {
  248. return
  249. }
  250. prettyPrint(vm, val)
  251. fmt.Println()
  252. })
  253. return err
  254. }
  255. // Compile compiles and then runs a piece of JS code.
  256. func (self *JSRE) Compile(filename string, src interface{}) (err error) {
  257. self.do(func(vm *otto.Otto) { _, err = compileAndRun(vm, filename, src) })
  258. return err
  259. }
  260. func compileAndRun(vm *otto.Otto, filename string, src interface{}) (otto.Value, error) {
  261. script, err := vm.Compile(filename, src)
  262. if err != nil {
  263. return otto.Value{}, err
  264. }
  265. return vm.Run(script)
  266. }