as_scriptobject.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2018 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. #include <new>
  24. #include "as_config.h"
  25. #include "as_scriptengine.h"
  26. #include "as_scriptobject.h"
  27. #include "as_texts.h"
  28. BEGIN_AS_NAMESPACE
  29. // This helper function will call the default factory, that is a script function
  30. asIScriptObject *ScriptObjectFactory(const asCObjectType *objType, asCScriptEngine *engine)
  31. {
  32. asIScriptContext *ctx = 0;
  33. int r = 0;
  34. bool isNested = false;
  35. // Use nested call in the context if there is an active context
  36. ctx = asGetActiveContext();
  37. if( ctx )
  38. {
  39. // It may not always be possible to reuse the current context,
  40. // in which case we'll have to create a new one any way.
  41. if( ctx->GetEngine() == objType->GetEngine() && ctx->PushState() == asSUCCESS )
  42. isNested = true;
  43. else
  44. ctx = 0;
  45. }
  46. if( ctx == 0 )
  47. {
  48. // Request a context from the engine
  49. ctx = engine->RequestContext();
  50. if( ctx == 0 )
  51. {
  52. // TODO: How to best report this failure?
  53. return 0;
  54. }
  55. }
  56. r = ctx->Prepare(engine->scriptFunctions[objType->beh.factory]);
  57. if( r < 0 )
  58. {
  59. if( isNested )
  60. ctx->PopState();
  61. else
  62. engine->ReturnContext(ctx);
  63. return 0;
  64. }
  65. for(;;)
  66. {
  67. r = ctx->Execute();
  68. // We can't allow this execution to be suspended
  69. // so resume the execution immediately
  70. if( r != asEXECUTION_SUSPENDED )
  71. break;
  72. }
  73. if( r != asEXECUTION_FINISHED )
  74. {
  75. if( isNested )
  76. {
  77. ctx->PopState();
  78. // If the execution was aborted or an exception occurred,
  79. // then we should forward that to the outer execution.
  80. if( r == asEXECUTION_EXCEPTION )
  81. {
  82. // TODO: How to improve this exception
  83. ctx->SetException(TXT_EXCEPTION_IN_NESTED_CALL);
  84. }
  85. else if( r == asEXECUTION_ABORTED )
  86. ctx->Abort();
  87. }
  88. else
  89. engine->ReturnContext(ctx);
  90. return 0;
  91. }
  92. asIScriptObject *ptr = (asIScriptObject*)ctx->GetReturnAddress();
  93. // Increase the reference, because the context will release its pointer
  94. ptr->AddRef();
  95. if( isNested )
  96. ctx->PopState();
  97. else
  98. engine->ReturnContext(ctx);
  99. return ptr;
  100. }
  101. // This helper function will call the copy factory, that is a script function
  102. // TODO: Clean up: This function is almost identical to ScriptObjectFactory. Should make better use of the identical code.
  103. asIScriptObject *ScriptObjectCopyFactory(const asCObjectType *objType, void *origObj, asCScriptEngine *engine)
  104. {
  105. asIScriptContext *ctx = 0;
  106. int r = 0;
  107. bool isNested = false;
  108. // Use nested call in the context if there is an active context
  109. ctx = asGetActiveContext();
  110. if (ctx)
  111. {
  112. // It may not always be possible to reuse the current context,
  113. // in which case we'll have to create a new one any way.
  114. if (ctx->GetEngine() == objType->GetEngine() && ctx->PushState() == asSUCCESS)
  115. isNested = true;
  116. else
  117. ctx = 0;
  118. }
  119. if (ctx == 0)
  120. {
  121. // Request a context from the engine
  122. ctx = engine->RequestContext();
  123. if (ctx == 0)
  124. {
  125. // TODO: How to best report this failure?
  126. return 0;
  127. }
  128. }
  129. r = ctx->Prepare(engine->scriptFunctions[objType->beh.copyfactory]);
  130. if (r < 0)
  131. {
  132. if (isNested)
  133. ctx->PopState();
  134. else
  135. engine->ReturnContext(ctx);
  136. return 0;
  137. }
  138. ctx->SetArgAddress(0, origObj);
  139. for (;;)
  140. {
  141. r = ctx->Execute();
  142. // We can't allow this execution to be suspended
  143. // so resume the execution immediately
  144. if (r != asEXECUTION_SUSPENDED)
  145. break;
  146. }
  147. if (r != asEXECUTION_FINISHED)
  148. {
  149. if (isNested)
  150. {
  151. ctx->PopState();
  152. // If the execution was aborted or an exception occurred,
  153. // then we should forward that to the outer execution.
  154. if (r == asEXECUTION_EXCEPTION)
  155. {
  156. // TODO: How to improve this exception
  157. ctx->SetException(TXT_EXCEPTION_IN_NESTED_CALL);
  158. }
  159. else if (r == asEXECUTION_ABORTED)
  160. ctx->Abort();
  161. }
  162. else
  163. engine->ReturnContext(ctx);
  164. return 0;
  165. }
  166. asIScriptObject *ptr = (asIScriptObject*)ctx->GetReturnAddress();
  167. // Increase the reference, because the context will release its pointer
  168. ptr->AddRef();
  169. if (isNested)
  170. ctx->PopState();
  171. else
  172. engine->ReturnContext(ctx);
  173. return ptr;
  174. }
  175. #ifdef AS_MAX_PORTABILITY
  176. static void ScriptObject_AddRef_Generic(asIScriptGeneric *gen)
  177. {
  178. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  179. self->AddRef();
  180. }
  181. static void ScriptObject_Release_Generic(asIScriptGeneric *gen)
  182. {
  183. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  184. self->Release();
  185. }
  186. static void ScriptObject_GetRefCount_Generic(asIScriptGeneric *gen)
  187. {
  188. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  189. *(int*)gen->GetAddressOfReturnLocation() = self->GetRefCount();
  190. }
  191. static void ScriptObject_SetFlag_Generic(asIScriptGeneric *gen)
  192. {
  193. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  194. self->SetFlag();
  195. }
  196. static void ScriptObject_GetFlag_Generic(asIScriptGeneric *gen)
  197. {
  198. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  199. *(bool*)gen->GetAddressOfReturnLocation() = self->GetFlag();
  200. }
  201. static void ScriptObject_GetWeakRefFlag_Generic(asIScriptGeneric *gen)
  202. {
  203. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  204. *(asILockableSharedBool**)gen->GetAddressOfReturnLocation() = self->GetWeakRefFlag();
  205. }
  206. static void ScriptObject_EnumReferences_Generic(asIScriptGeneric *gen)
  207. {
  208. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  209. asIScriptEngine *engine = *(asIScriptEngine**)gen->GetAddressOfArg(0);
  210. self->EnumReferences(engine);
  211. }
  212. static void ScriptObject_ReleaseAllHandles_Generic(asIScriptGeneric *gen)
  213. {
  214. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  215. asIScriptEngine *engine = *(asIScriptEngine**)gen->GetAddressOfArg(0);
  216. self->ReleaseAllHandles(engine);
  217. }
  218. static void ScriptObject_Assignment_Generic(asIScriptGeneric *gen)
  219. {
  220. asCScriptObject *other = *(asCScriptObject**)gen->GetAddressOfArg(0);
  221. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  222. *self = *other;
  223. *(asCScriptObject**)gen->GetAddressOfReturnLocation() = self;
  224. }
  225. static void ScriptObject_Construct_Generic(asIScriptGeneric *gen)
  226. {
  227. asCObjectType *objType = *(asCObjectType**)gen->GetAddressOfArg(0);
  228. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  229. ScriptObject_Construct(objType, self);
  230. }
  231. #endif
  232. void RegisterScriptObject(asCScriptEngine *engine)
  233. {
  234. // Register the default script class behaviours
  235. int r = 0;
  236. UNUSED_VAR(r); // It is only used in debug mode
  237. engine->scriptTypeBehaviours.engine = engine;
  238. engine->scriptTypeBehaviours.flags = asOBJ_SCRIPT_OBJECT | asOBJ_REF | asOBJ_GC;
  239. engine->scriptTypeBehaviours.name = "$obj";
  240. #ifndef AS_MAX_PORTABILITY
  241. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_CONSTRUCT, "void f(int&in)", asFUNCTION(ScriptObject_Construct), asCALL_CDECL_OBJLAST, 0); asASSERT( r >= 0 );
  242. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_ADDREF, "void f()", asMETHOD(asCScriptObject,AddRef), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  243. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_RELEASE, "void f()", asMETHOD(asCScriptObject,Release), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  244. r = engine->RegisterMethodToObjectType(&engine->scriptTypeBehaviours, "int &opAssign(int &in)", asFUNCTION(ScriptObject_Assignment), asCALL_CDECL_OBJLAST); asASSERT( r >= 0 );
  245. // Weakref behaviours
  246. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_GET_WEAKREF_FLAG, "int &f()", asMETHOD(asCScriptObject,GetWeakRefFlag), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  247. // Register GC behaviours
  248. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_GETREFCOUNT, "int f()", asMETHOD(asCScriptObject,GetRefCount), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  249. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_SETGCFLAG, "void f()", asMETHOD(asCScriptObject,SetFlag), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  250. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_GETGCFLAG, "bool f()", asMETHOD(asCScriptObject,GetFlag), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  251. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_ENUMREFS, "void f(int&in)", asMETHOD(asCScriptObject,EnumReferences), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  252. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_RELEASEREFS, "void f(int&in)", asMETHOD(asCScriptObject,ReleaseAllHandles), asCALL_THISCALL, 0); asASSERT( r >= 0 );
  253. #else
  254. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_CONSTRUCT, "void f(int&in)", asFUNCTION(ScriptObject_Construct_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  255. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_ADDREF, "void f()", asFUNCTION(ScriptObject_AddRef_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  256. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_RELEASE, "void f()", asFUNCTION(ScriptObject_Release_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  257. r = engine->RegisterMethodToObjectType(&engine->scriptTypeBehaviours, "int &opAssign(int &in)", asFUNCTION(ScriptObject_Assignment_Generic), asCALL_GENERIC); asASSERT( r >= 0 );
  258. // Weakref behaviours
  259. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_GET_WEAKREF_FLAG, "int &f()", asFUNCTION(ScriptObject_GetWeakRefFlag_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  260. // Register GC behaviours
  261. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_GETREFCOUNT, "int f()", asFUNCTION(ScriptObject_GetRefCount_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  262. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_SETGCFLAG, "void f()", asFUNCTION(ScriptObject_SetFlag_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  263. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_GETGCFLAG, "bool f()", asFUNCTION(ScriptObject_GetFlag_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  264. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_ENUMREFS, "void f(int&in)", asFUNCTION(ScriptObject_EnumReferences_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  265. r = engine->RegisterBehaviourToObjectType(&engine->scriptTypeBehaviours, asBEHAVE_RELEASEREFS, "void f(int&in)", asFUNCTION(ScriptObject_ReleaseAllHandles_Generic), asCALL_GENERIC, 0); asASSERT( r >= 0 );
  266. #endif
  267. }
  268. void ScriptObject_Construct(asCObjectType *objType, asCScriptObject *self)
  269. {
  270. new(self) asCScriptObject(objType);
  271. }
  272. void ScriptObject_ConstructUnitialized(asCObjectType *objType, asCScriptObject *self)
  273. {
  274. new(self) asCScriptObject(objType, false);
  275. }
  276. asCScriptObject::asCScriptObject(asCObjectType *ot, bool doInitialize)
  277. {
  278. refCount.set(1);
  279. objType = ot;
  280. objType->AddRef();
  281. isDestructCalled = false;
  282. extra = 0;
  283. hasRefCountReachedZero = false;
  284. // Notify the garbage collector of this object
  285. if( objType->flags & asOBJ_GC )
  286. objType->engine->gc.AddScriptObjectToGC(this, objType);
  287. // Initialize members to zero. Technically we only need to zero the pointer
  288. // members, but just the memset is faster than having to loop and check the datatypes
  289. memset((void*)(this+1), 0, objType->size - sizeof(asCScriptObject));
  290. if( doInitialize )
  291. {
  292. #ifdef AS_NO_MEMBER_INIT
  293. // When member initialization is disabled the constructor must make sure
  294. // to allocate and initialize all members with the default constructor
  295. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  296. {
  297. asCObjectProperty *prop = objType->properties[n];
  298. if( prop->type.IsObject() && !prop->type.IsObjectHandle() )
  299. {
  300. if( prop->type.IsReference() || prop->type.GetTypeInfo()->flags & asOBJ_REF )
  301. {
  302. asPWORD *ptr = reinterpret_cast<asPWORD*>(reinterpret_cast<asBYTE*>(this) + prop->byteOffset);
  303. if( prop->type.GetTypeInfo()->flags & asOBJ_SCRIPT_OBJECT )
  304. *ptr = (asPWORD)ScriptObjectFactory(prop->type.GetTypeInfo(), ot->engine);
  305. else
  306. *ptr = (asPWORD)AllocateUninitializedObject(prop->type.GetTypeInfo(), ot->engine);
  307. }
  308. }
  309. }
  310. #endif
  311. }
  312. else
  313. {
  314. // When the object is created without initialization, all non-handle members must be allocated, but not initialized
  315. asCScriptEngine *engine = objType->engine;
  316. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  317. {
  318. asCObjectProperty *prop = objType->properties[n];
  319. if( prop->type.IsObject() && !prop->type.IsObjectHandle() )
  320. {
  321. if( prop->type.IsReference() || (prop->type.GetTypeInfo()->flags & asOBJ_REF) )
  322. {
  323. asPWORD *ptr = reinterpret_cast<asPWORD*>(reinterpret_cast<asBYTE*>(this) + prop->byteOffset);
  324. *ptr = (asPWORD)AllocateUninitializedObject(CastToObjectType(prop->type.GetTypeInfo()), engine);
  325. }
  326. }
  327. }
  328. }
  329. }
  330. void asCScriptObject::Destruct()
  331. {
  332. // Call the destructor, which will also call the GCObject's destructor
  333. this->~asCScriptObject();
  334. // Free the memory
  335. #ifndef WIP_16BYTE_ALIGN
  336. userFree(this);
  337. #else
  338. // Script object memory is allocated through asCScriptEngine::CallAlloc()
  339. // This free call must match the allocator used in CallAlloc().
  340. userFreeAligned(this);
  341. #endif
  342. }
  343. asCScriptObject::~asCScriptObject()
  344. {
  345. if( extra )
  346. {
  347. if( extra->weakRefFlag )
  348. {
  349. extra->weakRefFlag->Release();
  350. extra->weakRefFlag = 0;
  351. }
  352. if( objType->engine )
  353. {
  354. // Clean the user data
  355. for( asUINT n = 0; n < extra->userData.GetLength(); n += 2 )
  356. {
  357. if( extra->userData[n+1] )
  358. {
  359. for( asUINT c = 0; c < objType->engine->cleanScriptObjectFuncs.GetLength(); c++ )
  360. if( objType->engine->cleanScriptObjectFuncs[c].type == extra->userData[n] )
  361. objType->engine->cleanScriptObjectFuncs[c].cleanFunc(this);
  362. }
  363. }
  364. }
  365. asDELETE(extra, SExtra);
  366. }
  367. // The engine pointer should be available from the objectType
  368. asCScriptEngine *engine = objType->engine;
  369. // Destroy all properties
  370. // In most cases the members are initialized in the order they have been declared,
  371. // so it's safer to uninitialize them from last to first. The order may be different
  372. // depending on the use of inheritance and or initialization in the declaration.
  373. // TODO: Should the order of initialization be stored by the compiler so that the
  374. // reverse order can be guaranteed during the destruction?
  375. for( int n = (int)objType->properties.GetLength()-1; n >= 0; n-- )
  376. {
  377. asCObjectProperty *prop = objType->properties[n];
  378. if( prop->type.IsObject() )
  379. {
  380. // Destroy the object
  381. asCObjectType *propType = CastToObjectType(prop->type.GetTypeInfo());
  382. if( prop->type.IsReference() || propType->flags & asOBJ_REF )
  383. {
  384. void **ptr = (void**)(((char*)this) + prop->byteOffset);
  385. if( *ptr )
  386. {
  387. FreeObject(*ptr, propType, engine);
  388. *(asDWORD*)ptr = 0;
  389. }
  390. }
  391. else
  392. {
  393. // The object is allocated inline. As only POD objects may be allocated inline
  394. // it is not a problem to call the destructor even if the object may never have
  395. // been initialized, e.g. if an exception interrupted the constructor.
  396. asASSERT( propType->flags & asOBJ_POD );
  397. void *ptr = (void**)(((char*)this) + prop->byteOffset);
  398. if( propType->beh.destruct )
  399. engine->CallObjectMethod(ptr, propType->beh.destruct);
  400. }
  401. }
  402. else if( prop->type.IsFuncdef() )
  403. {
  404. // Release the function descriptor
  405. asCScriptFunction **ptr = (asCScriptFunction**)(((char*)this) + prop->byteOffset);
  406. if (*ptr)
  407. {
  408. (*ptr)->Release();
  409. *ptr = 0;
  410. }
  411. }
  412. }
  413. objType->Release();
  414. objType = 0;
  415. // Something is really wrong if the refCount is not 0 by now
  416. asASSERT( refCount.get() == 0 );
  417. }
  418. asILockableSharedBool *asCScriptObject::GetWeakRefFlag() const
  419. {
  420. // If the object's refCount has already reached zero then the object is already
  421. // about to be destroyed so it's ok to return null if the weakRefFlag doesn't already
  422. // exist
  423. if( (extra && extra->weakRefFlag) || hasRefCountReachedZero )
  424. return extra->weakRefFlag;
  425. // Lock globally so no other thread can attempt
  426. // to create a shared bool at the same time.
  427. // TODO: runtime optimize: Instead of locking globally, it would be possible to have
  428. // a critical section per object type. This would reduce the
  429. // chances of two threads lock on the same critical section.
  430. asAcquireExclusiveLock();
  431. // Make sure another thread didn't create the
  432. // flag while we waited for the lock
  433. if( !extra )
  434. extra = asNEW(SExtra);
  435. if( !extra->weakRefFlag )
  436. extra->weakRefFlag = asNEW(asCLockableSharedBool);
  437. asReleaseExclusiveLock();
  438. return extra->weakRefFlag;
  439. }
  440. void *asCScriptObject::GetUserData(asPWORD type) const
  441. {
  442. if( !extra )
  443. return 0;
  444. // There may be multiple threads reading, but when
  445. // setting the user data nobody must be reading.
  446. // TODO: runtime optimize: Would it be worth it to have a rwlock per object type?
  447. asAcquireSharedLock();
  448. for( asUINT n = 0; n < extra->userData.GetLength(); n += 2 )
  449. {
  450. if( extra->userData[n] == type )
  451. {
  452. void *userData = reinterpret_cast<void*>(extra->userData[n+1]);
  453. asReleaseSharedLock();
  454. return userData;
  455. }
  456. }
  457. asReleaseSharedLock();
  458. return 0;
  459. }
  460. void *asCScriptObject::SetUserData(void *data, asPWORD type)
  461. {
  462. // Lock globally so no other thread can attempt
  463. // to manipulate the extra data at the same time.
  464. // TODO: runtime optimize: Instead of locking globally, it would be possible to have
  465. // a critical section per object type. This would reduce the
  466. // chances of two threads lock on the same critical section.
  467. asAcquireExclusiveLock();
  468. // Make sure another thread didn't create the
  469. // flag while we waited for the lock
  470. if( !extra )
  471. extra = asNEW(SExtra);
  472. // It is not intended to store a lot of different types of userdata,
  473. // so a more complex structure like a associative map would just have
  474. // more overhead than a simple array.
  475. for( asUINT n = 0; n < extra->userData.GetLength(); n += 2 )
  476. {
  477. if( extra->userData[n] == type )
  478. {
  479. void *oldData = reinterpret_cast<void*>(extra->userData[n+1]);
  480. extra->userData[n+1] = reinterpret_cast<asPWORD>(data);
  481. asReleaseExclusiveLock();
  482. return oldData;
  483. }
  484. }
  485. extra->userData.PushLast(type);
  486. extra->userData.PushLast(reinterpret_cast<asPWORD>(data));
  487. asReleaseExclusiveLock();
  488. return 0;
  489. }
  490. asIScriptEngine *asCScriptObject::GetEngine() const
  491. {
  492. return objType->engine;
  493. }
  494. int asCScriptObject::AddRef() const
  495. {
  496. // Warn in case the application tries to increase the refCount after it has reached zero.
  497. // This may happen for example if the application calls a method on the class while it is
  498. // being destroyed. The application shouldn't do this because it may cause application
  499. // crashes if members that have already been destroyed are accessed accidentally.
  500. if( hasRefCountReachedZero )
  501. {
  502. if( objType && objType->engine )
  503. {
  504. asCString msg;
  505. msg.Format(TXT_RESURRECTING_SCRIPTOBJECT_s, objType->name.AddressOf());
  506. objType->engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  507. }
  508. }
  509. // Increase counter and clear flag set by GC
  510. gcFlag = false;
  511. return refCount.atomicInc();
  512. }
  513. int asCScriptObject::Release() const
  514. {
  515. // Clear the flag set by the GC
  516. gcFlag = false;
  517. // If the weak ref flag exists it is because someone held a weak ref
  518. // and that someone may add a reference to the object at any time. It
  519. // is ok to check the existance of the weakRefFlag without locking here
  520. // because if the refCount is 1 then no other thread is currently
  521. // creating the weakRefFlag.
  522. if( refCount.get() == 1 && extra && extra->weakRefFlag )
  523. {
  524. // Set the flag to tell others that the object is no longer alive
  525. // We must do this before decreasing the refCount to 0 so we don't
  526. // end up with a race condition between this thread attempting to
  527. // destroy the object and the other that temporary added a strong
  528. // ref from the weak ref.
  529. extra->weakRefFlag->Set(true);
  530. }
  531. // Call the script destructor behaviour if the reference counter is 1.
  532. if( refCount.get() == 1 && !isDestructCalled )
  533. {
  534. // This cast is OK since we are the last reference
  535. const_cast<asCScriptObject*>(this)->CallDestructor();
  536. }
  537. // Now do the actual releasing
  538. int r = refCount.atomicDec();
  539. if( r == 0 )
  540. {
  541. // Flag this object as being destroyed so the application
  542. // can be warned if the code attempts to resurrect the object
  543. // during the destructor. This also avoids a recursive call
  544. // to the destructor which would crash the application if it
  545. // really does resurrect the object.
  546. if( !hasRefCountReachedZero )
  547. {
  548. hasRefCountReachedZero = true;
  549. // This cast is OK since we are the last reference
  550. const_cast<asCScriptObject*>(this)->Destruct();
  551. }
  552. return 0;
  553. }
  554. return r;
  555. }
  556. void asCScriptObject::CallDestructor()
  557. {
  558. // Only allow the destructor to be called once
  559. if( isDestructCalled ) return;
  560. asIScriptContext *ctx = 0;
  561. bool isNested = false;
  562. bool doAbort = false;
  563. // Make sure the destructor is called once only, even if the
  564. // reference count is increased and then decreased again
  565. isDestructCalled = true;
  566. // Call the destructor for this class and all the super classes
  567. asCObjectType *ot = objType;
  568. while( ot )
  569. {
  570. int funcIndex = ot->beh.destruct;
  571. if( funcIndex )
  572. {
  573. if( ctx == 0 )
  574. {
  575. // Check for active context first as it is quicker
  576. // to reuse than to set up a new one.
  577. ctx = asGetActiveContext();
  578. if( ctx )
  579. {
  580. if( ctx->GetEngine() == objType->GetEngine() && ctx->PushState() == asSUCCESS )
  581. isNested = true;
  582. else
  583. ctx = 0;
  584. }
  585. if( ctx == 0 )
  586. {
  587. // Request a context from the engine
  588. ctx = objType->engine->RequestContext();
  589. if( ctx == 0 )
  590. {
  591. // TODO: How to best report this failure?
  592. return;
  593. }
  594. }
  595. }
  596. int r = ctx->Prepare(objType->engine->scriptFunctions[funcIndex]);
  597. if( r >= 0 )
  598. {
  599. ctx->SetObject(this);
  600. for(;;)
  601. {
  602. r = ctx->Execute();
  603. // If the script tries to suspend itself just restart it
  604. if( r != asEXECUTION_SUSPENDED )
  605. break;
  606. }
  607. // Exceptions in the destructor will be ignored, as there is not much
  608. // that can be done about them. However a request to abort the execution
  609. // will be forwarded to the outer execution, in case of a nested call.
  610. if( r == asEXECUTION_ABORTED )
  611. doAbort = true;
  612. // Observe, even though the current destructor was aborted or an exception
  613. // occurred, we still try to execute the base class' destructor if available
  614. // in order to free as many resources as possible.
  615. }
  616. }
  617. ot = ot->derivedFrom;
  618. }
  619. if( ctx )
  620. {
  621. if( isNested )
  622. {
  623. ctx->PopState();
  624. // Forward any request to abort the execution to the outer call
  625. if( doAbort )
  626. ctx->Abort();
  627. }
  628. else
  629. {
  630. // Return the context to engine
  631. objType->engine->ReturnContext(ctx);
  632. }
  633. }
  634. }
  635. asITypeInfo *asCScriptObject::GetObjectType() const
  636. {
  637. return objType;
  638. }
  639. int asCScriptObject::GetRefCount()
  640. {
  641. return refCount.get();
  642. }
  643. void asCScriptObject::SetFlag()
  644. {
  645. gcFlag = true;
  646. }
  647. bool asCScriptObject::GetFlag()
  648. {
  649. return gcFlag;
  650. }
  651. // interface
  652. int asCScriptObject::GetTypeId() const
  653. {
  654. asCDataType dt = asCDataType::CreateType(objType, false);
  655. return objType->engine->GetTypeIdFromDataType(dt);
  656. }
  657. asUINT asCScriptObject::GetPropertyCount() const
  658. {
  659. return asUINT(objType->properties.GetLength());
  660. }
  661. int asCScriptObject::GetPropertyTypeId(asUINT prop) const
  662. {
  663. if( prop >= objType->properties.GetLength() )
  664. return asINVALID_ARG;
  665. return objType->engine->GetTypeIdFromDataType(objType->properties[prop]->type);
  666. }
  667. const char *asCScriptObject::GetPropertyName(asUINT prop) const
  668. {
  669. if( prop >= objType->properties.GetLength() )
  670. return 0;
  671. return objType->properties[prop]->name.AddressOf();
  672. }
  673. void *asCScriptObject::GetAddressOfProperty(asUINT prop)
  674. {
  675. if( prop >= objType->properties.GetLength() )
  676. return 0;
  677. // Objects are stored by reference, so this must be dereferenced
  678. asCDataType *dt = &objType->properties[prop]->type;
  679. if( dt->IsObject() && !dt->IsObjectHandle() &&
  680. (dt->IsReference() || dt->GetTypeInfo()->flags & asOBJ_REF) )
  681. return *(void**)(((char*)this) + objType->properties[prop]->byteOffset);
  682. return (void*)(((char*)this) + objType->properties[prop]->byteOffset);
  683. }
  684. void asCScriptObject::EnumReferences(asIScriptEngine *engine)
  685. {
  686. // We'll notify the GC of all object handles that we're holding
  687. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  688. {
  689. asCObjectProperty *prop = objType->properties[n];
  690. void *ptr = 0;
  691. if (prop->type.IsObject())
  692. {
  693. if (prop->type.IsReference() || (prop->type.GetTypeInfo()->flags & asOBJ_REF))
  694. ptr = *(void**)(((char*)this) + prop->byteOffset);
  695. else
  696. ptr = (void*)(((char*)this) + prop->byteOffset);
  697. // The members of the value type needs to be enumerated
  698. // too, since the value type may be holding a reference.
  699. if ((prop->type.GetTypeInfo()->flags & asOBJ_VALUE) && (prop->type.GetTypeInfo()->flags & asOBJ_GC))
  700. {
  701. reinterpret_cast<asCScriptEngine*>(engine)->CallObjectMethod(ptr, engine, CastToObjectType(prop->type.GetTypeInfo())->beh.gcEnumReferences);
  702. }
  703. }
  704. else if (prop->type.IsFuncdef())
  705. ptr = *(void**)(((char*)this) + prop->byteOffset);
  706. if (ptr)
  707. ((asCScriptEngine*)engine)->GCEnumCallback(ptr);
  708. }
  709. }
  710. void asCScriptObject::ReleaseAllHandles(asIScriptEngine *engine)
  711. {
  712. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  713. {
  714. asCObjectProperty *prop = objType->properties[n];
  715. if (prop->type.IsObject())
  716. {
  717. if (prop->type.IsObjectHandle())
  718. {
  719. void **ptr = (void**)(((char*)this) + prop->byteOffset);
  720. if (*ptr)
  721. {
  722. asASSERT((prop->type.GetTypeInfo()->flags & asOBJ_NOCOUNT) || prop->type.GetBehaviour()->release);
  723. if (prop->type.GetBehaviour()->release)
  724. ((asCScriptEngine*)engine)->CallObjectMethod(*ptr, prop->type.GetBehaviour()->release);
  725. *ptr = 0;
  726. }
  727. }
  728. else if ((prop->type.GetTypeInfo()->flags & asOBJ_VALUE) && (prop->type.GetTypeInfo()->flags & asOBJ_GC))
  729. {
  730. // The members of the members needs to be released
  731. // too, since they may be holding a reference. Even
  732. // if the member is a value type.
  733. void *ptr = 0;
  734. if (prop->type.IsReference())
  735. ptr = *(void**)(((char*)this) + prop->byteOffset);
  736. else
  737. ptr = (void*)(((char*)this) + prop->byteOffset);
  738. reinterpret_cast<asCScriptEngine*>(engine)->CallObjectMethod(ptr, engine, CastToObjectType(prop->type.GetTypeInfo())->beh.gcReleaseAllReferences);
  739. }
  740. }
  741. else if (prop->type.IsFuncdef())
  742. {
  743. asCScriptFunction **ptr = (asCScriptFunction**)(((char*)this) + prop->byteOffset);
  744. if (*ptr)
  745. {
  746. (*ptr)->Release();
  747. *ptr = 0;
  748. }
  749. }
  750. }
  751. }
  752. asCScriptObject &ScriptObject_Assignment(asCScriptObject *other, asCScriptObject *self)
  753. {
  754. return (*self = *other);
  755. }
  756. asCScriptObject &asCScriptObject::operator=(const asCScriptObject &other)
  757. {
  758. if( &other != this )
  759. {
  760. if( !other.objType->DerivesFrom(objType) )
  761. {
  762. // We cannot allow a value assignment from a type that isn't the same or
  763. // derives from this type as the member properties may not have the same layout
  764. asIScriptContext *ctx = asGetActiveContext();
  765. ctx->SetException(TXT_MISMATCH_IN_VALUE_ASSIGN);
  766. return *this;
  767. }
  768. // If the script class implements the opAssign method, it should be called
  769. asCScriptEngine *engine = objType->engine;
  770. asCScriptFunction *func = engine->scriptFunctions[objType->beh.copy];
  771. if( func->funcType == asFUNC_SYSTEM )
  772. {
  773. // Copy all properties
  774. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  775. {
  776. asCObjectProperty *prop = objType->properties[n];
  777. if( prop->type.IsObject() )
  778. {
  779. void **dst = (void**)(((char*)this) + prop->byteOffset);
  780. void **src = (void**)(((char*)&other) + prop->byteOffset);
  781. if( !prop->type.IsObjectHandle() )
  782. {
  783. if( prop->type.IsReference() || (prop->type.GetTypeInfo()->flags & asOBJ_REF) )
  784. CopyObject(*src, *dst, CastToObjectType(prop->type.GetTypeInfo()), engine);
  785. else
  786. CopyObject(src, dst, CastToObjectType(prop->type.GetTypeInfo()), engine);
  787. }
  788. else
  789. CopyHandle((asPWORD*)src, (asPWORD*)dst, CastToObjectType(prop->type.GetTypeInfo()), engine);
  790. }
  791. else if (prop->type.IsFuncdef())
  792. {
  793. asCScriptFunction **dst = (asCScriptFunction**)(((char*)this) + prop->byteOffset);
  794. asCScriptFunction **src = (asCScriptFunction**)(((char*)&other) + prop->byteOffset);
  795. if (*dst)
  796. (*dst)->Release();
  797. *dst = *src;
  798. if (*dst)
  799. (*dst)->AddRef();
  800. }
  801. else
  802. {
  803. void *dst = ((char*)this) + prop->byteOffset;
  804. void *src = ((char*)&other) + prop->byteOffset;
  805. memcpy(dst, src, prop->type.GetSizeInMemoryBytes());
  806. }
  807. }
  808. }
  809. else
  810. {
  811. // Reuse the active context or create a new one to call the script class' opAssign method
  812. asIScriptContext *ctx = 0;
  813. int r = 0;
  814. bool isNested = false;
  815. ctx = asGetActiveContext();
  816. if( ctx )
  817. {
  818. if( ctx->GetEngine() == engine && ctx->PushState() == asSUCCESS )
  819. isNested = true;
  820. else
  821. ctx = 0;
  822. }
  823. if( ctx == 0 )
  824. {
  825. // Request a context from the engine
  826. ctx = engine->RequestContext();
  827. if( ctx == 0 )
  828. {
  829. // TODO: How to best report this failure?
  830. return *this;
  831. }
  832. }
  833. r = ctx->Prepare(engine->scriptFunctions[objType->beh.copy]);
  834. if( r < 0 )
  835. {
  836. if( isNested )
  837. ctx->PopState();
  838. else
  839. engine->ReturnContext(ctx);
  840. // TODO: How to best report this failure?
  841. return *this;
  842. }
  843. r = ctx->SetArgAddress(0, const_cast<asCScriptObject*>(&other));
  844. asASSERT( r >= 0 );
  845. r = ctx->SetObject(this);
  846. asASSERT( r >= 0 );
  847. for(;;)
  848. {
  849. r = ctx->Execute();
  850. // We can't allow this execution to be suspended
  851. // so resume the execution immediately
  852. if( r != asEXECUTION_SUSPENDED )
  853. break;
  854. }
  855. if( r != asEXECUTION_FINISHED )
  856. {
  857. if( isNested )
  858. {
  859. ctx->PopState();
  860. // If the execution was aborted or an exception occurred,
  861. // then we should forward that to the outer execution.
  862. if( r == asEXECUTION_EXCEPTION )
  863. {
  864. // TODO: How to improve this exception
  865. ctx->SetException(TXT_EXCEPTION_IN_NESTED_CALL);
  866. }
  867. else if( r == asEXECUTION_ABORTED )
  868. ctx->Abort();
  869. }
  870. else
  871. {
  872. // Return the context to the engine
  873. engine->ReturnContext(ctx);
  874. }
  875. return *this;
  876. }
  877. if( isNested )
  878. ctx->PopState();
  879. else
  880. {
  881. // Return the context to the engine
  882. engine->ReturnContext(ctx);
  883. }
  884. }
  885. }
  886. return *this;
  887. }
  888. int asCScriptObject::CopyFrom(asIScriptObject *other)
  889. {
  890. if( other == 0 ) return asINVALID_ARG;
  891. if( GetTypeId() != other->GetTypeId() )
  892. return asINVALID_TYPE;
  893. *this = *(asCScriptObject*)other;
  894. return 0;
  895. }
  896. void *asCScriptObject::AllocateUninitializedObject(asCObjectType *in_objType, asCScriptEngine *engine)
  897. {
  898. void *ptr = 0;
  899. if( in_objType->flags & asOBJ_SCRIPT_OBJECT )
  900. {
  901. ptr = engine->CallAlloc(in_objType);
  902. ScriptObject_ConstructUnitialized(in_objType, reinterpret_cast<asCScriptObject*>(ptr));
  903. }
  904. else if( in_objType->flags & asOBJ_TEMPLATE )
  905. {
  906. // Templates store the original factory that takes the object
  907. // type as a hidden parameter in the construct behaviour
  908. ptr = engine->CallGlobalFunctionRetPtr(in_objType->beh.construct, in_objType);
  909. }
  910. else if( in_objType->flags & asOBJ_REF )
  911. {
  912. ptr = engine->CallGlobalFunctionRetPtr(in_objType->beh.factory);
  913. }
  914. else
  915. {
  916. ptr = engine->CallAlloc(in_objType);
  917. int funcIndex = in_objType->beh.construct;
  918. if( funcIndex )
  919. engine->CallObjectMethod(ptr, funcIndex);
  920. }
  921. return ptr;
  922. }
  923. void asCScriptObject::FreeObject(void *ptr, asCObjectType *in_objType, asCScriptEngine *engine)
  924. {
  925. if( in_objType->flags & asOBJ_REF )
  926. {
  927. asASSERT( (in_objType->flags & asOBJ_NOCOUNT) || in_objType->beh.release );
  928. if(in_objType->beh.release )
  929. engine->CallObjectMethod(ptr, in_objType->beh.release);
  930. }
  931. else
  932. {
  933. if( in_objType->beh.destruct )
  934. engine->CallObjectMethod(ptr, in_objType->beh.destruct);
  935. engine->CallFree(ptr);
  936. }
  937. }
  938. void asCScriptObject::CopyObject(void *src, void *dst, asCObjectType *in_objType, asCScriptEngine *engine)
  939. {
  940. int funcIndex = in_objType->beh.copy;
  941. if( funcIndex )
  942. {
  943. asCScriptFunction *func = engine->scriptFunctions[in_objType->beh.copy];
  944. if( func->funcType == asFUNC_SYSTEM )
  945. engine->CallObjectMethod(dst, src, funcIndex);
  946. else
  947. {
  948. // Call the script class' opAssign method
  949. asASSERT(in_objType->flags & asOBJ_SCRIPT_OBJECT );
  950. reinterpret_cast<asCScriptObject*>(dst)->CopyFrom(reinterpret_cast<asCScriptObject*>(src));
  951. }
  952. }
  953. else if( in_objType->size && (in_objType->flags & asOBJ_POD) )
  954. memcpy(dst, src, in_objType->size);
  955. }
  956. void asCScriptObject::CopyHandle(asPWORD *src, asPWORD *dst, asCObjectType *in_objType, asCScriptEngine *engine)
  957. {
  958. // asOBJ_NOCOUNT doesn't have addref or release behaviours
  959. asASSERT( (in_objType->flags & asOBJ_NOCOUNT) || (in_objType->beh.release && in_objType->beh.addref) );
  960. if( *dst && in_objType->beh.release )
  961. engine->CallObjectMethod(*(void**)dst, in_objType->beh.release);
  962. *dst = *src;
  963. if( *dst && in_objType->beh.addref )
  964. engine->CallObjectMethod(*(void**)dst, in_objType->beh.addref);
  965. }
  966. // TODO: weak: Should move to its own file
  967. asCLockableSharedBool::asCLockableSharedBool() : value(false)
  968. {
  969. refCount.set(1);
  970. }
  971. int asCLockableSharedBool::AddRef() const
  972. {
  973. return refCount.atomicInc();
  974. }
  975. int asCLockableSharedBool::Release() const
  976. {
  977. int r = refCount.atomicDec();
  978. if( r == 0 )
  979. asDELETE(const_cast<asCLockableSharedBool*>(this), asCLockableSharedBool);
  980. return r;
  981. }
  982. bool asCLockableSharedBool::Get() const
  983. {
  984. return value;
  985. }
  986. void asCLockableSharedBool::Set(bool v)
  987. {
  988. // Make sure the value is not changed while another thread
  989. // is inspecting it and taking a decision on what to do.
  990. Lock();
  991. value = v;
  992. Unlock();
  993. }
  994. void asCLockableSharedBool::Lock() const
  995. {
  996. ENTERCRITICALSECTION(lock);
  997. }
  998. void asCLockableSharedBool::Unlock() const
  999. {
  1000. LEAVECRITICALSECTION(lock);
  1001. }
  1002. // Interface
  1003. // Auxiliary function to allow applications to create shared
  1004. // booleans without having to implement the logic for them
  1005. AS_API asILockableSharedBool *asCreateLockableSharedBool()
  1006. {
  1007. return asNEW(asCLockableSharedBool);
  1008. }
  1009. END_AS_NAMESPACE