as_scriptobject.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2015 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.GetObjectType()->flags & asOBJ_REF )
  227. {
  228. asPWORD *ptr = reinterpret_cast<asPWORD*>(reinterpret_cast<asBYTE*>(this) + prop->byteOffset);
  229. if( prop->type.GetObjectType()->flags & asOBJ_SCRIPT_OBJECT )
  230. *ptr = (asPWORD)ScriptObjectFactory(prop->type.GetObjectType(), ot->engine);
  231. else
  232. *ptr = (asPWORD)AllocateUninitializedObject(prop->type.GetObjectType(), 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.GetObjectType()->flags & asOBJ_REF) )
  248. {
  249. asPWORD *ptr = reinterpret_cast<asPWORD*>(reinterpret_cast<asBYTE*>(this) + prop->byteOffset);
  250. *ptr = (asPWORD)AllocateUninitializedObject(prop->type.GetObjectType(), 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 = prop->type.GetObjectType();
  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. }
  329. objType->Release();
  330. objType = 0;
  331. // Something is really wrong if the refCount is not 0 by now
  332. asASSERT( refCount.get() == 0 );
  333. }
  334. asILockableSharedBool *asCScriptObject::GetWeakRefFlag() const
  335. {
  336. // If the object's refCount has already reached zero then the object is already
  337. // about to be destroyed so it's ok to return null if the weakRefFlag doesn't already
  338. // exist
  339. if( (extra && extra->weakRefFlag) || hasRefCountReachedZero )
  340. return extra->weakRefFlag;
  341. // Lock globally so no other thread can attempt
  342. // to create a shared bool at the same time.
  343. // TODO: runtime optimize: Instead of locking globally, it would be possible to have
  344. // a critical section per object type. This would reduce the
  345. // chances of two threads lock on the same critical section.
  346. asAcquireExclusiveLock();
  347. // Make sure another thread didn't create the
  348. // flag while we waited for the lock
  349. if( !extra )
  350. extra = asNEW(SExtra);
  351. if( !extra->weakRefFlag )
  352. extra->weakRefFlag = asNEW(asCLockableSharedBool);
  353. asReleaseExclusiveLock();
  354. return extra->weakRefFlag;
  355. }
  356. void *asCScriptObject::GetUserData(asPWORD type) const
  357. {
  358. if( !extra )
  359. return 0;
  360. // There may be multiple threads reading, but when
  361. // setting the user data nobody must be reading.
  362. // TODO: runtime optimize: Would it be worth it to have a rwlock per object type?
  363. asAcquireSharedLock();
  364. for( asUINT n = 0; n < extra->userData.GetLength(); n += 2 )
  365. {
  366. if( extra->userData[n] == type )
  367. {
  368. void *userData = reinterpret_cast<void*>(extra->userData[n+1]);
  369. asReleaseSharedLock();
  370. return userData;
  371. }
  372. }
  373. asReleaseSharedLock();
  374. return 0;
  375. }
  376. void *asCScriptObject::SetUserData(void *data, asPWORD type)
  377. {
  378. // Lock globally so no other thread can attempt
  379. // to manipulate the extra data at the same time.
  380. // TODO: runtime optimize: Instead of locking globally, it would be possible to have
  381. // a critical section per object type. This would reduce the
  382. // chances of two threads lock on the same critical section.
  383. asAcquireExclusiveLock();
  384. // Make sure another thread didn't create the
  385. // flag while we waited for the lock
  386. if( !extra )
  387. extra = asNEW(SExtra);
  388. // It is not intended to store a lot of different types of userdata,
  389. // so a more complex structure like a associative map would just have
  390. // more overhead than a simple array.
  391. for( asUINT n = 0; n < extra->userData.GetLength(); n += 2 )
  392. {
  393. if( extra->userData[n] == type )
  394. {
  395. void *oldData = reinterpret_cast<void*>(extra->userData[n+1]);
  396. extra->userData[n+1] = reinterpret_cast<asPWORD>(data);
  397. asReleaseExclusiveLock();
  398. return oldData;
  399. }
  400. }
  401. extra->userData.PushLast(type);
  402. extra->userData.PushLast(reinterpret_cast<asPWORD>(data));
  403. asReleaseExclusiveLock();
  404. return 0;
  405. }
  406. asIScriptEngine *asCScriptObject::GetEngine() const
  407. {
  408. return objType->engine;
  409. }
  410. int asCScriptObject::AddRef() const
  411. {
  412. // Warn in case the application tries to increase the refCount after it has reached zero.
  413. // This may happen for example if the application calls a method on the class while it is
  414. // being destroyed. The application shouldn't do this because it may cause application
  415. // crashes if members that have already been destroyed are accessed accidentally.
  416. if( hasRefCountReachedZero )
  417. {
  418. if( objType && objType->engine )
  419. {
  420. asCString msg;
  421. msg.Format(TXT_RESURRECTING_SCRIPTOBJECT_s, objType->name.AddressOf());
  422. objType->engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  423. }
  424. }
  425. // Increase counter and clear flag set by GC
  426. gcFlag = false;
  427. return refCount.atomicInc();
  428. }
  429. int asCScriptObject::Release() const
  430. {
  431. // Clear the flag set by the GC
  432. gcFlag = false;
  433. // If the weak ref flag exists it is because someone held a weak ref
  434. // and that someone may add a reference to the object at any time. It
  435. // is ok to check the existance of the weakRefFlag without locking here
  436. // because if the refCount is 1 then no other thread is currently
  437. // creating the weakRefFlag.
  438. if( refCount.get() == 1 && extra && extra->weakRefFlag )
  439. {
  440. // Set the flag to tell others that the object is no longer alive
  441. // We must do this before decreasing the refCount to 0 so we don't
  442. // end up with a race condition between this thread attempting to
  443. // destroy the object and the other that temporary added a strong
  444. // ref from the weak ref.
  445. extra->weakRefFlag->Set(true);
  446. }
  447. // Call the script destructor behaviour if the reference counter is 1.
  448. if( refCount.get() == 1 && !isDestructCalled )
  449. {
  450. // This cast is OK since we are the last reference
  451. const_cast<asCScriptObject*>(this)->CallDestructor();
  452. }
  453. // Now do the actual releasing
  454. int r = refCount.atomicDec();
  455. if( r == 0 )
  456. {
  457. // Flag this object as being destroyed so the application
  458. // can be warned if the code attempts to resurrect the object
  459. // during the destructor. This also avoids a recursive call
  460. // to the destructor which would crash the application if it
  461. // really does resurrect the object.
  462. if( !hasRefCountReachedZero )
  463. {
  464. hasRefCountReachedZero = true;
  465. // This cast is OK since we are the last reference
  466. const_cast<asCScriptObject*>(this)->Destruct();
  467. }
  468. return 0;
  469. }
  470. return r;
  471. }
  472. void asCScriptObject::CallDestructor()
  473. {
  474. // Only allow the destructor to be called once
  475. if( isDestructCalled ) return;
  476. asIScriptContext *ctx = 0;
  477. bool isNested = false;
  478. bool doAbort = false;
  479. // Make sure the destructor is called once only, even if the
  480. // reference count is increased and then decreased again
  481. isDestructCalled = true;
  482. // Call the destructor for this class and all the super classes
  483. asCObjectType *ot = objType;
  484. while( ot )
  485. {
  486. int funcIndex = ot->beh.destruct;
  487. if( funcIndex )
  488. {
  489. if( ctx == 0 )
  490. {
  491. // Check for active context first as it is quicker
  492. // to reuse than to set up a new one.
  493. ctx = asGetActiveContext();
  494. if( ctx )
  495. {
  496. if( ctx->GetEngine() == objType->GetEngine() && ctx->PushState() == asSUCCESS )
  497. isNested = true;
  498. else
  499. ctx = 0;
  500. }
  501. if( ctx == 0 )
  502. {
  503. // Request a context from the engine
  504. ctx = objType->engine->RequestContext();
  505. if( ctx == 0 )
  506. {
  507. // TODO: How to best report this failure?
  508. return;
  509. }
  510. }
  511. }
  512. int r = ctx->Prepare(objType->engine->scriptFunctions[funcIndex]);
  513. if( r >= 0 )
  514. {
  515. ctx->SetObject(this);
  516. for(;;)
  517. {
  518. r = ctx->Execute();
  519. // If the script tries to suspend itself just restart it
  520. if( r != asEXECUTION_SUSPENDED )
  521. break;
  522. }
  523. // Exceptions in the destructor will be ignored, as there is not much
  524. // that can be done about them. However a request to abort the execution
  525. // will be forwarded to the outer execution, in case of a nested call.
  526. if( r == asEXECUTION_ABORTED )
  527. doAbort = true;
  528. // Observe, even though the current destructor was aborted or an exception
  529. // occurred, we still try to execute the base class' destructor if available
  530. // in order to free as many resources as possible.
  531. }
  532. }
  533. ot = ot->derivedFrom;
  534. }
  535. if( ctx )
  536. {
  537. if( isNested )
  538. {
  539. ctx->PopState();
  540. // Forward any request to abort the execution to the outer call
  541. if( doAbort )
  542. ctx->Abort();
  543. }
  544. else
  545. {
  546. // Return the context to engine
  547. objType->engine->ReturnContext(ctx);
  548. }
  549. }
  550. }
  551. asIObjectType *asCScriptObject::GetObjectType() const
  552. {
  553. return objType;
  554. }
  555. int asCScriptObject::GetRefCount()
  556. {
  557. return refCount.get();
  558. }
  559. void asCScriptObject::SetFlag()
  560. {
  561. gcFlag = true;
  562. }
  563. bool asCScriptObject::GetFlag()
  564. {
  565. return gcFlag;
  566. }
  567. // interface
  568. int asCScriptObject::GetTypeId() const
  569. {
  570. asCDataType dt = asCDataType::CreateObject(objType, false);
  571. return objType->engine->GetTypeIdFromDataType(dt);
  572. }
  573. asUINT asCScriptObject::GetPropertyCount() const
  574. {
  575. return asUINT(objType->properties.GetLength());
  576. }
  577. int asCScriptObject::GetPropertyTypeId(asUINT prop) const
  578. {
  579. if( prop >= objType->properties.GetLength() )
  580. return asINVALID_ARG;
  581. return objType->engine->GetTypeIdFromDataType(objType->properties[prop]->type);
  582. }
  583. const char *asCScriptObject::GetPropertyName(asUINT prop) const
  584. {
  585. if( prop >= objType->properties.GetLength() )
  586. return 0;
  587. return objType->properties[prop]->name.AddressOf();
  588. }
  589. void *asCScriptObject::GetAddressOfProperty(asUINT prop)
  590. {
  591. if( prop >= objType->properties.GetLength() )
  592. return 0;
  593. // Objects are stored by reference, so this must be dereferenced
  594. asCDataType *dt = &objType->properties[prop]->type;
  595. if( dt->IsObject() && !dt->IsObjectHandle() &&
  596. (dt->IsReference() || dt->GetObjectType()->flags & asOBJ_REF) )
  597. return *(void**)(((char*)this) + objType->properties[prop]->byteOffset);
  598. return (void*)(((char*)this) + objType->properties[prop]->byteOffset);
  599. }
  600. void asCScriptObject::EnumReferences(asIScriptEngine *engine)
  601. {
  602. // We'll notify the GC of all object handles that we're holding
  603. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  604. {
  605. asCObjectProperty *prop = objType->properties[n];
  606. if( prop->type.IsObject() )
  607. {
  608. // TODO: gc: The members of the value type needs to be enumerated
  609. // too, since the value type may be holding a reference.
  610. void *ptr;
  611. if( prop->type.IsReference() || (prop->type.GetObjectType()->flags & asOBJ_REF) )
  612. ptr = *(void**)(((char*)this) + prop->byteOffset);
  613. else
  614. ptr = (void*)(((char*)this) + prop->byteOffset);
  615. if( ptr )
  616. ((asCScriptEngine*)engine)->GCEnumCallback(ptr);
  617. }
  618. }
  619. }
  620. void asCScriptObject::ReleaseAllHandles(asIScriptEngine *engine)
  621. {
  622. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  623. {
  624. asCObjectProperty *prop = objType->properties[n];
  625. // TODO: gc: The members of the members needs to be released
  626. // too, since they may be holding a reference. Even
  627. // if the member is a value type.
  628. if( prop->type.IsObject() && prop->type.IsObjectHandle() )
  629. {
  630. void **ptr = (void**)(((char*)this) + prop->byteOffset);
  631. if( *ptr )
  632. {
  633. asASSERT( (prop->type.GetObjectType()->flags & asOBJ_NOCOUNT) || prop->type.GetBehaviour()->release );
  634. if( prop->type.GetBehaviour()->release )
  635. ((asCScriptEngine*)engine)->CallObjectMethod(*ptr, prop->type.GetBehaviour()->release);
  636. *ptr = 0;
  637. }
  638. }
  639. }
  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