JSVM.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Duktape/duktape.h>
  23. #include <Atomic/Core/Profiler.h>
  24. #include <Atomic/Core/CoreEvents.h>
  25. #include <Atomic/IO/File.h>
  26. #include <Atomic/IO/Log.h>
  27. #include <Atomic/IO/FileSystem.h>
  28. #include <Atomic/IO/PackageFile.h>
  29. #include <Atomic/Resource/ResourceCache.h>
  30. #include "JSRequire.h"
  31. #include "JSPlugin.h"
  32. #include "JSEvents.h"
  33. #include "JSVM.h"
  34. #include "JSAtomic.h"
  35. #include "JSUI.h"
  36. #include "JSMetrics.h"
  37. #include "JSEventHelper.h"
  38. namespace Atomic
  39. {
  40. JSVM* JSVM::instance_ = NULL;
  41. JSVM::JSVM(Context* context) :
  42. Object(context),
  43. ctx_(0),
  44. gcTime_(0.0f)
  45. {
  46. assert(!instance_);
  47. instance_ = this;
  48. metrics_ = new JSMetrics(context, this);
  49. SharedPtr<JSEventDispatcher> dispatcher(new JSEventDispatcher(context_));
  50. context_->RegisterSubsystem(dispatcher);
  51. context_->AddGlobalEventListener(dispatcher);
  52. }
  53. JSVM::~JSVM()
  54. {
  55. context_->RemoveGlobalEventListener(context_->GetSubsystem<JSEventDispatcher>());
  56. context_->RemoveSubsystem(JSEventDispatcher::GetTypeStatic());
  57. duk_destroy_heap(ctx_);
  58. instance_ = NULL;
  59. }
  60. void JSVM::InitJSContext()
  61. {
  62. ctx_ = duk_create_heap_default();
  63. jsapi_init_atomic(this);
  64. // register whether we are in the editor
  65. duk_get_global_string(ctx_, "Atomic");
  66. duk_push_boolean(ctx_, context_->GetEditorContext() ? 1 : 0);
  67. duk_put_prop_string(ctx_, -2, "editor");
  68. duk_pop(ctx_);
  69. duk_push_global_stash(ctx_);
  70. duk_push_object(ctx_);
  71. duk_put_prop_index(ctx_, -2, JS_GLOBALSTASH_INDEX_COMPONENTS);
  72. duk_pop(ctx_);
  73. js_init_require(this);
  74. js_init_jsplugin(this);
  75. ui_ = new JSUI(context_);
  76. // handle this elsewhere?
  77. SubscribeToEvents();
  78. }
  79. void JSVM::SubscribeToEvents()
  80. {
  81. SubscribeToEvent(E_UPDATE, HANDLER(JSVM, HandleUpdate));
  82. }
  83. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  84. {
  85. PROFILE(JSVM_HandleUpdate);
  86. using namespace Update;
  87. // Take the frame time step, which is stored as a float
  88. float timeStep = eventData[P_TIMESTEP].GetFloat();
  89. gcTime_ += timeStep;
  90. if (gcTime_ > 5.0f)
  91. {
  92. PROFILE(JSVM_GC);
  93. // run twice to call finalizers
  94. // see duktape docs
  95. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  96. // is enabled in duktape.h
  97. duk_gc(ctx_, 0);
  98. duk_gc(ctx_, 0);
  99. gcTime_ = 0;
  100. }
  101. duk_get_global_string(ctx_, "__js_atomic_main_update");
  102. if (duk_is_function(ctx_, -1))
  103. {
  104. duk_push_number(ctx_, timeStep);
  105. duk_pcall(ctx_, 1);
  106. duk_pop(ctx_);
  107. }
  108. else
  109. {
  110. duk_pop(ctx_);
  111. }
  112. }
  113. bool JSVM::ExecuteFunction(const String& functionName)
  114. {
  115. duk_get_global_string(ctx_, functionName.CString());
  116. if (duk_is_function(ctx_, -1))
  117. {
  118. bool ok = true;
  119. if (duk_pcall(ctx_, 0) != 0)
  120. {
  121. ok = false;
  122. if (duk_is_object(ctx_, -1))
  123. {
  124. SendJSErrorEvent();
  125. }
  126. else
  127. {
  128. assert(0);
  129. }
  130. }
  131. duk_pop(ctx_);
  132. return ok;
  133. }
  134. else
  135. {
  136. duk_pop(ctx_);
  137. }
  138. return false;
  139. }
  140. void JSVM::SendJSErrorEvent(const String& filename)
  141. {
  142. duk_context* ctx = GetJSContext();
  143. using namespace JSError;
  144. VariantMap eventData;
  145. if (duk_is_string(ctx, -1))
  146. {
  147. eventData[P_ERRORNAME] = "(Unknown Error Name)";
  148. eventData[P_ERRORFILENAME] = "(Unknown Filename)";
  149. eventData[P_ERRORLINENUMBER] = -1;
  150. eventData[P_ERRORMESSAGE] = duk_to_string(ctx, -1);
  151. eventData[P_ERRORSTACK] = "";
  152. SendEvent(E_JSERROR, eventData);
  153. return;
  154. }
  155. assert(duk_is_object(ctx, -1));
  156. duk_get_prop_string(ctx, -1, "fileName");
  157. if (duk_is_string(ctx, -1))
  158. {
  159. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  160. }
  161. else
  162. {
  163. eventData[P_ERRORFILENAME] = filename;
  164. }
  165. // Component script are wrapped within a closure, the line number
  166. // needs to be offset by this header
  167. duk_get_prop_string(ctx, -2, "lineNumber");
  168. int lineNumber = (int) (duk_to_number(ctx, -1));
  169. eventData[P_ERRORLINENUMBER] = lineNumber;
  170. duk_get_prop_string(ctx, -3, "name");
  171. String name = duk_to_string(ctx, -1);
  172. eventData[P_ERRORNAME] = name;
  173. duk_get_prop_string(ctx, -4, "message");
  174. String message = duk_to_string(ctx, -1);
  175. eventData[P_ERRORMESSAGE] = message;
  176. // we're not getting good file/line from duktape on parser errors
  177. if (name == "SyntaxError")
  178. {
  179. lineNumber = -1;
  180. // parse line if we have it
  181. if (message.Contains("(line "))
  182. {
  183. if (!filename.Length())
  184. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  185. unsigned pos = message.Find("(line ");
  186. const char* parse = message.CString() + pos + 6;
  187. String number;
  188. while (*parse >= '0' && *parse<='9')
  189. {
  190. number += *parse;
  191. parse++;
  192. }
  193. lineNumber = ToInt(number);
  194. }
  195. eventData[P_ERRORLINENUMBER] = lineNumber;
  196. }
  197. duk_get_prop_string(ctx, -5, "stack");
  198. String stack = duk_to_string(ctx, -1);
  199. eventData[P_ERRORSTACK] = stack;
  200. duk_pop_n(ctx, 5);
  201. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  202. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  203. SendEvent(E_JSERROR, eventData);
  204. }
  205. int JSVM::GetRealLineNumber(const String& fileName, const int lineNumber) {
  206. int realLineNumber = lineNumber;
  207. String mapPath = fileName;
  208. if (!mapPath.EndsWith(".js.map"))
  209. mapPath += ".js.map";
  210. if (mapPath.EndsWith(".js")) {
  211. return realLineNumber;
  212. }
  213. ResourceCache* cache = GetSubsystem<ResourceCache>();
  214. String path;
  215. const Vector<String>& searchPaths = GetModuleSearchPaths();
  216. for (unsigned i = 0; i < searchPaths.Size(); i++)
  217. {
  218. String checkPath = searchPaths[i] + mapPath;
  219. if (cache->Exists(checkPath))
  220. {
  221. path = checkPath;
  222. break;
  223. }
  224. }
  225. if (!path.Length())
  226. return realLineNumber;
  227. SharedPtr<File> mapFile(GetSubsystem<ResourceCache>()->GetFile(path));
  228. //if there's no source map file, maybe you use a pure js, so give an error, or maybe forgot to generate source-maps :(
  229. if (mapFile.Null())
  230. {
  231. return realLineNumber;
  232. }
  233. String map;
  234. mapFile->ReadText(map);
  235. int top = duk_get_top(ctx_);
  236. duk_get_global_string(ctx_, "require");
  237. duk_push_string(ctx_, "AtomicEditor/EditorScripts/Lib/jsutils");
  238. if (duk_pcall(ctx_, 1))
  239. {
  240. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  241. duk_set_top(ctx_, top);
  242. return false;
  243. }
  244. duk_get_prop_string(ctx_, -1, "getRealLineNumber");
  245. duk_push_string(ctx_, map.CString());
  246. duk_push_int(ctx_, lineNumber);
  247. bool ok = true;
  248. if (duk_pcall(ctx_, 2))
  249. {
  250. ok = false;
  251. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  252. }
  253. else
  254. {
  255. realLineNumber = duk_to_int(ctx_, -1);
  256. }
  257. duk_set_top(ctx_, top);
  258. return realLineNumber;
  259. }
  260. bool JSVM::ExecuteScript(const String& scriptPath)
  261. {
  262. String path = scriptPath;
  263. if (!path.StartsWith("Scripts/"))
  264. path = "Scripts/" + path;
  265. if (!path.EndsWith(".js"))
  266. path += ".js";
  267. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  268. if (file.Null())
  269. {
  270. return false;
  271. }
  272. String source;
  273. file->ReadText(source);
  274. source.Append('\n');
  275. duk_push_string(ctx_, file->GetFullPath().CString());
  276. if (duk_eval_raw(ctx_, source.CString(), 0,
  277. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  278. {
  279. if (duk_is_object(ctx_, -1))
  280. SendJSErrorEvent(path);
  281. duk_pop(ctx_);
  282. return false;
  283. }
  284. duk_pop(ctx_);
  285. return true;
  286. }
  287. bool JSVM::ExecuteFile(File *file)
  288. {
  289. if (!file)
  290. return false;
  291. String source;
  292. file->ReadText(source);
  293. source.Append('\n');
  294. duk_push_string(ctx_, file->GetFullPath().CString());
  295. if (duk_eval_raw(ctx_, source.CString(), 0,
  296. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  297. {
  298. SendJSErrorEvent(file->GetFullPath());
  299. duk_pop(ctx_);
  300. return false;
  301. }
  302. duk_pop(ctx_);
  303. return true;
  304. }
  305. void JSVM::GC()
  306. {
  307. // run twice to ensure finalizers are run
  308. duk_gc(ctx_, 0);
  309. duk_gc(ctx_, 0);
  310. }
  311. bool JSVM::ExecuteMain()
  312. {
  313. if (!GetSubsystem<ResourceCache>()->Exists("Scripts/main.js"))
  314. return true;
  315. duk_get_global_string(ctx_, "require");
  316. duk_push_string(ctx_, "Scripts/main");
  317. if (duk_pcall(ctx_, 1) != 0)
  318. {
  319. SendJSErrorEvent();
  320. return false;
  321. }
  322. if (duk_is_object(ctx_, -1))
  323. {
  324. duk_get_prop_string(ctx_, -1, "update");
  325. if (duk_is_function(ctx_, -1))
  326. {
  327. // store function for main loop
  328. duk_put_global_string(ctx_, "__js_atomic_main_update");
  329. }
  330. else
  331. {
  332. duk_pop(ctx_);
  333. }
  334. }
  335. // pop main module
  336. duk_pop(ctx_);
  337. return true;
  338. }
  339. }