jsre.go 8.8 KB

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