as_scriptobject.cpp 32 KB

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