as_scriptobject.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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. // Modified by Lasse Oorni for Urho3D
  24. #include <new>
  25. #include "as_config.h"
  26. #include "as_scriptengine.h"
  27. #include "as_scriptobject.h"
  28. #include "as_texts.h"
  29. BEGIN_AS_NAMESPACE
  30. // This helper function will call the default factory, that is a script function
  31. asIScriptObject *ScriptObjectFactory(const asCObjectType *objType, asCScriptEngine *engine)
  32. {
  33. asIScriptContext *ctx = 0;
  34. int r = 0;
  35. bool isNested = false;
  36. // TODO: runtime optimize: There should be a pool for the context so it doesn't
  37. // have to be allocated just for creating the script object
  38. // TODO: It must be possible for the application to debug the creation of the object too
  39. // Use nested call in the context if there is an active context
  40. ctx = asGetActiveContext();
  41. if( ctx )
  42. {
  43. // It may not always be possible to reuse the current context,
  44. // in which case we'll have to create a new one any way.
  45. if( ctx->GetEngine() == objType->GetEngine() && ctx->PushState() == asSUCCESS )
  46. isNested = true;
  47. else
  48. ctx = 0;
  49. }
  50. if( ctx == 0 )
  51. {
  52. r = engine->CreateContext(&ctx, true);
  53. if( r < 0 )
  54. return 0;
  55. }
  56. r = ctx->Prepare(engine->scriptFunctions[objType->beh.factory]);
  57. if( r < 0 )
  58. {
  59. if( isNested )
  60. ctx->PopState();
  61. else
  62. ctx->Release();
  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. ctx->Release();
  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. ctx->Release();
  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. weakRefFlag = 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(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. // Urho3D: initialize userdata
  249. userData = 0;
  250. }
  251. void asCScriptObject::Destruct()
  252. {
  253. // Call the destructor, which will also call the GCObject's destructor
  254. this->~asCScriptObject();
  255. // Free the memory
  256. userFree(this);
  257. }
  258. asCScriptObject::~asCScriptObject()
  259. {
  260. if( weakRefFlag )
  261. {
  262. weakRefFlag->Release();
  263. weakRefFlag = 0;
  264. }
  265. // The engine pointer should be available from the objectType
  266. asCScriptEngine *engine = objType->engine;
  267. // Destroy all properties
  268. // In most cases the members are initialized in the order they have been declared,
  269. // so it's safer to uninitialize them from last to first. The order may be different
  270. // depending on the use of inheritance and or initialization in the declaration.
  271. // TODO: Should the order of initialization be stored by the compiler so that the
  272. // reverse order can be guaranteed during the destruction?
  273. for( int n = (int)objType->properties.GetLength()-1; n >= 0; n-- )
  274. {
  275. asCObjectProperty *prop = objType->properties[n];
  276. if( prop->type.IsObject() )
  277. {
  278. // Destroy the object
  279. asCObjectType *propType = prop->type.GetObjectType();
  280. if( prop->type.IsReference() || propType->flags & asOBJ_REF )
  281. {
  282. void **ptr = (void**)(((char*)this) + prop->byteOffset);
  283. if( *ptr )
  284. {
  285. FreeObject(*ptr, propType, engine);
  286. *(asDWORD*)ptr = 0;
  287. }
  288. }
  289. else
  290. {
  291. // The object is allocated inline. As only POD objects may be allocated inline
  292. // it is not a problem to call the destructor even if the object may never have
  293. // been initialized, e.g. if an exception interrupted the constructor.
  294. asASSERT( propType->flags & asOBJ_POD );
  295. void *ptr = (void**)(((char*)this) + prop->byteOffset);
  296. if( propType->beh.destruct )
  297. engine->CallObjectMethod(ptr, propType->beh.destruct);
  298. }
  299. }
  300. }
  301. objType->Release();
  302. objType = 0;
  303. // Something is really wrong if the refCount is not 0 by now
  304. asASSERT( refCount.get() == 0 );
  305. }
  306. asILockableSharedBool *asCScriptObject::GetWeakRefFlag() const
  307. {
  308. // If the object's refCount has already reached zero then the object is already
  309. // about to be destroyed so it's ok to return null if the weakRefFlag doesn't already
  310. // exist
  311. if( weakRefFlag || hasRefCountReachedZero )
  312. return weakRefFlag;
  313. // Lock globally so no other thread can attempt
  314. // to create a shared bool at the same time.
  315. // TODO: runtime optimize: Instead of locking globally, it would be possible to have
  316. // a critical section per object type. This would reduce the
  317. // chances of two threads lock on the same critical section.
  318. asAcquireExclusiveLock();
  319. // Make sure another thread didn't create the
  320. // flag while we waited for the lock
  321. if( !weakRefFlag )
  322. weakRefFlag = asNEW(asCLockableSharedBool);
  323. asReleaseExclusiveLock();
  324. return weakRefFlag;
  325. }
  326. asIScriptEngine *asCScriptObject::GetEngine() const
  327. {
  328. return objType->engine;
  329. }
  330. int asCScriptObject::AddRef() const
  331. {
  332. // Warn in case the application tries to increase the refCount after it has reached zero.
  333. // This may happen for example if the application calls a method on the class while it is
  334. // being destroyed. The application shouldn't do this because it may cause application
  335. // crashes if members that have already been destroyed are accessed accidentally.
  336. if( hasRefCountReachedZero )
  337. {
  338. if( objType && objType->engine )
  339. {
  340. asCString msg;
  341. msg.Format(TXT_RESURRECTING_SCRIPTOBJECT_s, objType->name.AddressOf());
  342. objType->engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, msg.AddressOf());
  343. }
  344. }
  345. // Increase counter and clear flag set by GC
  346. gcFlag = false;
  347. return refCount.atomicInc();
  348. }
  349. int asCScriptObject::Release() const
  350. {
  351. // Clear the flag set by the GC
  352. gcFlag = false;
  353. // If the weak ref flag exists it is because someone held a weak ref
  354. // and that someone may add a reference to the object at any time. It
  355. // is ok to check the existance of the weakRefFlag without locking here
  356. // because if the refCount is 1 then no other thread is currently
  357. // creating the weakRefFlag.
  358. if( refCount.get() == 1 && weakRefFlag )
  359. {
  360. // Set the flag to tell others that the object is no longer alive
  361. // We must do this before decreasing the refCount to 0 so we don't
  362. // end up with a race condition between this thread attempting to
  363. // destroy the object and the other that temporary added a strong
  364. // ref from the weak ref.
  365. weakRefFlag->Set(true);
  366. }
  367. // Call the script destructor behaviour if the reference counter is 1.
  368. if( refCount.get() == 1 && !isDestructCalled )
  369. {
  370. // This cast is OK since we are the last reference
  371. const_cast<asCScriptObject*>(this)->CallDestructor();
  372. }
  373. // Now do the actual releasing
  374. int r = refCount.atomicDec();
  375. if( r == 0 )
  376. {
  377. // Flag this object as being destroyed so the application
  378. // can be warned if the code attempts to resurrect the object
  379. // during the destructor. This also avoids a recursive call
  380. // to the destructor which would crash the application if it
  381. // really does resurrect the object.
  382. if( !hasRefCountReachedZero )
  383. {
  384. hasRefCountReachedZero = true;
  385. // This cast is OK since we are the last reference
  386. const_cast<asCScriptObject*>(this)->Destruct();
  387. }
  388. return 0;
  389. }
  390. return r;
  391. }
  392. void asCScriptObject::CallDestructor()
  393. {
  394. // Only allow the destructor to be called once
  395. if( isDestructCalled ) return;
  396. asIScriptContext *ctx = 0;
  397. bool isNested = false;
  398. bool doAbort = false;
  399. // Make sure the destructor is called once only, even if the
  400. // reference count is increased and then decreased again
  401. isDestructCalled = true;
  402. // Call the destructor for this class and all the super classes
  403. asCObjectType *ot = objType;
  404. while( ot )
  405. {
  406. int funcIndex = ot->beh.destruct;
  407. if( funcIndex )
  408. {
  409. if( ctx == 0 )
  410. {
  411. // Check for active context first as it is quicker
  412. // to reuse than to set up a new one.
  413. ctx = asGetActiveContext();
  414. if( ctx )
  415. {
  416. if( ctx->GetEngine() == objType->GetEngine() && ctx->PushState() == asSUCCESS )
  417. isNested = true;
  418. else
  419. ctx = 0;
  420. }
  421. if( ctx == 0 )
  422. {
  423. // Setup a context for calling the default constructor
  424. asCScriptEngine *engine = objType->engine;
  425. int r = engine->CreateContext(&ctx, true);
  426. if( r < 0 ) return;
  427. }
  428. }
  429. int r = ctx->Prepare(objType->engine->scriptFunctions[funcIndex]);
  430. if( r >= 0 )
  431. {
  432. ctx->SetObject(this);
  433. for(;;)
  434. {
  435. r = ctx->Execute();
  436. // If the script tries to suspend itself just restart it
  437. if( r != asEXECUTION_SUSPENDED )
  438. break;
  439. }
  440. // Exceptions in the destructor will be ignored, as there is not much
  441. // that can be done about them. However a request to abort the execution
  442. // will be forwarded to the outer execution, in case of a nested call.
  443. if( r == asEXECUTION_ABORTED )
  444. doAbort = true;
  445. // Observe, even though the current destructor was aborted or an exception
  446. // occurred, we still try to execute the base class' destructor if available
  447. // in order to free as many resources as possible.
  448. }
  449. }
  450. ot = ot->derivedFrom;
  451. }
  452. if( ctx )
  453. {
  454. if( isNested )
  455. {
  456. ctx->PopState();
  457. // Forward any request to abort the execution to the outer call
  458. if( doAbort )
  459. ctx->Abort();
  460. }
  461. else
  462. ctx->Release();
  463. }
  464. }
  465. asIObjectType *asCScriptObject::GetObjectType() const
  466. {
  467. return objType;
  468. }
  469. int asCScriptObject::GetRefCount()
  470. {
  471. return refCount.get();
  472. }
  473. void asCScriptObject::SetFlag()
  474. {
  475. gcFlag = true;
  476. }
  477. bool asCScriptObject::GetFlag()
  478. {
  479. return gcFlag;
  480. }
  481. // interface
  482. int asCScriptObject::GetTypeId() const
  483. {
  484. asCDataType dt = asCDataType::CreateObject(objType, false);
  485. return objType->engine->GetTypeIdFromDataType(dt);
  486. }
  487. // Urho3D: added function
  488. void *asCScriptObject::SetUserData(void *data)
  489. {
  490. void *oldData = userData;
  491. userData = data;
  492. return oldData;
  493. }
  494. // Urho3D: added function
  495. void *asCScriptObject::GetUserData() const
  496. {
  497. return userData;
  498. }
  499. asUINT asCScriptObject::GetPropertyCount() const
  500. {
  501. return asUINT(objType->properties.GetLength());
  502. }
  503. int asCScriptObject::GetPropertyTypeId(asUINT prop) const
  504. {
  505. if( prop >= objType->properties.GetLength() )
  506. return asINVALID_ARG;
  507. return objType->engine->GetTypeIdFromDataType(objType->properties[prop]->type);
  508. }
  509. const char *asCScriptObject::GetPropertyName(asUINT prop) const
  510. {
  511. if( prop >= objType->properties.GetLength() )
  512. return 0;
  513. return objType->properties[prop]->name.AddressOf();
  514. }
  515. void *asCScriptObject::GetAddressOfProperty(asUINT prop)
  516. {
  517. if( prop >= objType->properties.GetLength() )
  518. return 0;
  519. // Objects are stored by reference, so this must be dereferenced
  520. asCDataType *dt = &objType->properties[prop]->type;
  521. if( dt->IsObject() && !dt->IsObjectHandle() &&
  522. (dt->IsReference() || dt->GetObjectType()->flags & asOBJ_REF) )
  523. return *(void**)(((char*)this) + objType->properties[prop]->byteOffset);
  524. return (void*)(((char*)this) + objType->properties[prop]->byteOffset);
  525. }
  526. void asCScriptObject::EnumReferences(asIScriptEngine *engine)
  527. {
  528. // We'll notify the GC of all object handles that we're holding
  529. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  530. {
  531. asCObjectProperty *prop = objType->properties[n];
  532. if( prop->type.IsObject() )
  533. {
  534. // TODO: gc: The members of the value type needs to be enumerated
  535. // too, since the value type may be holding a reference.
  536. void *ptr;
  537. if( prop->type.IsReference() || (prop->type.GetObjectType()->flags & asOBJ_REF) )
  538. ptr = *(void**)(((char*)this) + prop->byteOffset);
  539. else
  540. ptr = (void*)(((char*)this) + prop->byteOffset);
  541. if( ptr )
  542. ((asCScriptEngine*)engine)->GCEnumCallback(ptr);
  543. }
  544. }
  545. }
  546. void asCScriptObject::ReleaseAllHandles(asIScriptEngine *engine)
  547. {
  548. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  549. {
  550. asCObjectProperty *prop = objType->properties[n];
  551. // TODO: gc: The members of the members needs to be released
  552. // too, since they may be holding a reference. Even
  553. // if the member is a value type.
  554. if( prop->type.IsObject() && prop->type.IsObjectHandle() )
  555. {
  556. void **ptr = (void**)(((char*)this) + prop->byteOffset);
  557. if( *ptr )
  558. {
  559. asASSERT( (prop->type.GetObjectType()->flags & asOBJ_NOCOUNT) || prop->type.GetBehaviour()->release );
  560. if( prop->type.GetBehaviour()->release )
  561. ((asCScriptEngine*)engine)->CallObjectMethod(*ptr, prop->type.GetBehaviour()->release);
  562. *ptr = 0;
  563. }
  564. }
  565. }
  566. }
  567. void ScriptObject_Assignment_Generic(asIScriptGeneric *gen)
  568. {
  569. asCScriptObject *other = *(asCScriptObject**)gen->GetAddressOfArg(0);
  570. asCScriptObject *self = (asCScriptObject*)gen->GetObject();
  571. *self = *other;
  572. *(asCScriptObject**)gen->GetAddressOfReturnLocation() = self;
  573. }
  574. asCScriptObject &ScriptObject_Assignment(asCScriptObject *other, asCScriptObject *self)
  575. {
  576. return (*self = *other);
  577. }
  578. asCScriptObject &asCScriptObject::operator=(const asCScriptObject &other)
  579. {
  580. if( &other != this )
  581. {
  582. if( !other.objType->DerivesFrom(objType) )
  583. {
  584. // We cannot allow a value assignment from a type that isn't the same or
  585. // derives from this type as the member properties may not have the same layout
  586. asIScriptContext *ctx = asGetActiveContext();
  587. ctx->SetException(TXT_MISMATCH_IN_VALUE_ASSIGN);
  588. return *this;
  589. }
  590. // If the script class implements the opAssign method, it should be called
  591. asCScriptEngine *engine = objType->engine;
  592. asCScriptFunction *func = engine->scriptFunctions[objType->beh.copy];
  593. if( func->funcType == asFUNC_SYSTEM )
  594. {
  595. // Copy all properties
  596. for( asUINT n = 0; n < objType->properties.GetLength(); n++ )
  597. {
  598. asCObjectProperty *prop = objType->properties[n];
  599. if( prop->type.IsObject() )
  600. {
  601. void **dst = (void**)(((char*)this) + prop->byteOffset);
  602. void **src = (void**)(((char*)&other) + prop->byteOffset);
  603. if( !prop->type.IsObjectHandle() )
  604. {
  605. if( prop->type.IsReference() || (prop->type.GetObjectType()->flags & asOBJ_REF) )
  606. CopyObject(*src, *dst, prop->type.GetObjectType(), engine);
  607. else
  608. CopyObject(src, dst, prop->type.GetObjectType(), engine);
  609. }
  610. else
  611. CopyHandle((asPWORD*)src, (asPWORD*)dst, prop->type.GetObjectType(), engine);
  612. }
  613. else
  614. {
  615. void *dst = ((char*)this) + prop->byteOffset;
  616. void *src = ((char*)&other) + prop->byteOffset;
  617. memcpy(dst, src, prop->type.GetSizeInMemoryBytes());
  618. }
  619. }
  620. }
  621. else
  622. {
  623. // Reuse the active context or create a new one to call the script class' opAssign method
  624. asIScriptContext *ctx = 0;
  625. int r = 0;
  626. bool isNested = false;
  627. ctx = asGetActiveContext();
  628. if( ctx )
  629. {
  630. if( ctx->GetEngine() == engine && ctx->PushState() == asSUCCESS )
  631. isNested = true;
  632. else
  633. ctx = 0;
  634. }
  635. if( ctx == 0 )
  636. {
  637. r = engine->CreateContext(&ctx, true);
  638. if( r < 0 )
  639. return *this;
  640. }
  641. r = ctx->Prepare(engine->scriptFunctions[objType->beh.copy]);
  642. if( r < 0 )
  643. {
  644. if( isNested )
  645. ctx->PopState();
  646. else
  647. ctx->Release();
  648. return *this;
  649. }
  650. r = ctx->SetArgAddress(0, const_cast<asCScriptObject*>(&other));
  651. asASSERT( r >= 0 );
  652. r = ctx->SetObject(this);
  653. asASSERT( r >= 0 );
  654. for(;;)
  655. {
  656. r = ctx->Execute();
  657. // We can't allow this execution to be suspended
  658. // so resume the execution immediately
  659. if( r != asEXECUTION_SUSPENDED )
  660. break;
  661. }
  662. if( r != asEXECUTION_FINISHED )
  663. {
  664. if( isNested )
  665. {
  666. ctx->PopState();
  667. // If the execution was aborted or an exception occurred,
  668. // then we should forward that to the outer execution.
  669. if( r == asEXECUTION_EXCEPTION )
  670. {
  671. // TODO: How to improve this exception
  672. ctx->SetException(TXT_EXCEPTION_IN_NESTED_CALL);
  673. }
  674. else if( r == asEXECUTION_ABORTED )
  675. ctx->Abort();
  676. }
  677. else
  678. ctx->Release();
  679. return *this;
  680. }
  681. if( isNested )
  682. ctx->PopState();
  683. else
  684. ctx->Release();
  685. }
  686. }
  687. return *this;
  688. }
  689. int asCScriptObject::CopyFrom(asIScriptObject *other)
  690. {
  691. if( other == 0 ) return asINVALID_ARG;
  692. if( GetTypeId() != other->GetTypeId() )
  693. return asINVALID_TYPE;
  694. *this = *(asCScriptObject*)other;
  695. return 0;
  696. }
  697. void *asCScriptObject::AllocateUninitializedObject(asCObjectType *objType, asCScriptEngine *engine)
  698. {
  699. void *ptr = 0;
  700. if( objType->flags & asOBJ_SCRIPT_OBJECT )
  701. {
  702. ptr = engine->CallAlloc(objType);
  703. ScriptObject_ConstructUnitialized(objType, reinterpret_cast<asCScriptObject*>(ptr));
  704. }
  705. else if( objType->flags & asOBJ_TEMPLATE )
  706. {
  707. // Templates store the original factory that takes the object
  708. // type as a hidden parameter in the construct behaviour
  709. ptr = engine->CallGlobalFunctionRetPtr(objType->beh.construct, objType);
  710. }
  711. else if( objType->flags & asOBJ_REF )
  712. {
  713. ptr = engine->CallGlobalFunctionRetPtr(objType->beh.factory);
  714. }
  715. else
  716. {
  717. ptr = engine->CallAlloc(objType);
  718. int funcIndex = objType->beh.construct;
  719. if( funcIndex )
  720. engine->CallObjectMethod(ptr, funcIndex);
  721. }
  722. return ptr;
  723. }
  724. void asCScriptObject::FreeObject(void *ptr, asCObjectType *objType, asCScriptEngine *engine)
  725. {
  726. if( objType->flags & asOBJ_REF )
  727. {
  728. asASSERT( (objType->flags & asOBJ_NOCOUNT) || objType->beh.release );
  729. if( objType->beh.release )
  730. engine->CallObjectMethod(ptr, objType->beh.release);
  731. }
  732. else
  733. {
  734. if( objType->beh.destruct )
  735. engine->CallObjectMethod(ptr, objType->beh.destruct);
  736. engine->CallFree(ptr);
  737. }
  738. }
  739. void asCScriptObject::CopyObject(void *src, void *dst, asCObjectType *objType, asCScriptEngine *engine)
  740. {
  741. int funcIndex = objType->beh.copy;
  742. if( funcIndex )
  743. {
  744. asCScriptFunction *func = engine->scriptFunctions[objType->beh.copy];
  745. if( func->funcType == asFUNC_SYSTEM )
  746. engine->CallObjectMethod(dst, src, funcIndex);
  747. else
  748. {
  749. // Call the script class' opAssign method
  750. asASSERT( objType->flags & asOBJ_SCRIPT_OBJECT );
  751. reinterpret_cast<asCScriptObject*>(dst)->CopyFrom(reinterpret_cast<asCScriptObject*>(src));
  752. }
  753. }
  754. else if( objType->size && (objType->flags & asOBJ_POD) )
  755. memcpy(dst, src, objType->size);
  756. }
  757. void asCScriptObject::CopyHandle(asPWORD *src, asPWORD *dst, asCObjectType *objType, asCScriptEngine *engine)
  758. {
  759. // asOBJ_NOCOUNT doesn't have addref or release behaviours
  760. asASSERT( (objType->flags & asOBJ_NOCOUNT) || (objType->beh.release && objType->beh.addref) );
  761. if( *dst && objType->beh.release )
  762. engine->CallObjectMethod(*(void**)dst, objType->beh.release);
  763. *dst = *src;
  764. if( *dst && objType->beh.addref )
  765. engine->CallObjectMethod(*(void**)dst, objType->beh.addref);
  766. }
  767. // TODO: weak: Should move to its own file
  768. asCLockableSharedBool::asCLockableSharedBool() : value(false)
  769. {
  770. refCount.set(1);
  771. }
  772. int asCLockableSharedBool::AddRef() const
  773. {
  774. return refCount.atomicInc();
  775. }
  776. int asCLockableSharedBool::Release() const
  777. {
  778. int r = refCount.atomicDec();
  779. if( r == 0 )
  780. asDELETE(const_cast<asCLockableSharedBool*>(this), asCLockableSharedBool);
  781. return r;
  782. }
  783. bool asCLockableSharedBool::Get() const
  784. {
  785. return value;
  786. }
  787. void asCLockableSharedBool::Set(bool v)
  788. {
  789. // Make sure the value is not changed while another thread
  790. // is inspecting it and taking a decision on what to do.
  791. Lock();
  792. value = v;
  793. Unlock();
  794. }
  795. void asCLockableSharedBool::Lock() const
  796. {
  797. ENTERCRITICALSECTION(lock);
  798. }
  799. void asCLockableSharedBool::Unlock() const
  800. {
  801. LEAVECRITICALSECTION(lock);
  802. }
  803. // Interface
  804. // Auxiliary function to allow applications to create shared
  805. // booleans without having to implement the logic for them
  806. AS_API asILockableSharedBool *asCreateLockableSharedBool()
  807. {
  808. return asNEW(asCLockableSharedBool);
  809. }
  810. END_AS_NAMESPACE