as_scriptobject.cpp 33 KB

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