JSVM.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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 <Duktape/duk_logging.h>
  24. #include <Duktape/duk_module_duktape.h>
  25. #include <Atomic/Core/Profiler.h>
  26. #include <Atomic/Core/CoreEvents.h>
  27. #include <Atomic/IO/File.h>
  28. #include <Atomic/IO/Log.h>
  29. #include <Atomic/IO/FileSystem.h>
  30. #include <Atomic/IO/PackageFile.h>
  31. #include <Atomic/Resource/ResourceCache.h>
  32. #include "JSRequire.h"
  33. #include "JSPlugin.h"
  34. #include "JSEvents.h"
  35. #include "JSVM.h"
  36. #include "JSAtomic.h"
  37. #include "JSUI.h"
  38. #include "JSMetrics.h"
  39. #include "JSEventHelper.h"
  40. namespace Atomic
  41. {
  42. JSVM* JSVM::instance_ = NULL;
  43. Vector<JSVM::JSAPIPackageRegistration*> JSVM::packageRegistrations_;
  44. JSVM::JSVM(Context* context) :
  45. Object(context),
  46. ctx_(0),
  47. gcTime_(0.0f),
  48. stashCount_(0),
  49. totalStashCount_(0),
  50. totalUnstashCount_(0)
  51. {
  52. assert(!instance_);
  53. instance_ = this;
  54. metrics_ = new JSMetrics(context, this);
  55. SharedPtr<JSEventDispatcher> dispatcher(new JSEventDispatcher(context_));
  56. context_->RegisterSubsystem(dispatcher);
  57. context_->AddGlobalEventListener(dispatcher);
  58. RefCounted::AddRefCountChangedFunction(OnRefCountChanged);
  59. }
  60. JSVM::~JSVM()
  61. {
  62. context_->RemoveGlobalEventListener(context_->GetSubsystem<JSEventDispatcher>());
  63. context_->RemoveSubsystem(JSEventDispatcher::GetTypeStatic());
  64. duk_destroy_heap(ctx_);
  65. RefCounted::RemoveRefCountChangedFunction(OnRefCountChanged);
  66. // assert(stashCount_ == 0);
  67. instance_ = NULL;
  68. }
  69. void JSVM::InitJSContext()
  70. {
  71. ctx_ = duk_create_heap_default();
  72. duk_logging_init(ctx_, 0);
  73. duk_module_duktape_init(ctx_);
  74. jsapi_init_atomic(this);
  75. // register whether we are in the editor
  76. duk_get_global_string(ctx_, "Atomic");
  77. duk_push_boolean(ctx_, context_->GetEditorContext() ? 1 : 0);
  78. duk_put_prop_string(ctx_, -2, "editor");
  79. duk_pop(ctx_);
  80. js_init_require(this);
  81. js_init_jsplugin(this);
  82. ui_ = new JSUI(context_);
  83. InitializePackages();
  84. // handle this elsewhere?
  85. SubscribeToEvents();
  86. }
  87. void JSVM::InitializePackages()
  88. {
  89. for (unsigned i = 0; i < packageRegistrations_.Size(); i++)
  90. {
  91. JSAPIPackageRegistration* pkgReg = packageRegistrations_.At(i);
  92. if (pkgReg->registrationFunction)
  93. {
  94. pkgReg->registrationFunction(this);
  95. }
  96. else
  97. {
  98. pkgReg->registrationSettingsFunction(this, pkgReg->settings);
  99. }
  100. delete pkgReg;
  101. }
  102. packageRegistrations_.Clear();
  103. }
  104. void JSVM::RegisterPackage(JSVMPackageRegistrationFunction regFunction)
  105. {
  106. packageRegistrations_.Push(new JSAPIPackageRegistration(regFunction));
  107. }
  108. void JSVM::RegisterPackage(JSVMPackageRegistrationSettingsFunction regFunction, const VariantMap& settings)
  109. {
  110. packageRegistrations_.Push(new JSAPIPackageRegistration(regFunction, settings));
  111. }
  112. void JSVM::SubscribeToEvents()
  113. {
  114. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(JSVM, HandleUpdate));
  115. }
  116. void JSVM::OnRefCountChanged(RefCounted* refCounted, int refCount)
  117. {
  118. assert(instance_);
  119. assert(refCounted->JSGetHeapPtr());
  120. if (refCount == 1)
  121. {
  122. // only script reference is left, so unstash
  123. instance_->Unstash(refCounted);
  124. }
  125. else if (refCount == 2)
  126. {
  127. // We are going from solely having a script reference to having another reference
  128. instance_->Stash(refCounted);
  129. }
  130. }
  131. void JSVM::Stash(RefCounted* refCounted)
  132. {
  133. assert(refCounted);
  134. assert(refCounted->JSGetHeapPtr());
  135. totalStashCount_++;
  136. stashCount_++;
  137. duk_push_global_stash(ctx_);
  138. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_REFCOUNTED_REGISTRY);
  139. // can't use instance as key, as this coerces to [Object] for
  140. // string property, pointer will be string representation of
  141. // address, so, unique key
  142. /*
  143. duk_push_pointer(ctx_, refCounted);
  144. duk_get_prop(ctx_, -2);
  145. assert(duk_is_undefined(ctx_, -1));
  146. duk_pop(ctx_);
  147. */
  148. duk_push_pointer(ctx_, refCounted);
  149. duk_push_heapptr(ctx_, refCounted->JSGetHeapPtr());
  150. duk_put_prop(ctx_, -3);
  151. duk_pop_2(ctx_);
  152. }
  153. void JSVM::Unstash(RefCounted* refCounted)
  154. {
  155. assert(refCounted);
  156. assert(refCounted->JSGetHeapPtr());
  157. assert(stashCount_ > 0);
  158. stashCount_--;
  159. totalUnstashCount_++;
  160. duk_push_global_stash(ctx_);
  161. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_REFCOUNTED_REGISTRY);
  162. // can't use instance as key, as this coerces to [Object] for
  163. // string property, pointer will be string representation of
  164. // address, so, unique key
  165. /*
  166. duk_push_pointer(ctx_, refCounted);
  167. duk_get_prop(ctx_, -2);
  168. assert(!duk_is_undefined(ctx_, -1));
  169. duk_pop(ctx_);
  170. */
  171. duk_push_pointer(ctx_, refCounted);
  172. duk_del_prop(ctx_, -2);
  173. duk_pop_2(ctx_);
  174. }
  175. // Returns if the given object is stashed
  176. bool JSVM::GetStashed(RefCounted* refcounted) const
  177. {
  178. duk_push_global_stash(ctx_);
  179. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_REFCOUNTED_REGISTRY);
  180. duk_push_pointer(ctx_, refcounted);
  181. duk_get_prop(ctx_, -2);
  182. bool result = !duk_is_undefined(ctx_, -1);
  183. duk_pop_3(ctx_);
  184. return result;
  185. }
  186. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  187. {
  188. ATOMIC_PROFILE(JSVM_HandleUpdate);
  189. using namespace Update;
  190. // Take the frame time step, which is stored as a float
  191. float timeStep = eventData[P_TIMESTEP].GetFloat();
  192. gcTime_ += timeStep;
  193. if (gcTime_ > 5.0f)
  194. {
  195. ATOMIC_PROFILE(JSVM_GC);
  196. // run twice to call finalizers
  197. // see duktape docs
  198. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  199. // is enabled in duktape.h
  200. duk_gc(ctx_, 0);
  201. duk_gc(ctx_, 0);
  202. gcTime_ = 0;
  203. // DumpJavascriptObjects();
  204. }
  205. duk_get_global_string(ctx_, "__js_atomic_main_update");
  206. if (duk_is_function(ctx_, -1))
  207. {
  208. duk_push_number(ctx_, timeStep);
  209. duk_pcall(ctx_, 1);
  210. duk_pop(ctx_);
  211. }
  212. else
  213. {
  214. duk_pop(ctx_);
  215. }
  216. }
  217. bool JSVM::ExecuteFunction(const String& functionName)
  218. {
  219. duk_get_global_string(ctx_, functionName.CString());
  220. if (duk_is_function(ctx_, -1))
  221. {
  222. bool ok = true;
  223. if (duk_pcall(ctx_, 0) != 0)
  224. {
  225. ok = false;
  226. if (duk_is_object(ctx_, -1))
  227. {
  228. SendJSErrorEvent();
  229. }
  230. else
  231. {
  232. assert(0);
  233. }
  234. }
  235. duk_pop(ctx_);
  236. return ok;
  237. }
  238. else
  239. {
  240. duk_pop(ctx_);
  241. }
  242. return false;
  243. }
  244. void JSVM::SendJSErrorEvent(const String& filename)
  245. {
  246. duk_context* ctx = GetJSContext();
  247. using namespace JSError;
  248. VariantMap eventData;
  249. if (duk_is_string(ctx, -1))
  250. {
  251. eventData[P_ERRORNAME] = "(Unknown Error Name)";
  252. eventData[P_ERRORFILENAME] = "(Unknown Filename)";
  253. eventData[P_ERRORLINENUMBER] = -1;
  254. eventData[P_ERRORMESSAGE] = duk_to_string(ctx, -1);
  255. eventData[P_ERRORSTACK] = "";
  256. SendEvent(E_JSERROR, eventData);
  257. return;
  258. }
  259. assert(duk_is_object(ctx, -1));
  260. duk_get_prop_string(ctx, -1, "fileName");
  261. if (duk_is_string(ctx, -1))
  262. {
  263. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  264. }
  265. else
  266. {
  267. eventData[P_ERRORFILENAME] = filename;
  268. }
  269. // Component script are wrapped within a closure, the line number
  270. // needs to be offset by this header
  271. duk_get_prop_string(ctx, -2, "lineNumber");
  272. int lineNumber = (int) (duk_to_number(ctx, -1));
  273. eventData[P_ERRORLINENUMBER] = lineNumber;
  274. duk_get_prop_string(ctx, -3, "name");
  275. String name = duk_to_string(ctx, -1);
  276. eventData[P_ERRORNAME] = name;
  277. duk_get_prop_string(ctx, -4, "message");
  278. String message = duk_to_string(ctx, -1);
  279. eventData[P_ERRORMESSAGE] = message;
  280. // we're not getting good file/line from duktape on parser errors
  281. if (name == "SyntaxError")
  282. {
  283. lineNumber = -1;
  284. // parse line if we have it
  285. if (message.Contains("(line "))
  286. {
  287. if (!filename.Length())
  288. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  289. unsigned pos = message.Find("(line ");
  290. const char* parse = message.CString() + pos + 6;
  291. String number;
  292. while (*parse >= '0' && *parse<='9')
  293. {
  294. number += *parse;
  295. parse++;
  296. }
  297. lineNumber = ToInt(number);
  298. }
  299. eventData[P_ERRORLINENUMBER] = lineNumber;
  300. }
  301. duk_get_prop_string(ctx, -5, "stack");
  302. String stack = duk_to_string(ctx, -1);
  303. eventData[P_ERRORSTACK] = stack;
  304. duk_pop_n(ctx, 5);
  305. ATOMIC_LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  306. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  307. SendEvent(E_JSERROR, eventData);
  308. }
  309. int JSVM::GetRealLineNumber(const String& fileName, const int lineNumber) {
  310. int realLineNumber = lineNumber;
  311. String mapPath = fileName;
  312. if (!mapPath.EndsWith(".js.map"))
  313. mapPath += ".js.map";
  314. if (mapPath.EndsWith(".js")) {
  315. return realLineNumber;
  316. }
  317. ResourceCache* cache = GetSubsystem<ResourceCache>();
  318. String path;
  319. const Vector<String>& searchPaths = GetModuleSearchPaths();
  320. for (unsigned i = 0; i < searchPaths.Size(); i++)
  321. {
  322. String checkPath = searchPaths[i] + mapPath;
  323. if (cache->Exists(checkPath))
  324. {
  325. path = checkPath;
  326. break;
  327. }
  328. }
  329. if (!path.Length())
  330. return realLineNumber;
  331. SharedPtr<File> mapFile(GetSubsystem<ResourceCache>()->GetFile(path));
  332. //if there's no source map file, maybe you use a pure js, so give an error, or maybe forgot to generate source-maps :(
  333. if (mapFile.Null())
  334. {
  335. return realLineNumber;
  336. }
  337. String map;
  338. mapFile->ReadText(map);
  339. int top = duk_get_top(ctx_);
  340. duk_get_global_string(ctx_, "require");
  341. duk_push_string(ctx_, "AtomicEditor/JavaScript/Lib/jsutils");
  342. if (duk_pcall(ctx_, 1))
  343. {
  344. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  345. duk_set_top(ctx_, top);
  346. return false;
  347. }
  348. duk_get_prop_string(ctx_, -1, "getRealLineNumber");
  349. duk_push_string(ctx_, map.CString());
  350. duk_push_int(ctx_, lineNumber);
  351. bool ok = true;
  352. if (duk_pcall(ctx_, 2))
  353. {
  354. ok = false;
  355. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  356. }
  357. else
  358. {
  359. realLineNumber = duk_to_int(ctx_, -1);
  360. }
  361. duk_set_top(ctx_, top);
  362. return realLineNumber;
  363. }
  364. bool JSVM::ExecuteScript(const String& scriptPath)
  365. {
  366. String path = scriptPath;
  367. if (!path.StartsWith("Scripts/"))
  368. path = "Scripts/" + path;
  369. if (!path.EndsWith(".js"))
  370. path += ".js";
  371. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  372. if (file.Null())
  373. {
  374. return false;
  375. }
  376. String source;
  377. file->ReadText(source);
  378. source.Append('\n');
  379. duk_push_string(ctx_, file->GetFullPath().CString());
  380. if (duk_eval_raw(ctx_, source.CString(), 0,
  381. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  382. {
  383. if (duk_is_object(ctx_, -1))
  384. SendJSErrorEvent(path);
  385. duk_pop(ctx_);
  386. return false;
  387. }
  388. duk_pop(ctx_);
  389. return true;
  390. }
  391. bool JSVM::ExecuteFile(File *file)
  392. {
  393. if (!file)
  394. return false;
  395. String source;
  396. file->ReadText(source);
  397. source.Append('\n');
  398. duk_push_string(ctx_, file->GetFullPath().CString());
  399. if (duk_eval_raw(ctx_, source.CString(), 0,
  400. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  401. {
  402. SendJSErrorEvent(file->GetFullPath());
  403. duk_pop(ctx_);
  404. return false;
  405. }
  406. duk_pop(ctx_);
  407. return true;
  408. }
  409. void JSVM::GC()
  410. {
  411. // run twice to ensure finalizers are run
  412. duk_gc(ctx_, 0);
  413. duk_gc(ctx_, 0);
  414. }
  415. bool JSVM::ExecuteMain()
  416. {
  417. if (!GetSubsystem<ResourceCache>()->Exists("Scripts/main.js"))
  418. return true;
  419. duk_get_global_string(ctx_, "require");
  420. duk_push_string(ctx_, "Scripts/main");
  421. if (duk_pcall(ctx_, 1) != 0)
  422. {
  423. SendJSErrorEvent();
  424. return false;
  425. }
  426. if (duk_is_object(ctx_, -1))
  427. {
  428. duk_get_prop_string(ctx_, -1, "update");
  429. if (duk_is_function(ctx_, -1))
  430. {
  431. // store function for main loop
  432. duk_put_global_string(ctx_, "__js_atomic_main_update");
  433. }
  434. else
  435. {
  436. duk_pop(ctx_);
  437. }
  438. }
  439. // pop main module
  440. duk_pop(ctx_);
  441. return true;
  442. }
  443. void JSVM::DumpJavascriptObjects()
  444. {
  445. ATOMIC_LOGINFOF("--- JS Objects ---");
  446. ATOMIC_LOGINFOF("Stash Count: %u, Total Stash: %u, Total Unstash: %u", stashCount_, totalStashCount_, totalUnstashCount_);
  447. HashMap<StringHash, String> strLookup;
  448. HashMap<StringHash, unsigned> totalClassCount;
  449. HashMap<StringHash, unsigned> stashedClassCount;
  450. HashMap<StringHash, int> maxRefCount;
  451. StringHash refCountedTypeHash("RefCounted");
  452. strLookup[refCountedTypeHash] = "RefCounted";
  453. duk_push_global_stash(ctx_);
  454. duk_get_prop_index(ctx_, -1, JS_GLOBALSTASH_INDEX_REFCOUNTED_REGISTRY);
  455. HashMap<void*, RefCounted*>::ConstIterator itr = heapToObject_.Begin();
  456. while (itr != heapToObject_.End())
  457. {
  458. void* heapPtr = itr->first_;
  459. RefCounted* refCounted = itr->second_;
  460. // TODO: need a lookup for refcounted classid to typename
  461. const String& className = refCounted->IsObject() ? ((Object*)refCounted)->GetTypeName() : "RefCounted";
  462. StringHash typeHash = refCounted->IsObject() ? ((Object*)refCounted)->GetType() : refCountedTypeHash;
  463. strLookup.InsertNew(typeHash, className);
  464. totalClassCount.InsertNew(typeHash, 0);
  465. totalClassCount[typeHash]++;
  466. maxRefCount.InsertNew(typeHash, 0);
  467. if (refCounted->Refs() > maxRefCount[typeHash])
  468. maxRefCount[typeHash] = refCounted->Refs();
  469. duk_push_pointer(ctx_, refCounted);
  470. duk_get_prop(ctx_, -2);
  471. if (!duk_is_undefined(ctx_, -1))
  472. {
  473. stashedClassCount.InsertNew(typeHash, 0);
  474. stashedClassCount[typeHash]++;
  475. }
  476. duk_pop(ctx_);
  477. itr++;
  478. }
  479. HashMap<StringHash, String>::ConstIterator itr2 = strLookup.Begin();
  480. while (itr2 != strLookup.End())
  481. {
  482. StringHash typeHash = itr2->first_;
  483. const String& className = itr2->second_;
  484. unsigned totalCount = totalClassCount[typeHash];
  485. unsigned stashedCount = stashedClassCount[typeHash];
  486. int _maxRefCount = maxRefCount[typeHash];
  487. ATOMIC_LOGINFOF("Classname: %s, Total: %u, Stashed: %u, Max Refs: %i", className.CString(), totalCount, stashedCount, _maxRefCount);
  488. itr2++;
  489. }
  490. duk_pop_2(ctx_);
  491. }
  492. }