JSVM.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. context_->RegisterSubsystem(new JSEventDispatcher(context_));
  50. context_->SetGlobalEventListener(context_->GetSubsystem<JSEventDispatcher>());
  51. }
  52. JSVM::~JSVM()
  53. {
  54. context_->SetGlobalEventListener(0);
  55. context_->RemoveSubsystem(JSEventDispatcher::GetTypeStatic());
  56. duk_destroy_heap(ctx_);
  57. instance_ = NULL;
  58. }
  59. void JSVM::InitJSContext()
  60. {
  61. ctx_ = duk_create_heap_default();
  62. jsapi_init_atomic(this);
  63. // register whether we are in the editor
  64. duk_get_global_string(ctx_, "Atomic");
  65. duk_push_boolean(ctx_, context_->GetEditorContext() ? 1 : 0);
  66. duk_put_prop_string(ctx_, -2, "editor");
  67. duk_pop(ctx_);
  68. duk_push_global_stash(ctx_);
  69. duk_push_object(ctx_);
  70. duk_put_prop_index(ctx_, -2, JS_GLOBALSTASH_INDEX_COMPONENTS);
  71. duk_pop(ctx_);
  72. js_init_require(this);
  73. js_init_jsplugin(this);
  74. ui_ = new JSUI(context_);
  75. // handle this elsewhere?
  76. SubscribeToEvents();
  77. }
  78. void JSVM::SubscribeToEvents()
  79. {
  80. SubscribeToEvent(E_UPDATE, HANDLER(JSVM, HandleUpdate));
  81. }
  82. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  83. {
  84. PROFILE(JSVM_HandleUpdate);
  85. using namespace Update;
  86. // Take the frame time step, which is stored as a float
  87. float timeStep = eventData[P_TIMESTEP].GetFloat();
  88. gcTime_ += timeStep;
  89. if (gcTime_ > 5.0f)
  90. {
  91. PROFILE(JSVM_GC);
  92. // run twice to call finalizers
  93. // see duktape docs
  94. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  95. // is enabled in duktape.h
  96. duk_gc(ctx_, 0);
  97. duk_gc(ctx_, 0);
  98. gcTime_ = 0;
  99. }
  100. duk_get_global_string(ctx_, "__js_atomic_main_update");
  101. if (duk_is_function(ctx_, -1))
  102. {
  103. duk_push_number(ctx_, timeStep);
  104. duk_pcall(ctx_, 1);
  105. duk_pop(ctx_);
  106. }
  107. else
  108. {
  109. duk_pop(ctx_);
  110. }
  111. }
  112. bool JSVM::ExecuteFunction(const String& functionName)
  113. {
  114. duk_get_global_string(ctx_, functionName.CString());
  115. if (duk_is_function(ctx_, -1))
  116. {
  117. bool ok = true;
  118. if (duk_pcall(ctx_, 0) != 0)
  119. {
  120. ok = false;
  121. if (duk_is_object(ctx_, -1))
  122. {
  123. SendJSErrorEvent();
  124. }
  125. else
  126. {
  127. assert(0);
  128. }
  129. }
  130. duk_pop(ctx_);
  131. return ok;
  132. }
  133. else
  134. {
  135. duk_pop(ctx_);
  136. }
  137. return false;
  138. }
  139. void JSVM::SendJSErrorEvent(const String& filename)
  140. {
  141. duk_context* ctx = GetJSContext();
  142. using namespace JSError;
  143. VariantMap eventData;
  144. if (duk_is_string(ctx, -1))
  145. {
  146. eventData[P_ERRORNAME] = "(Unknown Error Name)";
  147. eventData[P_ERRORFILENAME] = "(Unknown Filename)";
  148. eventData[P_ERRORLINENUMBER] = -1;
  149. eventData[P_ERRORMESSAGE] = duk_to_string(ctx, -1);
  150. eventData[P_ERRORSTACK] = "";
  151. SendEvent(E_JSERROR, eventData);
  152. return;
  153. }
  154. assert(duk_is_object(ctx, -1));
  155. duk_get_prop_string(ctx, -1, "fileName");
  156. if (duk_is_string(ctx, -1))
  157. {
  158. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  159. }
  160. else
  161. {
  162. eventData[P_ERRORFILENAME] = filename;
  163. }
  164. // Component script are wrapped within a closure, the line number
  165. // needs to be offset by this header
  166. duk_get_prop_string(ctx, -2, "lineNumber");
  167. int lineNumber = (int) (duk_to_number(ctx, -1));
  168. eventData[P_ERRORLINENUMBER] = lineNumber;
  169. duk_get_prop_string(ctx, -3, "name");
  170. String name = duk_to_string(ctx, -1);
  171. eventData[P_ERRORNAME] = name;
  172. duk_get_prop_string(ctx, -4, "message");
  173. String message = duk_to_string(ctx, -1);
  174. eventData[P_ERRORMESSAGE] = message;
  175. // we're not getting good file/line from duktape on parser errors
  176. if (name == "SyntaxError")
  177. {
  178. lineNumber = -1;
  179. // parse line if we have it
  180. if (message.Contains("(line "))
  181. {
  182. if (!filename.Length())
  183. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  184. unsigned pos = message.Find("(line ");
  185. const char* parse = message.CString() + pos + 6;
  186. String number;
  187. while (*parse >= '0' && *parse<='9')
  188. {
  189. number += *parse;
  190. parse++;
  191. }
  192. lineNumber = ToInt(number);
  193. }
  194. eventData[P_ERRORLINENUMBER] = lineNumber;
  195. }
  196. duk_get_prop_string(ctx, -5, "stack");
  197. String stack = duk_to_string(ctx, -1);
  198. eventData[P_ERRORSTACK] = stack;
  199. duk_pop_n(ctx, 5);
  200. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  201. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  202. SendEvent(E_JSERROR, eventData);
  203. }
  204. int JSVM::GetRealLineNumber(const String& fileName, const int lineNumber) {
  205. int realLineNumber = lineNumber;
  206. String mapPath = fileName;
  207. if (!mapPath.EndsWith(".js.map"))
  208. mapPath += ".js.map";
  209. if (mapPath.EndsWith(".js")) {
  210. return realLineNumber;
  211. }
  212. ResourceCache* cache = GetSubsystem<ResourceCache>();
  213. String path;
  214. const Vector<String>& searchPaths = GetModuleSearchPaths();
  215. for (unsigned i = 0; i < searchPaths.Size(); i++)
  216. {
  217. String checkPath = searchPaths[i] + mapPath;
  218. if (cache->Exists(checkPath))
  219. {
  220. path = checkPath;
  221. break;
  222. }
  223. }
  224. if (!path.Length())
  225. return realLineNumber;
  226. SharedPtr<File> mapFile(GetSubsystem<ResourceCache>()->GetFile(path));
  227. //if there's no source map file, maybe you use a pure js, so give an error, or maybe forgot to generate source-maps :(
  228. if (mapFile.Null())
  229. {
  230. return realLineNumber;
  231. }
  232. String map;
  233. mapFile->ReadText(map);
  234. int top = duk_get_top(ctx_);
  235. duk_get_global_string(ctx_, "require");
  236. duk_push_string(ctx_, "AtomicEditor/EditorScripts/Lib/jsutils");
  237. if (duk_pcall(ctx_, 1))
  238. {
  239. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  240. duk_set_top(ctx_, top);
  241. return false;
  242. }
  243. duk_get_prop_string(ctx_, -1, "getRealLineNumber");
  244. duk_push_string(ctx_, map.CString());
  245. duk_push_int(ctx_, lineNumber);
  246. bool ok = true;
  247. if (duk_pcall(ctx_, 2))
  248. {
  249. ok = false;
  250. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  251. }
  252. else
  253. {
  254. realLineNumber = duk_to_int(ctx_, -1);
  255. }
  256. duk_set_top(ctx_, top);
  257. return realLineNumber;
  258. }
  259. bool JSVM::ExecuteScript(const String& scriptPath)
  260. {
  261. String path = scriptPath;
  262. if (!path.StartsWith("Scripts/"))
  263. path = "Scripts/" + path;
  264. if (!path.EndsWith(".js"))
  265. path += ".js";
  266. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  267. if (file.Null())
  268. {
  269. return false;
  270. }
  271. String source;
  272. file->ReadText(source);
  273. source.Append('\n');
  274. duk_push_string(ctx_, file->GetFullPath().CString());
  275. if (duk_eval_raw(ctx_, source.CString(), 0,
  276. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  277. {
  278. if (duk_is_object(ctx_, -1))
  279. SendJSErrorEvent(path);
  280. duk_pop(ctx_);
  281. return false;
  282. }
  283. duk_pop(ctx_);
  284. return true;
  285. }
  286. bool JSVM::ExecuteFile(File *file)
  287. {
  288. if (!file)
  289. return false;
  290. String source;
  291. file->ReadText(source);
  292. source.Append('\n');
  293. duk_push_string(ctx_, file->GetFullPath().CString());
  294. if (duk_eval_raw(ctx_, source.CString(), 0,
  295. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  296. {
  297. SendJSErrorEvent(file->GetFullPath());
  298. duk_pop(ctx_);
  299. return false;
  300. }
  301. duk_pop(ctx_);
  302. return true;
  303. }
  304. void JSVM::GC()
  305. {
  306. // run twice to ensure finalizers are run
  307. duk_gc(ctx_, 0);
  308. duk_gc(ctx_, 0);
  309. }
  310. bool JSVM::ExecuteMain()
  311. {
  312. if (!GetSubsystem<ResourceCache>()->Exists("Scripts/main.js"))
  313. return true;
  314. duk_get_global_string(ctx_, "require");
  315. duk_push_string(ctx_, "Scripts/main");
  316. if (duk_pcall(ctx_, 1) != 0)
  317. {
  318. SendJSErrorEvent();
  319. return false;
  320. }
  321. if (duk_is_object(ctx_, -1))
  322. {
  323. duk_get_prop_string(ctx_, -1, "update");
  324. if (duk_is_function(ctx_, -1))
  325. {
  326. // store function for main loop
  327. duk_put_global_string(ctx_, "__js_atomic_main_update");
  328. }
  329. else
  330. {
  331. duk_pop(ctx_);
  332. }
  333. }
  334. // pop main module
  335. duk_pop(ctx_);
  336. return true;
  337. }
  338. }