as_scriptobject.cpp 30 KB

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