JSVM.h 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. #pragma once
  23. #include <Atomic/Core/Context.h>
  24. #include <Atomic/Core/Object.h>
  25. #include <Atomic/Container/List.h>
  26. #include <Atomic/IO/Log.h>
  27. #include <Atomic/IO/FileSystem.h>
  28. #include "JSAPI.h"
  29. #include "JSEvents.h"
  30. //#define JSVM_DEBUG
  31. namespace Atomic
  32. {
  33. class JSFile;
  34. class JSUI;
  35. class JSMetrics;
  36. class JSVM;
  37. /// Registration signature for JSVM package registration
  38. typedef void(*JSVMPackageRegistrationFunction)(JSVM* vm);
  39. /// Registration signature for JSVM package registration with settings
  40. typedef void(*JSVMPackageRegistrationSettingsFunction)(JSVM* vm, const VariantMap& setting);
  41. class JSVM : public Object
  42. {
  43. friend class JSMetrics;
  44. ATOMIC_OBJECT(JSVM, Object)
  45. public:
  46. /// Construct.
  47. JSVM(Context* context);
  48. /// Destruct.
  49. virtual ~JSVM();
  50. void InitJSContext();
  51. /// Package registration
  52. static void RegisterPackage(JSVMPackageRegistrationFunction regFunction);
  53. static void RegisterPackage(JSVMPackageRegistrationSettingsFunction regFunction, const VariantMap& settings);
  54. /// Initialize registered packages
  55. void InitializePackages();
  56. bool ExecuteFile(File* file);
  57. // Resources/Scripts/*.js
  58. bool ExecuteScript(const String& scriptPath);
  59. // Resources/Script/main.js
  60. bool ExecuteMain();
  61. bool ExecuteFunction(const String& functionName);
  62. inline static JSVM* GetJSVM(duk_context* context)
  63. {
  64. return instance_;
  65. }
  66. inline duk_context* GetJSContext() { return ctx_; }
  67. void GC();
  68. JSMetrics* GetMetrics() { return metrics_; }
  69. void DumpJavascriptObjects();
  70. #ifdef JSVM_DEBUG
  71. inline void ValidateJSHeapPtr(void* heapptr)
  72. {
  73. assert(removedHeapPtr_.Find(heapptr) == removedHeapPtr_.End());
  74. assert(heapToObject_.Find(heapptr) != heapToObject_.End());
  75. }
  76. #endif
  77. // Returns if the given object is stashed
  78. bool GetStashed(RefCounted* refcounted) const;
  79. inline void AddObject(void* heapptr, RefCounted* object, InstantiationType instantiationType)
  80. {
  81. assert(!object->JSGetHeapPtr());
  82. object->JSSetHeapPtr(heapptr);
  83. object->SetInstantiationType(instantiationType);
  84. #ifdef JSVM_DEBUG
  85. assert(heapToObject_.Find(heapptr) == heapToObject_.End());
  86. #endif
  87. heapToObject_[heapptr] = object;
  88. #ifdef JSVM_DEBUG
  89. HashMap<void*, void*>::Iterator itr = removedHeapPtr_.Find(heapptr);
  90. if (itr != removedHeapPtr_.End())
  91. removedHeapPtr_.Erase(itr);
  92. #endif
  93. if (instantiationType != INSTANTIATION_JAVASCRIPT)
  94. {
  95. if (!object->Refs())
  96. {
  97. ATOMIC_LOGWARNING("JSVM::AddObject, native or C# instantiated object added with 0 refs");
  98. }
  99. else
  100. {
  101. // stash
  102. Stash(object);
  103. }
  104. }
  105. else
  106. {
  107. if (object->Refs() != 0)
  108. {
  109. // we already have a native reference, so need to stash
  110. Stash(object);
  111. }
  112. }
  113. object->AddRefSilent();
  114. if (object->IsObject())
  115. {
  116. objectAddedData_[ObjectAdded::P_OBJECT] = object;
  117. SendEvent(E_JSOBJECTADDED, objectAddedData_);
  118. }
  119. }
  120. inline void RemoveObject(RefCounted* object)
  121. {
  122. if (object->IsObject())
  123. {
  124. objectRemovedData_[ObjectRemoved::P_OBJECT] = object;
  125. SendEvent(E_JSOBJECTREMOVED, objectRemovedData_);
  126. }
  127. void* heapptr = object->JSGetHeapPtr();
  128. assert(heapptr);
  129. object->JSSetHeapPtr(NULL);
  130. HashMap<void*, RefCounted*>::Iterator hitr = heapToObject_.Find(heapptr);
  131. assert(hitr != heapToObject_.End());
  132. heapToObject_.Erase(hitr);
  133. #ifdef JSVM_DEBUG
  134. assert(removedHeapPtr_.Find(heapptr) == removedHeapPtr_.End());
  135. removedHeapPtr_[heapptr] = heapptr;
  136. #endif
  137. }
  138. void Stash(RefCounted* refCounted);
  139. inline RefCounted* GetObjectPtr(void* heapptr, bool allowNull = false)
  140. {
  141. #ifdef JSVM_DEBUG
  142. assert(!removedHeapPtr_.Contains(heapptr));
  143. #endif
  144. if (allowNull && !heapToObject_.Contains(heapptr))
  145. {
  146. return NULL;
  147. }
  148. assert(heapToObject_.Contains(heapptr));
  149. #ifdef JSVM_DEBUG
  150. RefCounted* ref = heapToObject_[heapptr];
  151. assert(ref->JSGetHeapPtr() == heapptr);
  152. #endif
  153. return heapToObject_[heapptr];
  154. }
  155. void SetModuleSearchPaths(const String& searchPath)
  156. {
  157. moduleSearchPath_ = searchPath.Split(';');
  158. for (unsigned i = 0; i < moduleSearchPath_.Size(); i++)
  159. {
  160. moduleSearchPath_[i] = AddTrailingSlash(moduleSearchPath_[i]);
  161. }
  162. }
  163. const Vector<String>& GetModuleSearchPaths()
  164. {
  165. return moduleSearchPath_;
  166. }
  167. void SetLastModuleSearchFile(const String& fileName) { lastModuleSearchFilename_ = fileName; }
  168. const String& GetLastModuleSearchFile() { return lastModuleSearchFilename_; }
  169. const String& GetErrorString() { return errorString_; }
  170. void SendJSErrorEvent(const String& filename = String::EMPTY);
  171. int GetRealLineNumber(const String& fileName, const int lineNumber);
  172. unsigned GetStashCount() const { return stashCount_; }
  173. unsigned GetTotalStashCount() const { return totalStashCount_; }
  174. unsigned GetTotalUnstashCount() const { return totalUnstashCount_; }
  175. private:
  176. void Unstash(RefCounted* refCounted);
  177. struct JSAPIPackageRegistration
  178. {
  179. JSAPIPackageRegistration()
  180. {
  181. registrationFunction = 0;
  182. registrationSettingsFunction = 0;
  183. }
  184. JSAPIPackageRegistration(JSVMPackageRegistrationFunction regFunction)
  185. {
  186. registrationFunction = regFunction;
  187. registrationSettingsFunction = 0;
  188. }
  189. JSAPIPackageRegistration(JSVMPackageRegistrationSettingsFunction regFunction, const VariantMap& regSettings)
  190. {
  191. registrationFunction = 0;
  192. registrationSettingsFunction = regFunction;
  193. settings = regSettings;
  194. }
  195. JSVMPackageRegistrationFunction registrationFunction;
  196. JSVMPackageRegistrationSettingsFunction registrationSettingsFunction;
  197. VariantMap settings;
  198. };
  199. static void OnRefCountChanged(RefCounted* refCounted, int refCount);
  200. void SubscribeToEvents();
  201. void HandleUpdate(StringHash eventType, VariantMap& eventData);
  202. duk_context* ctx_;
  203. HashMap<void*, RefCounted*> heapToObject_;
  204. #ifdef JSVM_DEBUG
  205. // Debugging
  206. HashMap<void*, void*> removedHeapPtr_;
  207. #endif
  208. float gcTime_;
  209. Vector<String> moduleSearchPath_;
  210. String lastModuleSearchFilename_;
  211. String errorString_;
  212. SharedPtr<JSUI> ui_;
  213. VariantMap objectAddedData_;
  214. VariantMap objectRemovedData_;
  215. SharedPtr<JSMetrics> metrics_;
  216. static Vector<JSAPIPackageRegistration*> packageRegistrations_;
  217. unsigned stashCount_;
  218. unsigned totalStashCount_;
  219. unsigned totalUnstashCount_;
  220. static JSVM* instance_;
  221. };
  222. template<typename T>
  223. T* js_to_class_instance(duk_context* ctx, int index, unsigned classID)
  224. {
  225. if (!duk_is_object(ctx, index))
  226. return NULL;
  227. return (T*) JSVM::GetJSVM(ctx)->GetObjectPtr(duk_get_heapptr(ctx, index));
  228. }
  229. // pushes null if instance is null
  230. // pushes from object store if already wrapped
  231. // pushes a new'd instance with wrapped native
  232. // must be an Object (so downcast works)
  233. inline bool js_push_class_object_instance(duk_context* ctx, const RefCounted *instance, const char* classname = "")
  234. {
  235. if (!instance)
  236. {
  237. duk_push_null(ctx);
  238. return true;
  239. }
  240. int top = duk_get_top(ctx);
  241. if (instance->JSGetHeapPtr())
  242. {
  243. duk_push_heapptr(ctx, instance->JSGetHeapPtr());
  244. assert(duk_is_object(ctx, -1));
  245. return true;
  246. }
  247. duk_push_heap_stash(ctx);
  248. duk_push_pointer(ctx, (void*) instance->GetClassID());
  249. duk_get_prop(ctx, -2);
  250. // if not an object, this instance isn't not a scriptable class
  251. // reset top and return false
  252. if (!duk_is_object(ctx, -1))
  253. {
  254. if (instance->IsObject())
  255. {
  256. ATOMIC_LOGERRORF("Unable to push class object instance due to missing ClassID: %s", ((Object*)instance)->GetTypeName().CString());
  257. }
  258. else
  259. {
  260. ATOMIC_LOGERROR("Unable to push RefCounted instance due to missing ClassID");
  261. }
  262. duk_set_top(ctx, top);
  263. return false;
  264. }
  265. duk_get_prop_index(ctx, -1, 0);
  266. const char* package = duk_require_string(ctx, -1);
  267. duk_get_prop_index(ctx, -2, 1);
  268. const char* jclassname = duk_require_string(ctx, -1);
  269. duk_set_top(ctx, top);
  270. duk_get_global_string(ctx, package);
  271. duk_get_prop_string(ctx, -1, jclassname);
  272. assert(duk_is_function(ctx, -1));
  273. duk_push_pointer(ctx, (void*) instance);
  274. duk_new(ctx, 1);
  275. duk_remove(ctx, -2); // remove Atomic object
  276. assert(duk_is_object(ctx, -1));
  277. assert ((top + 1) == duk_get_top(ctx));
  278. return true;
  279. }
  280. }