JSVM.cpp 11 KB

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