jsre.go 8.7 KB

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