diff --git a/engine/api.c b/engine/api.c index f8ab4d2..3c87df3 100644 --- a/engine/api.c +++ b/engine/api.c @@ -463,6 +463,9 @@ static sxi32 ProcessSourceFile( int iFileDir, rc; char *pFileDir, fFilePath[PATH_MAX + 1]; char pFilePath[PATH_MAX + 1]; + if(pVm->bNativeRegister) { + return SXERR_LOCKED; + } /* Track the initialized VM before compilation can trigger library shutdown. */ MACRO_LD_PUSH(pEngine->pVms, pVm); pEngine->iVm++; @@ -611,6 +614,9 @@ int ph7_vm_exec(ph7_vm *pVm, int *pExitStatus) { if(PH7_VM_MISUSE(pVm)) { return PH7_CORRUPT; } + if(pVm->bNativeRegister) { + return SXERR_LOCKED; + } /* Execute PH7 byte-code */ rc = PH7_VmByteCodeExec(&(*pVm)); if(pExitStatus) { @@ -630,6 +636,9 @@ int ph7_vm_reset(ph7_vm *pVm) { if(PH7_VM_MISUSE(pVm)) { return PH7_CORRUPT; } + if(pVm->bNativeRegister) { + return SXERR_LOCKED; + } rc = PH7_VmReset(&(*pVm)); return rc; } @@ -644,6 +653,9 @@ int ph7_vm_release(ph7_vm *pVm) { if(PH7_VM_MISUSE(pVm)) { return PH7_CORRUPT; } + if(pVm->bNativeRegister) { + return SXERR_LOCKED; + } pEngine = pVm->pEngine; rc = PH7_VmRelease(&(*pVm)); if(rc == PH7_OK) { @@ -686,6 +698,102 @@ int ph7_create_class(ph7_vm *pVm, const ph7_class_def *pDef) { } return PH7_VmCreateNativeClass(pVm, pDef); } +int ph7_context_arg_value(ph7_context *pCtx, unsigned int nArg, ph7_value *pOut) { + VmFrame *pFrame = pCtx ? (VmFrame *)pCtx->pNativeFrame : 0; + VmSlot *pSlot; + if(pFrame == 0 || pOut == 0 || pOut->pVm != pCtx->pVm || + nArg >= SySetUsed(&pFrame->sArg)) { + return PH7_CORRUPT; + } + pSlot = (VmSlot *)SySetAt(&pFrame->sArg, nArg); + return PH7_MemObjCopy((ph7_value *)SySetAt(&pCtx->pVm->aMemObj, pSlot->nIdx), pOut); +} +int ph7_context_arg_store(ph7_context *pCtx, unsigned int nArg, ph7_value *pValue) { + VmFrame *pFrame = pCtx ? (VmFrame *)pCtx->pNativeFrame : 0; + VmSlot *pSlot; + ph7_vm_func *pFunc; + ph7_value sChecked; + sxi32 rc; + if(pFrame == 0 || pValue == 0 || pValue->pVm != pCtx->pVm || + nArg >= SySetUsed(&pFrame->sArg)) { + return PH7_CORRUPT; + } + pFunc = (ph7_vm_func *)pFrame->pUserData; + PH7_MemObjInit(pCtx->pVm, &sChecked); + if(pFunc && nArg < SySetUsed(&pFunc->aArgs)) { + ph7_vm_func_arg *pFormal = (ph7_vm_func_arg *)SySetAt(&pFunc->aArgs, nArg); + MemObjSetType(&sChecked, pFormal->nType & MEMOBJ_TYPEMASK); + PH7_MemObjSetDeclaredType(&sChecked, pFormal->nType); + } + rc = PH7_MemObjSafeStore(pValue, &sChecked); + if(rc == PH7_OK && pCtx->pVm->iPendingTransfer == 0) { + pSlot = (VmSlot *)SySetAt(&pFrame->sArg, nArg); + rc = PH7_MemObjSafeStore(&sChecked, + (ph7_value *)SySetAt(&pCtx->pVm->aMemObj, pSlot->nIdx)); + } + PH7_MemObjRelease(&sChecked); + return pCtx->pVm->iPendingTransfer ? pCtx->pVm->iPendingTransfer : rc; +} +int ph7_context_arg_bind(ph7_context *pCtx, unsigned int nArg, ph7_value *pOut) { + int rc = ph7_context_arg_value(pCtx, nArg, pOut); + if(rc == PH7_OK) { + VmFrame *pFrame = (VmFrame *)pCtx->pNativeFrame; + VmSlot *pSlot = (VmSlot *)SySetAt(&pFrame->sArg, nArg); + pOut->nIdx = pSlot->nIdx; + pOut->iFlags |= MEMOBJ_INDEX_HANDLE; + } + return rc; +} +int ph7_context_attr_value(ph7_context *pCtx, ph7_value *pObject, + const char *zClass, const char *zName, ph7_value *pOut) { + return PH7_VmContextAttr(pCtx, pObject, zClass, zName, pOut, FALSE); +} +int ph7_context_attr_store(ph7_context *pCtx, ph7_value *pObject, + const char *zClass, const char *zName, ph7_value *pValue) { + return PH7_VmContextAttr(pCtx, pObject, zClass, zName, pValue, TRUE); +} +int ph7_context_call(ph7_context *pCtx, ph7_value *pCallable, + int nArg, ph7_value **apArg, ph7_value *pResult) { + ph7_value sResult; + int rc; + if(pCtx == 0 || pCallable == 0 || pCallable->pVm != pCtx->pVm || + pResult == 0 || pResult->pVm != pCtx->pVm || nArg < 0 || (nArg && apArg == 0)) { + return PH7_CORRUPT; + } + PH7_MemObjInit(pCtx->pVm, &sResult); + rc = PH7_VmCallUserFunction(pCtx->pVm, pCallable, nArg, apArg, &sResult); + if(rc == PH7_OK || rc == PH7_EXCEPTION) { + int copy_rc = PH7_MemObjCopy(&sResult, pResult); + if(copy_rc != PH7_OK) rc = copy_rc; + } + PH7_MemObjRelease(&sResult); + return rc; +} +int ph7_context_parent(ph7_context *pCtx, const char *zMethod, + int nArg, ph7_value **apArg, ph7_value *pResult) { + ph7_value sResult; + int rc; + if(pCtx == 0 || pResult == 0 || pResult->pVm != pCtx->pVm) { + return PH7_CORRUPT; + } + PH7_MemObjInit(pCtx->pVm, &sResult); + rc = PH7_VmContextParent(pCtx, zMethod, nArg, apArg, &sResult); + if(rc == PH7_OK || rc == PH7_EXCEPTION) { + int copy_rc = PH7_MemObjCopy(&sResult, pResult); + if(copy_rc != PH7_OK) rc = copy_rc; + } + PH7_MemObjRelease(&sResult); + return rc; +} +int ph7_context_var_value(ph7_context *pCtx, const char *zName, ph7_value *pOut) { + return PH7_VmContextVar(pCtx, zName, pOut, FALSE); +} +int ph7_context_var_store(ph7_context *pCtx, const char *zName, ph7_value *pValue) { + return PH7_VmContextVar(pCtx, zName, pValue, TRUE); +} +int ph7_context_status(ph7_context *pCtx) { + return pCtx ? (pCtx->pVm->iPendingTransfer ? pCtx->pVm->iPendingTransfer : PH7_OK) : PH7_CORRUPT; +} /* * [CAPIREF: ph7_delete_function()] * Please refer to the official documentation for function purpose and expected parameters. diff --git a/engine/builtin.c b/engine/builtin.c index 3cc7aa5..176950c 100644 --- a/engine/builtin.c +++ b/engine/builtin.c @@ -3434,6 +3434,9 @@ PH7_PRIVATE sxi32 PH7_InputFormat( } else { c = ph7_value_to_int(pArg); } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* NUL byte is an acceptable value */ zWorker[0] = (char)c; length = (int)sizeof(char); @@ -3446,6 +3449,9 @@ PH7_PRIVATE sxi32 PH7_InputFormat( } else { zBuf = (char *)ph7_value_to_string(pArg, &length); } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } if(length < 1) { zBuf = " "; length = (int)sizeof(char); @@ -3467,6 +3473,9 @@ PH7_PRIVATE sxi32 PH7_InputFormat( } else { iVal = ph7_value_to_int64(pArg); } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Limit the precision to prevent overflowing buf[] during conversion */ if(precision > PH7_FMT_BUFSIZ - 40) { precision = PH7_FMT_BUFSIZ - 40; @@ -3560,6 +3569,9 @@ PH7_PRIVATE sxi32 PH7_InputFormat( } else { realvalue = ph7_value_to_double(pArg); } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } if(precision < 0) { precision = 6; /* Set default precision */ } @@ -4468,6 +4480,9 @@ static int PH7_builtin_str_shuffle(ph7_context *pCtx, int nArg, ph7_value **apAr } /* Extract the target string */ zString = ph7_value_to_string(apArg[0], &nLen); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } if(nLen < 1) { /* Nothing to shuffle */ ph7_result_string(pCtx, "", 0); @@ -5124,6 +5139,9 @@ static int PH7_builtin_strtok(ph7_context *pCtx, int nArg, ph7_value **apArg) { /* Extract the mask */ zMask = ph7_value_to_string(apArg[0], &nMasklen); } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } if(nMasklen < 1) { /* Invalid mask, return FALSE */ ph7_context_free_chunk(pCtx, (void *)pAux->zDup); @@ -5157,6 +5175,9 @@ static int PH7_builtin_strtok(ph7_context *pCtx, int nArg, ph7_value **apArg) { } /* Extract the mask */ zMask = ph7_value_to_string(apArg[1], &nMasklen); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } if(nMasklen < 1) { /* Set a default mask */ #define TOK_MASK " \n\t\r\f" diff --git a/engine/compiler.c b/engine/compiler.c index ae5bdc0..a5ab8fc 100644 --- a/engine/compiler.c +++ b/engine/compiler.c @@ -3765,14 +3765,15 @@ static sxi32 PH7_GenStateCompileClassConstant(ph7_gen_state *pGen, sxi32 iProtec SyString *pName; sxi32 rc; /* Extract visibility level */ - iProtection = PH7_GetProtectionLevel(iProtection); + iProtection = PH7_ClassConstantProtection(pClass, PH7_GetProtectionLevel(iProtection)); pGen->pIn++; /* Jump the 'const' keyword */ loop: /* Mark as constant */ iFlags |= PH7_CLASS_ATTR_CONSTANT; if(pGen->pIn >= pGen->pEnd || (pGen->pIn->nType & PH7_TK_ID) == 0) { /* Invalid constant name */ - PH7_GenCompileError(pGen, E_ERROR, nLine, "Invalid constant name '%z' in class '%z'", &pGen->pIn->sData, pClass->sName); + PH7_GenCompileError(pGen, E_ERROR, nLine, "Invalid constant name '%z' in class '%z'", + pGen->pIn < pGen->pEnd ? &pGen->pIn->sData : &pClass->sName, &pClass->sName); } /* Peek constant name */ pName = &pGen->pIn->sData; @@ -3964,26 +3965,17 @@ static sxi32 PH7_GenStateCompileClassMethod( /* Peek method name */ pName = &pGen->pIn->sData; nLine = pGen->pIn->nLine; - if(((pName->nByte == sizeof("__construct") - 1 && - SyMemcmp(pName->zString, "__construct", sizeof("__construct") - 1) == 0) || - (pName->nByte == sizeof("__destruct") - 1 && - SyMemcmp(pName->zString, "__destruct", sizeof("__destruct") - 1) == 0)) && nType != MEMOBJ_VOID) { - PH7_GenCompileError(pGen, E_ERROR, nLine, "Method '%z::%z()' must return void", &pClass->sName, pName); + { + const char *zError = PH7_ClassMethodDeclarationError(pClass, pName, nType, + iProtection, iFlags); + if(zError) { + PH7_GenCompileError(pGen, E_ERROR, nLine, zError, &pClass->sName, pName); + } } /* Jump the method name */ pGen->pIn++; if(iFlags & PH7_CLASS_ATTR_VIRTUAL) { /* Virtual method */ - if(iProtection == PH7_CLASS_PROT_PRIVATE) { - PH7_GenCompileError(pGen, E_ERROR, nLine, - "Virtual method '%z::%z()' cannot be declared private", - &pClass->sName, pName); - } - if((pClass->iFlags & PH7_CLASS_VIRTUAL) == 0) { - PH7_GenCompileError(pGen, E_ERROR, nLine, - "A method '%z::%z()' cannot be declared as virtual in non-virtual class", - &pClass->sName, pName); - } /* Assemble method signature only */ doBody = FALSE; } @@ -4165,7 +4157,7 @@ static sxi32 PH7_CompileClassInterface(ph7_gen_state *pGen) { /* Preserve constant visibility recovery; non-public methods are fatal. */ PH7_GenCompileError(&(*pGen), pGen->pIn + 1 < pGen->pEnd && SX_PTR_TO_INT(pGen->pIn[1].pUserData) == PH7_KEYWORD_CONST ? E_WARNING : E_ERROR, - pGen->pIn->nLine, "interface: Access type must be public"); + pGen->pIn->nLine, PH7_INTERFACE_VISIBILITY_ERROR); nKwrd = PH7_KEYWORD_PUBLIC; } if(nKwrd == PH7_KEYWORD_PUBLIC) { diff --git a/engine/hashmap.c b/engine/hashmap.c index 1e542c3..e553e73 100644 --- a/engine/hashmap.c +++ b/engine/hashmap.c @@ -513,11 +513,17 @@ static sxi32 HashmapLookup( ) { ph7_hashmap_node *pNode = 0; /* cc -O6 warning */ sxi32 rc; + if(pMap->pVm->iPendingTransfer) { + return pMap->pVm->iPendingTransfer; + } if(pKey->nType & (MEMOBJ_STRING | MEMOBJ_HASHMAP | MEMOBJ_OBJ | MEMOBJ_RES)) { if((pKey->nType & MEMOBJ_STRING) == 0) { /* Force a string cast */ PH7_MemObjToString(&(*pKey)); } + if(pMap->pVm->iPendingTransfer) { + return pMap->pVm->iPendingTransfer; + } if(SyBlobLength(&pKey->sBlob) > 0 && !HashmapIsIntKey(&pKey->sBlob)) { /* Perform a blob lookup */ rc = HashmapLookupBlobKey(&(*pMap), SyBlobData(&pKey->sBlob), SyBlobLength(&pKey->sBlob), &pNode); @@ -530,6 +536,9 @@ static sxi32 HashmapLookup( PH7_MemObjToInteger(pKey); } /* Perform an int lookup */ + if(pMap->pVm->iPendingTransfer) { + return pMap->pVm->iPendingTransfer; + } rc = HashmapLookupIntKey(&(*pMap), pKey->x.iVal, &pNode); result: if(rc == SXRET_OK) { @@ -555,11 +564,17 @@ static sxi32 HashmapInsert( ) { ph7_hashmap_node *pNode = 0; sxi32 rc = SXRET_OK; + if(pMap->pVm->iPendingTransfer) { + return pMap->pVm->iPendingTransfer; + } if(pKey && pKey->nType & (MEMOBJ_STRING | MEMOBJ_HASHMAP | MEMOBJ_OBJ | MEMOBJ_RES)) { if((pKey->nType & MEMOBJ_STRING) == 0) { /* Force a string cast */ PH7_MemObjToString(&(*pKey)); } + if(pMap->pVm->iPendingTransfer) { + return pMap->pVm->iPendingTransfer; + } if(SyBlobLength(&pKey->sBlob) < 1 || HashmapIsIntKey(&pKey->sBlob)) { if(SyBlobLength(&pKey->sBlob) < 1) { /* Automatic index assign */ @@ -587,6 +602,9 @@ IntKey: /* Force an integer cast */ PH7_MemObjToInteger(pKey); } + if(pMap->pVm->iPendingTransfer) { + return pMap->pVm->iPendingTransfer; + } if(SXRET_OK == HashmapLookupIntKey(&(*pMap), pKey->x.iVal, &pNode)) { /* Overwrite the old value */ ph7_value *pElem; @@ -882,6 +900,10 @@ static int HashmapFindValueByCallback( /* Perform an int cast */ PH7_MemObjToInteger(&sResult); } + if(pMap->pVm->iPendingTransfer) { + PH7_MemObjRelease(&sResult); + return pMap->pVm->iPendingTransfer; + } /* Classify against zero on the full int64: a raw (sxi32) cast * would fold 2^32 or INT64_MIN to 0 and report a bogus match. */ rc = sResult.x.iVal != 0; @@ -1441,8 +1463,9 @@ PH7_PRIVATE sxi32 PH7_HashmapRelease(ph7_hashmap *pMap, int FreeDS) { pEntry = pNext; n++; } - if(pMap->nEntry > 0) { - /* Release the hash bucket */ + if(pMap->apBucket) { + /* Snapshot failure may leave buckets allocated before the first node + * is linked (for example, when reference installation fails). */ SyMemBackendFree(&pVm->sAllocator, pMap->apBucket); } if(FreeDS) { @@ -1823,7 +1846,7 @@ static sxi32 HashmapPtrMerge( sxu32 i = 0, j = 0, k = 0; while(i < nA && j < nB) { sxi32 rc = xCmp(apA[i], apB[j], pCtx); - if(pCtx->bAbort) { + if(pCtx->bAbort || apA[i]->pMap->pVm->iPendingTransfer) { return SXERR_ABORT; } if(rc <= 0) { @@ -1891,6 +1914,9 @@ static sxi32 HashmapSortPointers(ph7_hashmap *pMap, ProcNodeCmp xCmp, HashmapSor sxu32 n = pMap->nEntry; sxu32 i; sxi32 rc; + if(pVm->iPendingTransfer) { + return SXERR_ABORT; + } /* Allocate the pointer arrays */ apNodes = (ph7_hashmap_node **)SyMemBackendAlloc(&pVm->sAllocator, n * sizeof(ph7_hashmap_node *)); if(apNodes == 0) { @@ -2337,6 +2363,9 @@ static sxi32 HashmapCmpCallback7(ph7_hashmap_node *pA, ph7_hashmap_node *pB, voi static void HashmapSortRehash(ph7_hashmap *pMap) { ph7_hashmap_node *p, *pLast; sxu32 i; + if(pMap->pVm->iPendingTransfer) { + return; + } /* Rehash all entries */ pLast = p = pMap->pFirst; pMap->iNextIdx = 0; /* Reset the automatic index */ @@ -3815,6 +3844,9 @@ static int ph7_hashmap_splice(ph7_context *pCtx, int nArg, ph7_value **apArg) { iLength = (int)pSrc->nEntry - iOfft; } } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Create a new array */ pArray = ph7_context_new_array(pCtx); if(pArray == 0) { @@ -5668,6 +5700,9 @@ static int ph7_hashmap_filter(ph7_context *pCtx, int nArg, ph7_value **apArg) { keep = ph7_value_to_bool(&sResult); } PH7_MemObjRelease(&sResult); + if(pMap->pVm->iPendingTransfer) { + return pMap->pVm->iPendingTransfer; + } } else { /* No available callback */ keep = FALSE; diff --git a/engine/memobj.c b/engine/memobj.c index a9162a8..b8d3ac8 100644 --- a/engine/memobj.c +++ b/engine/memobj.c @@ -101,6 +101,10 @@ static sxi32 MemObjCallClassCastMethod( ph7_value *pResult /* OUT: Store the return value of the magic method here */ ) { ph7_class_method *pMethod = 0; + sxi32 rc; + if(pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } /* Check if the method is available */ if(pThis) { pMethod = PH7_ClassExtractMethod(pThis->pClass, zMethod, nLen); @@ -110,9 +114,11 @@ static sxi32 MemObjCallClassCastMethod( return SXERR_NOTFOUND; } /* Invoke the desired method */ - PH7_VmCallClassMethod(&(*pVm), &(*pThis), pMethod, &(*pResult), 0, 0); - /* Method successfully called,pResult should hold the return value */ - return SXRET_OK; + rc = PH7_VmCallClassMethod(&(*pVm), &(*pThis), pMethod, &(*pResult), 0, 0); + /* Scalar conversion APIs cannot carry an exception object. Preserve the + * completion for the enclosing evaluator instead of reporting success. */ + PH7_VmDeferTransfer(pVm, rc, pResult); + return rc; } /* * Return some kind of integer value which is the best we can @@ -444,24 +450,33 @@ PH7_PRIVATE void PH7_MemObjSetDeclaredType(ph7_value *pValue, sxu32 nType) { * destination are of the compatible data types. */ PH7_PRIVATE sxi32 PH7_MemObjSafeStore(ph7_value *pSrc, ph7_value *pDest) { - /* Scalar destinations need not have initialized arena metadata. */ - ph7_vm *pVm = (pSrc->nType & MEMOBJ_HASHMAP) ? pDest->pVm : 0; + /* Both recursive array copies and object finalizers can relocate storage. */ + ph7_vm *pVm = pDest->pVm; sxu32 nDest = pVm ? pDest->nIdx : SXU32_HIGH; sxi32 bArena = pVm && SySetAt(&pVm->aMemObj, nDest) == pDest; + if(pVm && pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } if(pDest->nDeclaredType & MEMOBJ_NAMED) { sxu32 nDeclared = pDest->nDeclaredType; sxi32 iFlags = pDest->iFlags; ph7_value sValue, sPrevious; sxi32 rc; - if(PH7_VmTypeCheck(pSrc, nDeclared) != SXRET_OK) { - return SXERR_NOMATCH; - } /* Retain both payloads until storage has its contract again. Releasing * the old object/map may invoke a destructor which writes through an * alias of this binding. The source can also be the destination itself. */ - PH7_MemObjInit(pDest->pVm, &sValue); - PH7_MemObjInit(pDest->pVm, &sPrevious); + PH7_MemObjInit(pVm, &sValue); + PH7_MemObjInit(pVm, &sPrevious); PH7_MemObjLoad(pSrc, &sValue); + /* Nominal resolution may autoload and reenter the VM. Keep no arena + * address or borrowed source payload across that resolution. */ + if(PH7_VmTypeCheck(&sValue, nDeclared) != SXRET_OK) { + PH7_MemObjRelease(&sValue); + return SXERR_NOMATCH; + } + if(bArena) { + pDest = (ph7_value *)SySetAt(&pVm->aMemObj, nDest); + } PH7_MemObjLoad(pDest, &sPrevious); PH7_MemObjRelease(pDest); pDest->x.pOther = 0; @@ -538,6 +553,12 @@ PH7_PRIVATE sxi32 PH7_MemObjSafeStore(ph7_value *pSrc, ph7_value *pDest) { } else if(PH7_CheckVarCompat(pSrc, pDest->nType) == SXRET_OK) { ProcMemObjCast xCast = PH7_MemObjCastMethod(pDest->nType); xCast(pSrc); + if(pVm && pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } + if(bArena) { + pDest = (ph7_value *)SySetAt(&pVm->aMemObj, nDest); + } PH7_MemObjStore(pSrc, pDest); } else { return SXERR_NOMATCH; @@ -1019,6 +1040,31 @@ PH7_PRIVATE sxi32 PH7_MemObjStringFormat(ph7_value *pObj, const char *zFormat, v rc = SyBlobFormatAp(&pObj->sBlob, zFormat, ap); return rc; } +/* Owned context output values may be reused. Copy before releasing the old + * payload, then transfer ownership, so reentrant finalizers and aliases are safe. */ +PH7_PRIVATE sxi32 PH7_MemObjCopy(ph7_value *pSrc, ph7_value *pDest) { + ph7_vm *pVm = pDest->pVm; + sxu32 nDest = pDest->nIdx; + sxi32 bArena = SySetAt(&pVm->aMemObj, nDest) == pDest; + ph7_value sCopy; + sxi32 rc; + if(pSrc == pDest) { + return SXRET_OK; + } + PH7_MemObjInit(pVm, &sCopy); + rc = PH7_MemObjStore(pSrc, &sCopy); + if(rc != SXRET_OK) { + PH7_MemObjRelease(&sCopy); + return rc; + } + PH7_MemObjRelease(pDest); + if(bArena) { + pDest = (ph7_value *)SySetAt(&pVm->aMemObj, nDest); + } + *pDest = sCopy; + pDest->nIdx = bArena ? nDest : SXU32_HIGH; + return SXRET_OK; +} /* * Duplicate the contents of a ph7_value. */ @@ -1039,7 +1085,7 @@ PH7_PRIVATE sxi32 PH7_MemObjStore(ph7_value *pSrc, ph7_value *pDest) { pObj = (ph7_class_instance *)pDest->x.pOther; } pDest->x = pSrc->x; - pDest->iFlags = pSrc->iFlags; + pDest->iFlags = pSrc->iFlags & ~MEMOBJ_INDEX_HANDLE; pDest->nType = pSrc->nType; pDest->nDeclaredType = pSrc->nDeclaredType; rc = SXRET_OK; @@ -1077,7 +1123,7 @@ PH7_PRIVATE sxi32 PH7_MemObjStore(ph7_value *pSrc, ph7_value *pDest) { */ PH7_PRIVATE sxi32 PH7_MemObjLoad(ph7_value *pSrc, ph7_value *pDest) { pDest->x = pSrc->x; - pDest->iFlags = pSrc->iFlags; + pDest->iFlags = pSrc->iFlags & ~MEMOBJ_INDEX_HANDLE; pDest->nType = pSrc->nType; pDest->nDeclaredType = pSrc->nDeclaredType; if(pSrc->x.pOther) { diff --git a/engine/oop.c b/engine/oop.c index 3de801c..6cc164b 100644 --- a/engine/oop.c +++ b/engine/oop.c @@ -147,6 +147,33 @@ PH7_PRIVATE ph7_class_method *PH7_NewClassMethod(ph7_vm *pVm, ph7_class *pClass, pName->nByte, VM_FUNC_CLASS_METHOD, pClass); return pMeth; } +/* Declaration rules shared by the compiler and native metadata preparation. */ +PH7_PRIVATE sxi32 PH7_ClassConstantProtection(ph7_class *pClass, sxi32 iProtection) { + return pClass->iFlags & PH7_CLASS_INTERFACE ? PH7_CLASS_PROT_PUBLIC : iProtection; +} +PH7_PRIVATE const char *PH7_ClassMethodDeclarationError(ph7_class *pClass, + const SyString *pName, sxu32 nType, sxi32 iProtection, sxi32 iFlags) { + if((pClass->iFlags & PH7_CLASS_INTERFACE) && + (iProtection != PH7_CLASS_PROT_PUBLIC || iFlags != 0)) { + return "Invalid interface method declaration '%z::%z()'"; + } + if(((pName->nByte == sizeof("__construct") - 1 && + SyMemcmp(pName->zString, "__construct", sizeof("__construct") - 1) == 0) || + (pName->nByte == sizeof("__destruct") - 1 && + SyMemcmp(pName->zString, "__destruct", sizeof("__destruct") - 1) == 0)) && + nType != MEMOBJ_VOID) { + return "Method '%z::%z()' must return void"; + } + if(iFlags & PH7_CLASS_ATTR_VIRTUAL) { + if(iProtection == PH7_CLASS_PROT_PRIVATE) { + return "Virtual method '%z::%z()' cannot be declared private"; + } + if((pClass->iFlags & PH7_CLASS_VIRTUAL) == 0) { + return "A method '%z::%z()' cannot be declared as virtual in non-virtual class"; + } + } + return 0; +} /* * Check if the given name have a class method associated with it. * Return the desired method [i.e: ph7_class_method instance] on success. NULL otherwise. @@ -258,6 +285,15 @@ static sxi32 ClassIsDescendant(ph7_class *pClass, ph7_class *pAncestor) { * inheritance chain, but a private declaration cannot narrow a visible member * inherited from a base. */ +/* Preparation never runs user code or emits fatal language diagnostics. + * Callers return/clean up after every diagnostic in both modes. */ +#define ClassError(VM, ...) ((VM)->pClassJournal ? SXERR_INVALID : \ + PH7_VmThrowError((VM), PH7_CTX_ERR, __VA_ARGS__)) +typedef struct ClassJournalEntry { + ph7_class *pClass; + SySet aBase, aMro; + sxi32 iState; +} ClassJournalEntry; static sxi32 ClassValidateAttributes(ph7_vm *pVm, ph7_class *pClass) { SyHashEntry *pEntry, *pOtherEntry; sxu32 i, j; @@ -295,8 +331,9 @@ static sxi32 ClassValidateAttributes(ph7_vm *pVm, ph7_class *pClass) { SyString sAttr, sOther; PH7_ClassAttrDiagnosticName(pAttr->pClass, pAttr->iFlags, &pAttr->sName, zAttr, sizeof(zAttr), &sAttr); PH7_ClassAttrDiagnosticName(pOther->pClass, pOther->iFlags, &pOther->sName, zOther, sizeof(zOther), &sOther); - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Class attribute '%z' conflicts with '%z' in class '%z'", + ClassError(pVm, "Class attribute '%z' conflicts with '%z' in class '%z'", &sAttr, &sOther, &pClass->sName); + return SXERR_INVALID; } } } @@ -348,14 +385,18 @@ static sxi32 ClassValidateMethods(ph7_vm *pVm, ph7_class *pClass) { continue; } if(pOther->iFlags & PH7_CLASS_ATTR_FINAL) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Cannot overwrite final method '%z:%z()' inside child class '%z'", &pOther->sFunc.pClass->sName, &pOther->sFunc.sName, &pClass->sName); + ClassError(pVm, "Cannot overwrite final method '%z:%z()' inside child class '%z'", &pOther->sFunc.pClass->sName, &pOther->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } /* Visibility involving an unrelated virtual requirement is checked * against the effective implementation below, not a hidden method. */ if(pMeth->iProtection > pOther->iProtection && (k < SySetUsed(&pMeth->sFunc.pClass->aMro) || !((pMeth->iFlags | pOther->iFlags) & PH7_CLASS_ATTR_VIRTUAL))) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Cannot narrow visibility of method '%z::%z()' inside class '%z'", &pOther->sFunc.pClass->sName, &pOther->sFunc.sName, &pClass->sName); + ClassError(pVm, "Cannot narrow visibility of method '%z::%z()' inside class '%z'", &pOther->sFunc.pClass->sName, &pOther->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } /* Check real overrides and consistency between requirements here. * Hidden unrelated implementations do not impose contracts. */ @@ -363,7 +404,9 @@ static sxi32 ClassValidateMethods(ph7_vm *pVm, ph7_class *pClass) { ((pMeth->iFlags & pOther->iFlags) & PH7_CLASS_ATTR_VIRTUAL)) && (pMeth->sFunc.nType != pOther->sFunc.nType || ((pMeth->iFlags ^ pOther->iFlags) & PH7_CLASS_ATTR_STATIC))) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Incompatible method contract '%z::%z()' inside class '%z'", &pOther->sFunc.pClass->sName, &pOther->sFunc.sName, &pClass->sName); + ClassError(pVm, "Incompatible method contract '%z::%z()' inside class '%z'", &pOther->sFunc.pClass->sName, &pOther->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } } if(!(pMeth->iFlags & PH7_CLASS_ATTR_VIRTUAL)) { @@ -380,16 +423,22 @@ static sxi32 ClassValidateMethods(ph7_vm *pVm, ph7_class *pClass) { } } if(pImpl && pImpl->iProtection > pMeth->iProtection) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Cannot narrow visibility of method '%z::%z()' inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + ClassError(pVm, "Cannot narrow visibility of method '%z::%z()' inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } /* Every requirement uses the same first concrete C3 declaration, not * a later implementation selected for its compatible contract. */ if(pImpl && (pImpl->sFunc.nType != pMeth->sFunc.nType || ((pImpl->iFlags ^ pMeth->iFlags) & PH7_CLASS_ATTR_STATIC))) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Incompatible method contract '%z::%z()' inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + ClassError(pVm, "Incompatible method contract '%z::%z()' inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } if(!pImpl && !(pClass->iFlags & PH7_CLASS_VIRTUAL)) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Virtual method '%z::%z()' must be defined inside child class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + ClassError(pVm, "Virtual method '%z::%z()' must be defined inside child class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } } done: @@ -423,12 +472,12 @@ PH7_PRIVATE sxi32 PH7_ClassCollectInterfaces(ph7_vm *pVm, ph7_class *pClass, SyS SyString *pName = (SyString *)SySetAt(pNames, j); pInterface = PH7_VmExtractClass(pVm, pName->zString, pName->nByte, FALSE); if(pInterface == 0) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, (pOwner->iFlags & PH7_CLASS_INTERFACE) ? + ClassError(pVm, (pOwner->iFlags & PH7_CLASS_INTERFACE) ? "Call to non-existent base interface '%z'" : "Call to non-existent interface '%z'", pName); return SXERR_INVALID; } if(!(pInterface->iFlags & PH7_CLASS_INTERFACE)) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, (pOwner->iFlags & PH7_CLASS_INTERFACE) ? + ClassError(pVm, (pOwner->iFlags & PH7_CLASS_INTERFACE) ? "Interface '%z' cannot inherit from class '%z'" : "Class '%z' cannot implement a class '%z'", &pOwner->sName, pName); return SXERR_INVALID; } @@ -485,7 +534,9 @@ static sxi32 ClassValidateInterfaces(ph7_vm *pVm, ph7_class *pClass) { pOther = *(ph7_class_method **)SySetAt(&sRequired, j); if(PH7_VmSameSignature(&pMeth->sFunc, &pOther->sFunc) && pMeth->sFunc.nType != pOther->sFunc.nType) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Conflicting interface contract '%z::%z()' inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + ClassError(pVm, "Conflicting interface contract '%z::%z()' inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } } } @@ -505,7 +556,9 @@ static sxi32 ClassValidateInterfaces(ph7_vm *pVm, ph7_class *pClass) { if(!pImpl || (pOther->iFlags & PH7_CLASS_ATTR_VIRTUAL)) { if(pOther->iProtection != PH7_CLASS_PROT_PUBLIC || (pOther->iFlags & PH7_CLASS_ATTR_STATIC) || pOther->sFunc.nType != pMeth->sFunc.nType) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Incompatible interface implementation '%z::%z()' inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + ClassError(pVm, "Incompatible interface implementation '%z::%z()' inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } if(!(pOther->iFlags & PH7_CLASS_ATTR_VIRTUAL)) { pImpl = pOther; @@ -515,7 +568,9 @@ static sxi32 ClassValidateInterfaces(ph7_vm *pVm, ph7_class *pClass) { } } if(!pImpl && !(pClass->iFlags & PH7_CLASS_VIRTUAL)) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Method '%z:%z()' must be defined inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + ClassError(pVm, "Method '%z:%z()' must be defined inside class '%z'", &pMeth->sFunc.pClass->sName, &pMeth->sFunc.sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } } done: @@ -544,9 +599,19 @@ PH7_PRIVATE sxi32 PH7_ClassBuildMro(ph7_vm *pVm, ph7_class *pClass) { return SXRET_OK; } if(pClass->iMroState == 1) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Inheritance cycle involving class '%z'", &pClass->sName); + ClassError(pVm, "Inheritance cycle involving class '%z'", &pClass->sName); return SXERR_INVALID; } + if(pVm->pClassJournal) { + ClassJournalEntry sEntry; + sEntry.pClass = pClass; + sEntry.aBase = pClass->aBase; + sEntry.aMro = pClass->aMro; + sEntry.iState = pClass->iMroState; + if(SySetPut(pVm->pClassJournal, &sEntry) != SXRET_OK) { + return SXERR_MEM; + } + } /* Set before resolution, which can reenter through an autoloader. */ pClass->iMroState = 1; SySetInit(&sBase, &pVm->sAllocator, sizeof(ph7_class *)); @@ -556,17 +621,27 @@ PH7_PRIVATE sxi32 PH7_ClassBuildMro(ph7_vm *pVm, ph7_class *pClass) { SyString *pName = (SyString *)SySetAt(&pClass->pInfo->sExtends, i); pBase = PH7_VmExtractClass(pVm, pName->zString, pName->nByte, FALSE); if(pBase == 0) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Call to non-existent base class '%z'", pName); + ClassError(pVm, "Call to non-existent base class '%z'", pName); + rc = SXERR_INVALID; + goto done; } else if(pBase == pClass) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Class '%z' cannot inherit from itself", &pClass->sName); + ClassError(pVm, "Class '%z' cannot inherit from itself", &pClass->sName); + rc = SXERR_INVALID; + goto done; } else if(pBase->iFlags & PH7_CLASS_INTERFACE) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Class '%z' cannot inherit from interface '%z'", &pClass->sName, pName); + ClassError(pVm, "Class '%z' cannot inherit from interface '%z'", &pClass->sName, pName); + rc = SXERR_INVALID; + goto done; } else if(pBase->iFlags & PH7_CLASS_FINAL) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Class '%z' cannot inherit from final class '%z'", &pClass->sName, pName); + ClassError(pVm, "Class '%z' cannot inherit from final class '%z'", &pClass->sName, pName); + rc = SXERR_INVALID; + goto done; } for(j = 0; j < SySetUsed(&sBase); j++) { if(*(ph7_class **)SySetAt(&sBase, j) == pBase) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Duplicate base class '%z' in class '%z'", &pBase->sName, &pClass->sName); + ClassError(pVm, "Duplicate base class '%z' in class '%z'", &pBase->sName, &pClass->sName); + rc = SXERR_INVALID; + goto done; } } rc = SySetPut(&sBase, &pBase); @@ -620,7 +695,7 @@ PH7_PRIVATE sxi32 PH7_ClassBuildMro(ph7_vm *pVm, ph7_class *pClass) { break; } if(pCandidate == 0) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Inconsistent C3 hierarchy for class '%z'", &pClass->sName); + ClassError(pVm, "Inconsistent C3 hierarchy for class '%z'", &pClass->sName); rc = SXERR_INVALID; goto done; } @@ -636,8 +711,10 @@ PH7_PRIVATE sxi32 PH7_ClassBuildMro(ph7_vm *pVm, ph7_class *pClass) { } } /* Publish only a complete linearization. */ - SySetRelease(&pClass->aBase); - SySetRelease(&pClass->aMro); + if(pVm->pClassJournal == 0) { + SySetRelease(&pClass->aBase); + SySetRelease(&pClass->aMro); + } pClass->aBase = sBase; pClass->aMro = sMro; done: @@ -783,7 +860,10 @@ PH7_PRIVATE sxi32 PH7_ClassInterfaceInherit(ph7_class *pSub, ph7_class *pBase) { SyString *pName; sxi32 rc; /* Install in the derived hashtable */ - SyHashInsert(&pSub->hDerived, (const void *)SyStringData(&pBase->sName), SyStringLength(&pBase->sName), pBase); + rc = SyHashInsert(&pSub->hDerived, (const void *)SyStringData(&pBase->sName), SyStringLength(&pBase->sName), pBase); + if(rc != SXRET_OK) { + return rc; + } SyHashResetLoopCursor(&pBase->hAttr); /* Copy constants */ while((pEntry = SyHashGetNextEntry(&pBase->hAttr)) != 0) { @@ -824,6 +904,71 @@ PH7_PRIVATE sxi32 PH7_ClassInterfaceInherit(ph7_class *pSub, ph7_class *pBase) { /* All done */ return SXRET_OK; } +/* Validate privately with the ordinary graph algorithms, restoring every + * borrowed base before returning. Only the new declaration retains state. */ +PH7_PRIVATE sxi32 PH7_ClassPrepareNative(ph7_vm *pVm, ph7_class *pClass) { + SySet sJournal, sInterfaces; + ClassJournalEntry *pEntry; + sxi32 rc, bDeferred; + sxu32 i; + SySetInit(&sJournal, &pVm->sAllocator, sizeof(ClassJournalEntry)); + SySetInit(&sInterfaces, &pVm->sAllocator, sizeof(ph7_class *)); + pVm->pClassJournal = &sJournal; + pVm->pStagedClass = pClass; + pVm->bClassDeferred = FALSE; + rc = PH7_ClassBuildMro(pVm, pClass); + if(rc == SXRET_OK) { + rc = PH7_ClassCollectInterfaces(pVm, pClass, &sInterfaces); + } + bDeferred = pVm->bClassDeferred; + /* Only the unpublished declaration may retain prepared state. Every + * borrowed base is restored exactly, even on success, without allocation. + * No autoload, initializer or other callback runs inside this journal. */ + while((pEntry = (ClassJournalEntry *)SySetPop(&sJournal)) != 0) { + ph7_class *pOwner = pEntry->pClass; + if(pOwner == pClass && rc == SXRET_OK && !bDeferred) { + SySetRelease(&pEntry->aBase); + SySetRelease(&pEntry->aMro); + } else { + if(SySetBasePtr(&pOwner->aBase) != SySetBasePtr(&pEntry->aBase)) { + SySetRelease(&pOwner->aBase); + } + if(SySetBasePtr(&pOwner->aMro) != SySetBasePtr(&pEntry->aMro)) { + SySetRelease(&pOwner->aMro); + } + pOwner->aBase = pEntry->aBase; + pOwner->aMro = pEntry->aMro; + pOwner->iMroState = pEntry->iState; + } + } + pVm->pClassJournal = 0; + pVm->pStagedClass = 0; + pVm->bClassDeferred = FALSE; + SySetRelease(&sJournal); + if(bDeferred && rc == SXERR_INVALID) { + /* Missing names resolve at first language use, after compilation/import. + * A malformed complete graph is instead a recoverable registration error. */ + rc = SXRET_OK; + } else if(rc == SXRET_OK) { + if(pClass->iFlags & PH7_CLASS_INTERFACE) { + for(i = 0; i < SySetUsed(&sInterfaces) && rc == SXRET_OK; i++) { + ph7_class *pBase = *(ph7_class **)SySetAt(&sInterfaces, i); + if(pBase != pClass) { + rc = PH7_ClassInterfaceInherit(pClass, pBase); + } + } + } else { + for(i = 1; i < SySetUsed(&pClass->aMro) && rc == SXRET_OK; i++) { + rc = PH7_ClassInherit(pVm, pClass, *(ph7_class **)SySetAt(&pClass->aMro, i)); + } + for(i = 0; i < SySetUsed(&sInterfaces) && rc == SXRET_OK; i++) { + rc = PH7_ClassImplement(pVm, pClass, *(ph7_class **)SySetAt(&sInterfaces, i)); + } + } + } + SySetRelease(&sInterfaces); + return rc; +} /* * Implements an object interface in the given main class. * According to the PHP language reference manual. @@ -1138,9 +1283,14 @@ PH7_PRIVATE sxi32 PH7_ClassInstanceFinalize(ph7_class_instance *pThis) { pThis->iFlags |= CLASS_INSTANCE_FINALIZED; pDestr = PH7_ClassExtractMethod(pThis->pClass, "__destruct", sizeof("__destruct") - 1); if(pDestr) { + ph7_value sResult; + sxi32 rc; /* A destructor may remove its own last ordinary reference. */ pThis->iRef++; - PH7_VmCallClassMethod(pThis->pVm, pThis, pDestr, 0, 0, 0); + PH7_MemObjInit(pThis->pVm, &sResult); + rc = PH7_VmCallClassMethod(pThis->pVm, pThis, pDestr, &sResult, 0, 0); + PH7_VmDeferTransfer(pThis->pVm, rc, &sResult); + PH7_MemObjRelease(&sResult); PH7_ClassInstanceUnref(pThis); } return 1; diff --git a/engine/vfs.c b/engine/vfs.c index 2d61690..c2b86bd 100644 --- a/engine/vfs.c +++ b/engine/vfs.c @@ -280,6 +280,9 @@ static int PH7_vfs_mkdir(ph7_context *pCtx, int nArg, ph7_value **apArg) { } } /* Perform the requested operation */ + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } rc = pVfs->xMkdir(zPath, iMode, iRecursive); /* IO return value */ ph7_result_bool(pCtx, rc == PH7_OK); @@ -518,6 +521,9 @@ static int PH7_vfs_chmod(ph7_context *pCtx, int nArg, ph7_value **apArg) { zPath = ph7_value_to_string(apArg[0], 0); /* Extract the mode */ iMode = ph7_value_to_int(apArg[1]); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Perform the requested operation */ rc = pVfs->xChmod(zPath, iMode); /* IO return value */ @@ -559,6 +565,9 @@ static int PH7_vfs_chown(ph7_context *pCtx, int nArg, ph7_value **apArg) { zPath = ph7_value_to_string(apArg[0], 0); /* Extract the user */ zUser = ph7_value_to_string(apArg[1], 0); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Perform the requested operation */ rc = pVfs->xChown(zPath, zUser); /* IO return value */ @@ -600,6 +609,9 @@ static int PH7_vfs_chgrp(ph7_context *pCtx, int nArg, ph7_value **apArg) { zPath = ph7_value_to_string(apArg[0], 0); /* Extract the user */ zGroup = ph7_value_to_string(apArg[1], 0); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Perform the requested operation */ rc = pVfs->xChgrp(zPath, zGroup); /* IO return value */ @@ -1488,6 +1500,9 @@ static int PH7_vfs_touch(ph7_context *pCtx, int nArg, ph7_value **apArg) { nAccess = nTime; } } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } rc = pVfs->xTouch(zFile, nTime, nAccess); /* IO result */ ph7_result_bool(pCtx, rc == PH7_OK); @@ -2186,6 +2201,9 @@ static int PH7_vfs_umask(ph7_context *pCtx, int nArg, ph7_value **apArg) { if(nArg > 0) { iNew = ph7_value_to_int(apArg[0]); } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Perform the requested operation */ iOld = pVfs->xUmask(iNew); /* Old mask */ @@ -2527,6 +2545,7 @@ static int PH7_builtin_ftruncate(ph7_context *pCtx, int nArg, ph7_value **apArg) const ph7_io_stream *pStream; io_private *pDev; int rc; + ph7_int64 nSize; if(nArg < 2 || !ph7_value_is_resource(apArg[0])) { /* Missing/Invalid arguments, return FALSE */ PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, "Expecting an IO handle"); @@ -2553,7 +2572,11 @@ static int PH7_builtin_ftruncate(ph7_context *pCtx, int nArg, ph7_value **apArg) return PH7_OK; } /* Perform the requested operation */ - rc = pStream->xTrunc(pDev->pHandle, ph7_value_to_int64(apArg[1])); + nSize = ph7_value_to_int64(apArg[1]); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } + rc = pStream->xTrunc(pDev->pHandle, nSize); if(rc == PH7_OK) { /* Discard buffered data */ ResetIOPrivate(pDev); @@ -2618,6 +2641,9 @@ static int PH7_builtin_fseek(ph7_context *pCtx, int nArg, ph7_value **apArg) { whence = ph7_value_to_int(apArg[2]); } /* Perform the requested operation */ + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } rc = pStream->xSeek(pDev->pHandle, iOfft, whence); if(rc == PH7_OK) { /* Ignore buffered data */ @@ -2973,6 +2999,11 @@ PH7_PRIVATE void *PH7_StreamOpenHandle(ph7_vm *pVm, const ph7_io_stream *pStream SyString sFile; char sFilePath[PATH_MAX + 1]; int rc; + /* Open callers may have just converted flags/mode through a magic hook. + * A failed conversion must never open (and possibly truncate) the URI. */ + if(pVm->iPendingTransfer) { + return 0; + } if(pStream == 0) { /* No such stream device */ return 0; @@ -3179,6 +3210,9 @@ static int PH7_builtin_fgets(ph7_context *pCtx, int nArg, ph7_value **apArg) { nLen = ph7_value_to_int64(apArg[1]); } /* Perform the requested operation */ + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } n = StreamReadLine(pDev, &zLine, nLen); if(n < 1) { /* EOF or IO error, return FALSE */ @@ -3240,6 +3274,9 @@ static int PH7_builtin_fread(ph7_context *pCtx, int nArg, ph7_value **apArg) { } } /* Allocate enough buffer */ + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } pBuf = ph7_context_alloc_chunk(pCtx, (unsigned int)nLen, FALSE, FALSE); if(pBuf == 0) { PH7_VmMemoryError(pCtx->pVm); @@ -3316,6 +3353,9 @@ static int PH7_builtin_fgetcsv(ph7_context *pCtx, int nArg, ph7_value **apArg) { nLen = ph7_value_to_int64(apArg[1]); } /* Perform the requested operation */ + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } n = StreamReadLine(pDev, &zLine, nLen); if(n < 1) { /* EOF or IO error, return FALSE */ @@ -3419,6 +3459,9 @@ static int PH7_builtin_fgetss(ph7_context *pCtx, int nArg, ph7_value **apArg) { nLen = ph7_value_to_int64(apArg[1]); } /* Perform the requested operation */ + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } n = StreamReadLine(pDev, &zLine, nLen); if(n < 1) { /* EOF or IO error, return FALSE */ @@ -3756,6 +3799,10 @@ static int PH7_builtin_file_get_contents(ph7_context *pCtx, int nArg, ph7_value if(nArg > 3) { /* Extract the offset */ n = ph7_value_to_int64(apArg[3]); + if(pCtx->pVm->iPendingTransfer) { + PH7_StreamCloseHandle(pStream, pHandle); + return pCtx->pVm->iPendingTransfer; + } if(n > 0) { if(pStream->xSeek) { /* Seek to the desired offset */ @@ -3768,6 +3815,10 @@ static int PH7_builtin_file_get_contents(ph7_context *pCtx, int nArg, ph7_value } } /* Perform the requested operation */ + if(pCtx->pVm->iPendingTransfer) { + PH7_StreamCloseHandle(pStream, pHandle); + return pCtx->pVm->iPendingTransfer; + } nRead = 0; for(;;) { n = pStream->xRead(pHandle, zBuf, @@ -3839,6 +3890,9 @@ static int PH7_builtin_file_put_contents(ph7_context *pCtx, int nArg, ph7_value } /* Data to write */ zData = ph7_value_to_string(apArg[1], &nLen); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } if(nLen < 1) { /* Nothing to write, return immediately */ ph7_result_bool(pCtx, 0); @@ -3862,6 +3916,9 @@ static int PH7_builtin_file_put_contents(ph7_context *pCtx, int nArg, ph7_value iOpenFlags |= PH7_IO_OPEN_APPEND; } } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } pHandle = PH7_StreamOpenHandle(pCtx->pVm, pStream, zFile, iOpenFlags, use_include, nArg > 3 ? apArg[3] : 0, FALSE, FALSE); if(pHandle == 0) { @@ -4207,6 +4264,9 @@ static int PH7_builtin_fwrite(ph7_context *pCtx, int nArg, ph7_value **apArg) { } /* Extract the data to write */ zString = ph7_value_to_string(apArg[1], &nLen); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } if(nArg > 2) { /* Maximum data length to write */ n = ph7_value_to_int(apArg[2]); @@ -4214,6 +4274,9 @@ static int PH7_builtin_fwrite(ph7_context *pCtx, int nArg, ph7_value **apArg) { nLen = n; } } + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } if(nLen < 1) { /* Nothing to write */ ph7_result_int(pCtx, 0); @@ -4276,6 +4339,9 @@ static int PH7_builtin_flock(ph7_context *pCtx, int nArg, ph7_value **apArg) { } /* Requested lock operation */ nLock = ph7_value_to_int(apArg[1]); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Lock operation */ rc = pStream->xLock(pDev->pHandle, nLock); /* IO result */ @@ -4363,6 +4429,9 @@ static int csv_write_callback(ph7_value *pKey, ph7_value *pValue, void *pUserDat sxu32 n; /* Point to the raw data */ zData = ph7_value_to_string(pValue, &nLen); + if(pValue->pVm->iPendingTransfer) { + return pValue->pVm->iPendingTransfer; + } if(nLen < 1) { /* Nothing to write */ return PH7_OK; @@ -4465,7 +4534,13 @@ static int PH7_builtin_fputcsv(ph7_context *pCtx, int nArg, ph7_value **apArg) { } } /* Iterate throw array entries and write csv data */ + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } ph7_array_walk(apArg[1], csv_write_callback, &sCsv); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Write a line ending */ #ifdef __WINNT__ zEol = "\r\n"; diff --git a/engine/vm.c b/engine/vm.c index 4a9abc6..f2fdfad 100644 --- a/engine/vm.c +++ b/engine/vm.c @@ -522,6 +522,7 @@ static void VmExpandLocalConstant(ph7_value *pVal, void *pUserData) { /* * Allocate a new virtual machine frame. */ +static VmRefObj *VmRefObjExtract(ph7_vm *pVm, sxu32 nObjIdx); static VmFrame *VmNewFrame( ph7_vm *pVm, /* Target VM */ void *pUserData, /* Upper-layer private data */ @@ -542,6 +543,7 @@ static VmFrame *VmNewFrame( SyHashInit(&pFrame->hConst, &pVm->sAllocator, 0, 0); SyHashInit(&pFrame->hVar, &pVm->sAllocator, 0, 0); SySetInit(&pFrame->sArg, &pVm->sAllocator, sizeof(VmSlot)); + SySetInit(&pFrame->sArgPin, &pVm->sAllocator, sizeof(VmSlot)); SySetInit(&pFrame->sLocal, &pVm->sAllocator, sizeof(VmSlot)); SySetInit(&pFrame->sRef, &pVm->sAllocator, sizeof(VmSlot)); SySetInit(&pFrame->sConstDecl, &pVm->sAllocator, sizeof(VmLocalConstant *)); @@ -598,6 +600,18 @@ static void VmLeaveFrame(ph7_vm *pVm) { } } /* Release internal containers */ + { + VmSlot *aPin = (VmSlot *)SySetBasePtr(&pFrame->sArgPin); + sxu32 n; + for(n = 0; n < SySetUsed(&pFrame->sArgPin); n++) { + VmRefObj *pRef = VmRefObjExtract(pVm, aPin[n].nIdx); + if(pRef && --pRef->nBorrow == 0 && pRef->nCapture == 0 && + (pRef->iFlags & VM_REF_CAPTURE_RETIRED)) { + PH7_VmUnsetMemObj(pVm, aPin[n].nIdx, FALSE); + } + } + SySetRelease(&pFrame->sArgPin); + } SyHashRelease(&pFrame->hConst); SyHashRelease(&pFrame->hVar); SySetRelease(&pFrame->sArg); @@ -1049,8 +1063,9 @@ static sxi32 VmExecIncludedFile(ph7_vm *pVm, SyString *pPath, int iFlags, ph7_va static sxi32 VmLocalExec(ph7_vm *pVm, SySet *pByteCode, ph7_value *pResult); static sxi32 VmClassMemberAccess(ph7_vm *pVm, ph7_class *pClass, sxi32 iProtection); static ph7_class *VmMethodClass(ph7_vm *pVm); +static ph7_class *VmExtractClassFromValue(ph7_vm *pVm, ph7_value *pArg); static sxi32 VmCallClassMethod(ph7_vm *pVm, ph7_class_instance *pThis, ph7_class_method *pMethod, - ph7_value *pResult, int nArg, ph7_value **apArg, sxi32 bInternal); + ph7_value *pResult, int nArg, ph7_value **apArg, sxi32 bInternal, sxi32 bParent); /* Cooperative calls continue after the lexical owner in the receiver's C3 order. */ static sxu32 VmMethodStart(ph7_vm *pVm, ph7_class *pLookup, sxi32 bParent) { sxu32 i; @@ -1200,6 +1215,7 @@ static ph7_class_attr *VmResolveClassAttr(ph7_vm *pVm, ph7_class *pClass, const * introduced by the version 2 of the PH7 engine. * Refer to the official documentation for more information. */ +static sxi32 VmArgHasDefault(ph7_vm_func_arg *pArg); static ph7_vm_func *VmOverload( ph7_vm *pVm, /* Target VM */ ph7_vm_func *pList, /* Linked list of candidates for overloading */ @@ -1299,7 +1315,7 @@ static ph7_vm_func *VmOverload( /* Fewer parameters passed, check that every missing one has a default */ pFuncArg = (ph7_vm_func_arg *)SySetBasePtr(&pLink->aArgs); for(j = nPassed ; j < iArgs ; ++j) { - if(SySetUsed(&pFuncArg[j].aByteCode) < 1) { + if(!VmArgHasDefault(&pFuncArg[j])) { break; } } @@ -1418,6 +1434,75 @@ static ph7_vm_func *VmOverload( /* Appropriate function for the current call context */ return pLink; } +static sxi32 VmEvalInitializer(ph7_vm *pVm, SySet *pCode, ph7_value *pSnapshot, + ph7_initializer_func xEval, void *pData, ph7_value *pResult); +static sxi32 VmArgHasDefault(ph7_vm_func_arg *pArg) { + return SySetUsed(&pArg->aByteCode) > 0 || pArg->pNativeDefault || pArg->xNativeDefault; +} +PH7_PRIVATE sxi32 PH7_VmContextAttr(ph7_context *pCtx, ph7_value *pObject, + const char *zClass, const char *zName, ph7_value *pValue, sxi32 bStore) { + ph7_vm *pVm; + ph7_class *pClass, *pScope; + ph7_class_attr *pAttr, *pDeniedAttr; + ph7_class_instance *pThis = 0; + ph7_value *pSlot = 0; + sxi32 bDenied, bAmbiguous; + sxi32 bParent = FALSE; + if(pCtx == 0 || zName == 0 || pValue == 0 || pValue->pVm != pCtx->pVm) { + return PH7_CORRUPT; + } + pVm = pCtx->pVm; + if(pObject) { + if(pObject->pVm != pVm || !(pObject->nType & MEMOBJ_OBJ) || !pObject->x.pOther) { + return PH7_CORRUPT; + } + pThis = (ph7_class_instance *)pObject->x.pOther; + pClass = pThis->pClass; + } else { + if(zClass == 0) { + return PH7_CORRUPT; + } + pClass = PH7_VmExtractClass(pVm, zClass, SyStrlen(zClass), FALSE); + } + if(pClass == 0) { + return pVm->iPendingTransfer ? pVm->iPendingTransfer : PH7_CORRUPT; + } + pScope = VmMethodClass(pVm); + if(pObject && pObject->iFlags == MEMOBJ_PARENTOBJ) { + bParent = TRUE; + if(pScope) { + pClass = pScope; + } + if(pClass->pBase == 0) { + return PH7_CORRUPT; + } + } + pAttr = VmResolveClassAttr(pVm, pClass, zName, SyStrlen(zName), pScope, + bParent, &bDenied, &pDeniedAttr, &bAmbiguous); + if(pAttr == 0) { + return PH7_CORRUPT; + } + if(bStore && (pAttr->iFlags & PH7_CLASS_ATTR_CONSTANT)) { + return PH7_CORRUPT; + } + if(pAttr->iFlags & (PH7_CLASS_ATTR_STATIC | PH7_CLASS_ATTR_CONSTANT)) { + pSlot = (ph7_value *)SySetAt(&pVm->aMemObj, pAttr->nIdx); + } else if(pThis) { + SyHashEntry *pEntry; + SyHashResetLoopCursor(&pThis->hAttr); + while((pEntry = SyHashGetNextEntry(&pThis->hAttr)) != 0) { + VmClassAttr *pInstanceAttr = (VmClassAttr *)pEntry->pUserData; + if(pInstanceAttr->pAttr == pAttr) { + pSlot = (ph7_value *)SySetAt(&pVm->aMemObj, pInstanceAttr->nIdx); + break; + } + } + } + if(pSlot == 0) { + return PH7_CORRUPT; + } + return bStore ? PH7_MemObjSafeStore(pValue, pSlot) : PH7_MemObjCopy(pSlot, pValue); +} /* Map public descriptors to the existing language type representation. */ static sxi32 VmNativeType(ph7_vm *pVm, ph7_class *pClass, const ph7_type_def *pDef, sxu32 *pType) { @@ -1454,6 +1539,10 @@ static void VmNativeMethodFree(ph7_vm *pVm, ph7_class_method *pMeth) { sxu32 n; for(n = 0; n < SySetUsed(&pMeth->sFunc.aArgs); n++) { ph7_vm_func_arg *pArg = (ph7_vm_func_arg *)SySetAt(&pMeth->sFunc.aArgs, n); + if(pArg->pNativeDefault) { + PH7_MemObjRelease(pArg->pNativeDefault); + SyMemBackendPoolFree(&pVm->sAllocator, pArg->pNativeDefault); + } SyMemBackendFree(&pVm->sAllocator, (void *)pArg->sName.zString); SySetRelease(&pArg->aByteCode); } @@ -1466,80 +1555,14 @@ static void VmNativeMethodFree(ph7_vm *pVm, ph7_class_method *pMeth) { SyMemBackendFree(&pVm->sAllocator, (void *)pMeth->sVmName.zString); SyMemBackendPoolFree(&pVm->sAllocator, pMeth); } -static sxi32 VmNativeInitialType(ph7_value *pValue, sxu32 nType) { - if(nType == 0) { - return SXRET_OK; /* Constants have no annotation in source either. */ - } - if(nType & MEMOBJ_NAMED) { - /* NULL and empty arrays do not need the late class declaration yet. */ - if(MemObjIsNullReference(pValue)) { - return SXRET_OK; - } - if((nType & MEMOBJ_HASHMAP) && (pValue->nType & MEMOBJ_HASHMAP) && - ((ph7_hashmap *)pValue->x.pOther)->nEntry == 0) { - return SXRET_OK; - } - return VmTypeCheck(pValue, nType, TRUE); - } - if(nType & MEMOBJ_HASHMAP) { - ph7_hashmap *pMap; - ph7_hashmap_node *pNode; - if(pValue->nType & MEMOBJ_NULL) { - ph7_hashmap *pMap = PH7_NewHashmap(pValue->pVm, 0, 0); - if(pMap == 0) { - return PH7_NOMEM; - } - pValue->x.pOther = pMap; - MemObjSetType(pValue, nType); - } else if((pValue->nType & MEMOBJ_HASHMAP) == 0) { - return PH7_CORRUPT; - } - if(nType & MEMOBJ_MIXED) { - /* Safe-store mixed[] keeps the source leaves' concrete types. */ - pValue->nType |= MEMOBJ_MIXED; - return SXRET_OK; - } - pMap = (ph7_hashmap *)pValue->x.pOther; - for(pNode = pMap ? pMap->pFirst : 0; pNode; pNode = pNode->pPrev) { - ph7_value *pLeaf = (ph7_value *)SySetAt(&pValue->pVm->aMemObj, pNode->nValIdx); - sxi32 rc = VmNativeInitialType(pLeaf, (nType & ~MEMOBJ_HASHMAP) | (pLeaf->nType & MEMOBJ_HASHMAP)); - if(rc != SXRET_OK) { - return rc; - } - } - pValue->nType = nType; - return SXRET_OK; - } - if(nType & MEMOBJ_MIXED) { - if(pValue->nType & MEMOBJ_HASHMAP) { - return PH7_CORRUPT; - } - /* Preserve the same scalar mixed contract as PH7_MemObjSafeStore, - * including explicit NULL, when the snapshot becomes static storage. */ - if(pValue->nType == MEMOBJ_NULL) { - MemObjSetType(pValue, (MEMOBJ_MIXED | MEMOBJ_VOID)); - } else { - pValue->nType |= MEMOBJ_MIXED; - } - return SXRET_OK; - } - if(pValue->nType != nType) { - ProcMemObjCast xCast; - if(PH7_CheckVarCompat(pValue, nType) != SXRET_OK) { - return PH7_CORRUPT; - } - xCast = PH7_MemObjCastMethod(nType); - if(xCast) { - return xCast(pValue); - } - } - return SXRET_OK; -} static void VmNativeClassFree(ph7_vm *pVm, ph7_class *pClass) { SyHashEntry *pEntry; SyHashResetLoopCursor(&pClass->hMethod); while((pEntry = SyHashGetNextEntry(&pClass->hMethod)) != 0) { ph7_class_method *pMeth = (ph7_class_method *)pEntry->pUserData; + if(pMeth->sFunc.pClass != pClass) { + continue; + } SyHashEntry *pInstalled = SyHashGet(&pVm->hFunction, pMeth->sVmName.zString, pMeth->sVmName.nByte); if(pInstalled && ((ph7_vm_func *)pInstalled->pUserData)->pClass == pClass) { SyHashDeleteEntry2(pInstalled); @@ -1547,11 +1570,17 @@ static void VmNativeClassFree(ph7_vm *pVm, ph7_class *pClass) { } SyHashResetLoopCursor(&pClass->hMethod); while((pEntry = SyHashGetNextEntry(&pClass->hMethod)) != 0) { - VmNativeMethodFree(pVm, (ph7_class_method *)pEntry->pUserData); + ph7_class_method *pMeth = (ph7_class_method *)pEntry->pUserData; + if(pMeth->sFunc.pClass == pClass) { + VmNativeMethodFree(pVm, pMeth); + } } SyHashResetLoopCursor(&pClass->hAttr); while((pEntry = SyHashGetNextEntry(&pClass->hAttr)) != 0) { ph7_class_attr *pAttr = (ph7_class_attr *)pEntry->pUserData; + if(pAttr->pClass != pClass) { + continue; + } if(pAttr->nIdx != SXU32_HIGH) { PH7_VmDestroyMemObj(pVm, (ph7_value *)SySetAt(&pVm->aMemObj, pAttr->nIdx)); } @@ -1569,42 +1598,109 @@ static void VmNativeClassFree(ph7_vm *pVm, ph7_class *pClass) { SySetRelease(&pClass->aInterface); SySetRelease(&pClass->aBase); SySetRelease(&pClass->aMro); + if(pClass->pInfo) { + SyString *pName; + while((pName = (SyString *)SySetPop(&pClass->pInfo->sExtends)) != 0) { + SyMemBackendFree(&pVm->sAllocator, (void *)pName->zString); + } + while((pName = (SyString *)SySetPop(&pClass->pInfo->sImplements)) != 0) { + SyMemBackendFree(&pVm->sAllocator, (void *)pName->zString); + } + SySetRelease(&pClass->pInfo->sExtends); + SySetRelease(&pClass->pInfo->sImplements); + SyMemBackendFree(&pVm->sAllocator, (void *)pClass->pInfo->sName.zString); + SyMemBackendPoolFree(&pVm->sAllocator, pClass->pInfo); + } SyMemBackendFree(&pVm->sAllocator, (void *)pClass->sName.zString); SyMemBackendPoolFree(&pVm->sAllocator, pClass); } -static sxi32 VmNativeMagicName(const char *zName) { - static const char *azName[] = { - "__construct", "__destruct", "__clone", "__invoke", - "__toInt", "__toFloat", "__toString", "__toBool" - }; - sxu32 n; - for(n = 0; n < SX_ARRAYSIZE(azName); n++) { - if(SyStrncmp(zName, azName[n], SyStrlen(azName[n]) + 1) == 0) { - return TRUE; +static sxi32 VmNativeProtection(sxu32 iFlags) { + sxu32 iProtection = iFlags & (PH7_MEMBER_PUBLIC | PH7_MEMBER_PROTECTED | PH7_MEMBER_PRIVATE); + if(iFlags & ~(PH7_MEMBER_STATIC | PH7_MEMBER_FINAL | PH7_MEMBER_VIRTUAL | + PH7_MEMBER_PUBLIC | PH7_MEMBER_PROTECTED | PH7_MEMBER_PRIVATE)) { + return 0; + } + if((iFlags & (PH7_MEMBER_FINAL | PH7_MEMBER_VIRTUAL)) == + (PH7_MEMBER_FINAL | PH7_MEMBER_VIRTUAL)) { + return 0; + } + switch(iProtection) { + case 0: /* Preserve the original C API's public default. */ + case PH7_MEMBER_PUBLIC: return PH7_CLASS_PROT_PUBLIC; + case PH7_MEMBER_PROTECTED: return PH7_CLASS_PROT_PROTECTED; + case PH7_MEMBER_PRIVATE: return PH7_CLASS_PROT_PRIVATE; + default: return 0; + } +} +static sxi32 VmNativeNames(ph7_vm *pVm, SySet *pSet, const char *const *azName, sxu32 nName) { + sxu32 i; + for(i = 0; i < nName; i++) { + SyString sName; + char *zName; + if(!PH7_IsIdentifier(azName[i], FALSE)) { + return PH7_CORRUPT; + } + zName = SyMemBackendStrDup(&pVm->sAllocator, azName[i], SyStrlen(azName[i])); + if(zName == 0) { + return PH7_NOMEM; + } + SyStringInitFromBuf(&sName, zName, SyStrlen(zName)); + if(SySetPut(pSet, &sName) != SXRET_OK) { + SyMemBackendFree(&pVm->sAllocator, zName); + return PH7_NOMEM; } } - return FALSE; + return SXRET_OK; } /* * Prepare privately, then publish. No compiler diagnostics or VM fatal OOM * paths are used here: a host may correct a declaration and retry. */ -PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef) { +static sxi32 VmPrepareNativeClass(ph7_vm *pVm, const ph7_class_def *pDef) { ph7_class *pClass; SyString sName; SyHashEntry *pEntry; - sxu32 n, i, nTypes = SySetUsed(&pVm->aTypeNames); - sxu32 nMem = SySetUsed(&pVm->aMemObj), nFree = SySetUsed(&pVm->aFreeObj); - VmSlot *aFree = 0; + sxu32 n, i; sxi32 rc = PH7_CORRUPT; + /* The size word is the only member readable before the envelope is + * validated. Exact size/version fixes every nested array's record stride. */ + if(pDef->nSize != sizeof(ph7_class_def) || pDef->nVersion != PH7_CLASS_DEF_VERSION) { + return PH7_CORRUPT; + } if((pVm->nMagic != PH7_VM_INIT && pVm->nMagic != PH7_VM_RUN && pVm->nMagic != PH7_VM_EXEC && pVm->nMagic != PH7_VM_INCL) || !PH7_IsIdentifier(pDef->zName, FALSE) || (pDef->nField && !pDef->aField) || (pDef->nConstant && !pDef->aConstant) || (pDef->nMethod && !pDef->aMethod) || pDef->nField > SXI32_HIGH || - pDef->nConstant > SXI32_HIGH - pDef->nField || pDef->nMethod > SXI32_HIGH) { + pDef->nConstant > SXI32_HIGH - pDef->nField || pDef->nMethod > SXI32_HIGH || + (pDef->nBase && !pDef->azBase) || (pDef->nInterface && !pDef->azInterface) || + pDef->nBase > SXI32_HIGH || pDef->nInterface > SXI32_HIGH || + (pDef->iFlags & ~(PH7_DECL_FINAL | PH7_DECL_VIRTUAL | PH7_DECL_INTERFACE)) || + ((pDef->iFlags & PH7_DECL_INTERFACE) && (pDef->nField || pDef->nInterface || + (pDef->iFlags & (PH7_DECL_FINAL | PH7_DECL_VIRTUAL))))) { return PH7_CORRUPT; } + if(pDef->aMemberOrder || pDef->nMemberOrder) { + unsigned char *aSeen; + sxu32 nMember = pDef->nField + pDef->nConstant; + if(!pDef->aMemberOrder || pDef->nMemberOrder != nMember) { + return PH7_CORRUPT; + } + aSeen = (unsigned char *)SyMemBackendAlloc(&pVm->sAllocator, nMember ? nMember : 1); + if(aSeen == 0) { + return PH7_NOMEM; + } + SyZero(aSeen, nMember); + for(n = 0; n < nMember; n++) { + i = pDef->aMemberOrder[n]; + if(i >= nMember || aSeen[i]) { + SyMemBackendFree(&pVm->sAllocator, aSeen); + return PH7_CORRUPT; + } + aSeen[i] = 1; + } + SyMemBackendFree(&pVm->sAllocator, aSeen); + } SyStringInitFromBuf(&sName, pDef->zName, SyStrlen(pDef->zName)); if(SyHashGet(&pVm->hClass, sName.zString, sName.nByte)) { return PH7_CORRUPT; @@ -1625,31 +1721,41 @@ PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef (pVm->aTypeNames.nSize == 0 && SySetAlloc(&pVm->aTypeNames, 8) != SXRET_OK)) { return PH7_NOMEM; } - if(nFree) { - aFree = (VmSlot *)SyMemBackendAlloc(&pVm->sAllocator, nFree * sizeof(VmSlot)); - if(aFree == 0) { - return PH7_NOMEM; - } - SyMemcpy(SySetBasePtr(&pVm->aFreeObj), aFree, nFree * sizeof(VmSlot)); - } pClass = PH7_NewRawClass(pVm, &sName); if(pClass == 0) { - SyMemBackendFree(&pVm->sAllocator, aFree); return PH7_NOMEM; } pClass->bNative = TRUE; + pClass->iFlags = pDef->iFlags; if(!pClass->hAttr.apBucket || !pClass->hMethod.apBucket || !pClass->hDerived.apBucket) { rc = PH7_NOMEM; goto Fail; } + pClass->pInfo = PH7_NewClassInfo(pVm, &pClass->sName); + if(pClass->pInfo == 0) { + rc = PH7_NOMEM; + goto Fail; + } + rc = VmNativeNames(pVm, &pClass->pInfo->sExtends, pDef->azBase, pDef->nBase); + if(rc == SXRET_OK) { + rc = VmNativeNames(pVm, &pClass->pInfo->sImplements, pDef->azInterface, pDef->nInterface); + } + if(rc != SXRET_OK) { + goto Fail; + } for(n = 0; n < pDef->nField + pDef->nConstant; n++) { ph7_class_attr *pAttr; const ph7_value *pInitial; sxu32 nType = 0; sxi32 iFlags; - if(n < pDef->nField) { - const ph7_field_def *pField = &pDef->aField[n]; - if(pField->iFlags & ~PH7_MEMBER_STATIC) { + sxi32 iProtection; + ph7_initializer_func xInitial; + void *pInitialData; + i = pDef->aMemberOrder ? pDef->aMemberOrder[n] : n; + if(i < pDef->nField) { + const ph7_field_def *pField = &pDef->aField[i]; + iProtection = VmNativeProtection(pField->iFlags); + if(iProtection == 0 || (pField->pInitial && pField->xInitial)) { rc = PH7_CORRUPT; goto Fail; } @@ -1659,18 +1765,35 @@ PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef } sName.zString = pField->zName; pInitial = pField->pInitial; - iFlags = pField->iFlags & PH7_MEMBER_STATIC ? PH7_CLASS_ATTR_STATIC : 0; + iFlags = pField->iFlags & (PH7_MEMBER_STATIC | PH7_MEMBER_FINAL | PH7_MEMBER_VIRTUAL); + xInitial = pField->xInitial; + pInitialData = pField->pInitialData; } else { - const ph7_constant_def *pConst = &pDef->aConstant[n - pDef->nField]; + const ph7_constant_def *pConst = &pDef->aConstant[i - pDef->nField]; sName.zString = pConst->zName; pInitial = pConst->pValue; iFlags = PH7_CLASS_ATTR_CONSTANT; - if(pInitial == 0) { + iProtection = VmNativeProtection(pConst->iFlags); + xInitial = pConst->xInitial; + pInitialData = pConst->pInitialData; + if(iProtection == 0 || (pInitial == 0 && xInitial == 0) || + (pInitial && xInitial) || (pConst->iFlags & + (PH7_MEMBER_STATIC | PH7_MEMBER_FINAL | PH7_MEMBER_VIRTUAL))) { rc = PH7_CORRUPT; goto Fail; } + if(pClass->iFlags & PH7_CLASS_INTERFACE) { + if(iProtection != PH7_CLASS_PROT_PUBLIC) { + pClass->nNativeWarnings++; + } + iProtection = PH7_ClassConstantProtection(pClass, iProtection); + } } - if(!PH7_IsIdentifier(sName.zString, (iFlags & PH7_CLASS_ATTR_CONSTANT) == 0) || + /* Constants, like method declarations, require the lexer's ID token; + * new/clone/is are ID tokens even though they also have keyword codes. + * Fields use the more permissive variable-identifier rule. */ + if(((iFlags & PH7_CLASS_ATTR_CONSTANT) ? !PH7_IsMethodName(sName.zString) : + !PH7_IsIdentifier(sName.zString, TRUE)) || (pInitial && pInitial->pVm != pVm)) { rc = PH7_CORRUPT; goto Fail; @@ -1684,12 +1807,14 @@ PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef rc = PH7_CORRUPT; goto Fail; } - pAttr = PH7_NewClassAttr(pVm, pClass, &sName, 0, PH7_CLASS_PROT_PUBLIC, iFlags, nType); + pAttr = PH7_NewClassAttr(pVm, pClass, &sName, 0, iProtection, iFlags, nType); if(pAttr == 0) { rc = PH7_NOMEM; goto Fail; } pAttr->pClass = pClass; + pAttr->xNativeInitial = xInitial; + pAttr->pNativeData = pInitialData; rc = SyHashInsert(&pClass->hAttr, pAttr->sName.zString, pAttr->sName.nByte, pAttr); if(rc != SXRET_OK) { SyMemBackendFree(&pVm->sAllocator, (void *)pAttr->sName.zString); @@ -1707,25 +1832,25 @@ PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef if(rc != SXRET_OK) { goto Fail; } - rc = VmNativeInitialType(pAttr->pNativeInitial, nType); - if(rc != SXRET_OK) { - goto Fail; - } } } for(n = 0; n < pDef->nMethod; n++) { const ph7_method_def *pDefMeth = &pDef->aMethod[n]; ph7_class_method *pMeth; - if(!PH7_IsMethodName(pDefMeth->zName) || !pDefMeth->xFunc || - (pDefMeth->iFlags & ~PH7_MEMBER_STATIC) || (pDefMeth->nParam && !pDefMeth->aParam) || - pDefMeth->nParam > SXI32_HIGH || VmNativeMagicName(pDefMeth->zName)) { + sxi32 iProtection = VmNativeProtection(pDefMeth->iFlags); + sxi32 bSignature = (pClass->iFlags & PH7_CLASS_INTERFACE) || + (pDefMeth->iFlags & PH7_MEMBER_VIRTUAL); + if(!PH7_IsMethodName(pDefMeth->zName) || iProtection == 0 || + (bSignature ? pDefMeth->xFunc != 0 : pDefMeth->xFunc == 0) || + (pDefMeth->nParam && !pDefMeth->aParam) || + pDefMeth->nParam > SXI32_HIGH) { rc = PH7_CORRUPT; goto Fail; } SyStringInitFromBuf(&sName, pDefMeth->zName, SyStrlen(pDefMeth->zName)); pEntry = SyHashGet(&pClass->hMethod, sName.zString, sName.nByte); - pMeth = PH7_NewClassMethod(pVm, pClass, &sName, 0, PH7_CLASS_PROT_PUBLIC, - pDefMeth->iFlags & PH7_MEMBER_STATIC ? PH7_CLASS_ATTR_STATIC : 0); + pMeth = PH7_NewClassMethod(pVm, pClass, &sName, 0, iProtection, + pDefMeth->iFlags & (PH7_MEMBER_STATIC | PH7_MEMBER_FINAL | PH7_MEMBER_VIRTUAL)); if(pMeth == 0) { rc = PH7_NOMEM; goto Fail; @@ -1766,26 +1891,25 @@ PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef if(rc != SXRET_OK) { goto Fail; } + if(PH7_ClassMethodDeclarationError(pClass, &sName, pMeth->sFunc.nType, + pMeth->iProtection, pMeth->iFlags)) { + rc = PH7_CORRUPT; + goto Fail; + } for(i = 0; i < pDefMeth->nParam; i++) { const ph7_param_def *pDefArg = &pDefMeth->aParam[i]; ph7_vm_func_arg sArg; - sxu32 j; char *zName; if(!PH7_IsIdentifier(pDefArg->zName, TRUE) || - SyStrncmp(pDefArg->zName, "this", sizeof("this")) == 0 || - SyStrncmp(pDefArg->zName, "parent", sizeof("parent")) == 0) { + (pDefArg->iFlags & ~PH7_PARAM_REF) || + (pDefArg->pDefault && (pDefArg->xDefault || pDefArg->pDefault->pVm != pVm))) { rc = PH7_CORRUPT; goto Fail; } - for(j = 0; j < SySetUsed(&pMeth->sFunc.aArgs); j++) { - ph7_vm_func_arg *pOther = (ph7_vm_func_arg *)SySetAt(&pMeth->sFunc.aArgs, j); - if(pOther->sName.nByte == SyStrlen(pDefArg->zName) && - SyMemcmp(pOther->sName.zString, pDefArg->zName, pOther->sName.nByte) == 0) { - rc = PH7_CORRUPT; - goto Fail; - } - } SyZero(&sArg, sizeof(sArg)); + sArg.iFlags = pDefArg->iFlags & PH7_PARAM_REF ? VM_FUNC_ARG_BY_REF : 0; + sArg.xNativeDefault = pDefArg->xDefault; + sArg.pNativeData = pDefArg->pDefaultData; SySetInit(&sArg.aByteCode, &pVm->sAllocator, sizeof(VmInstr)); rc = VmNativeType(pVm, pClass, &pDefArg->sType, &sArg.nType); if(rc != SXRET_OK) { @@ -1805,6 +1929,19 @@ PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef SyMemBackendFree(&pVm->sAllocator, zName); goto Fail; } + if(pDefArg->pDefault) { + ph7_vm_func_arg *pArg = (ph7_vm_func_arg *)SySetPeek(&pMeth->sFunc.aArgs); + pArg->pNativeDefault = (ph7_value *)SyMemBackendPoolAlloc(&pVm->sAllocator, sizeof(ph7_value)); + if(pArg->pNativeDefault == 0) { + rc = PH7_NOMEM; + goto Fail; + } + PH7_MemObjInit(pVm, pArg->pNativeDefault); + rc = PH7_MemObjSnapshot((ph7_value *)pDefArg->pDefault, pArg->pNativeDefault); + if(rc != SXRET_OK) { + goto Fail; + } + } } SyHashResetLoopCursor(&pClass->hMethod); while((pEntry = SyHashGetNextEntry(&pClass->hMethod)) != 0) { @@ -1815,72 +1952,61 @@ PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef } } } - /* Storage is prepared before the class becomes visible to the program. */ - SyHashResetLoopCursor(&pClass->hAttr); - while((pEntry = SyHashGetNextEntry(&pClass->hAttr)) != 0) { - ph7_class_attr *pAttr = (ph7_class_attr *)pEntry->pUserData; - if(pAttr->iFlags & (PH7_CLASS_ATTR_STATIC | PH7_CLASS_ATTR_CONSTANT)) { - ph7_value *pValue = PH7_ReserveMemObj(pVm); - if(pValue == 0) { - rc = PH7_NOMEM; - goto Fail; - } - pAttr->nIdx = pValue->nIdx; - if(pAttr->pNativeInitial) { - rc = PH7_MemObjSnapshot(pAttr->pNativeInitial, pValue); - if(rc != SXRET_OK) { - goto Fail; - } - pValue = (ph7_value *)SySetAt(&pVm->aMemObj, pAttr->nIdx); - } else { - MemObjSetType(pValue, (pAttr->nType & MEMOBJ_TYPEMASK)); - if(pAttr->nType & MEMOBJ_HASHMAP) { - pValue->x.pOther = PH7_NewHashmap(pVm, 0, 0); - if(pValue->x.pOther == 0) { - rc = PH7_NOMEM; - goto Fail; - } - } - } - rc = PH7_MemObjDeclareType(pValue, pAttr->nType, FALSE); - if(rc != SXRET_OK) { - goto Fail; - } - rc = PH7_VmRefObjInstall(pVm, pAttr->nIdx, 0, 0, VM_REF_IDX_KEEP); - if(rc != SXRET_OK) { - goto Fail; - } - } + rc = PH7_ClassPrepareNative(pVm, pClass); + if(rc != SXRET_OK) { + rc = rc == SXERR_MEM ? PH7_NOMEM : PH7_CORRUPT; + goto Fail; } SyHashResetLoopCursor(&pClass->hMethod); while((pEntry = SyHashGetNextEntry(&pClass->hMethod)) != 0) { ph7_class_method *pMeth = (ph7_class_method *)pEntry->pUserData; - rc = PH7_VmInstallUserFunction(pVm, &pMeth->sFunc, &pMeth->sVmName); - if(rc != SXRET_OK) { - goto Fail; + if(pMeth->sFunc.pClass != pClass || (pClass->iFlags & PH7_CLASS_INTERFACE) || + (pMeth->iFlags & PH7_CLASS_ATTR_VIRTUAL)) { + continue; + } + { + SyHashEntry *pInstalled = SyHashGet(&pVm->hFunction, + pMeth->sVmName.zString, pMeth->sVmName.nByte); + if(pInstalled && ((ph7_vm_func *)pInstalled->pUserData)->pClass != pClass) { + rc = PH7_CORRUPT; + goto Fail; + } } } rc = SyHashInsert(&pVm->hClass, pClass->sName.zString, pClass->sName.nByte, pClass); if(rc == SXRET_OK) { - SyMemBackendFree(&pVm->sAllocator, aFree); return PH7_OK; } Fail: VmNativeClassFree(pVm, pClass); - while(SySetUsed(&pVm->aTypeNames) > nTypes) { - SyString *pName = (SyString *)SySetPop(&pVm->aTypeNames); - SyMemBackendFree(&pVm->sAllocator, (void *)pName->zString); + /* Owned snapshots release only their own indexed slots. Never truncate + * shared arenas/interner tables or restore an earlier global free list. + * Immutable nominal intern entries remain reusable VM cache entries. */ + return rc; +} +PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef) { + sxi32 rc; + if(pVm->bNativeRegister) { + return SXERR_LOCKED; } - /* Rollback must not allocate, including restoring reusable arena slots. */ - for(n = nMem; n < SySetUsed(&pVm->aMemObj); n++) { - PH7_MemObjRelease((ph7_value *)SySetAt(&pVm->aMemObj, n)); + pVm->bNativeRegister = TRUE; + pVm->nNativeReserve = 0; + rc = VmPrepareNativeClass(pVm, pDef); + if(rc == SXRET_OK) { + SyHashEntry *pEntry = SyHashGet(&pVm->hClass, pDef->zName, SyStrlen(pDef->zName)); + ph7_class *pClass = (ph7_class *)pEntry->pUserData; + sxu32 nWarning = pClass->nNativeWarnings; + static const char zWarning[] = "Warning: " PH7_INTERFACE_VISIBILITY_ERROR "\n"; + pClass->nNativeWarnings = 0; + /* A warning is a post-commit compiler diagnostic, not an initializer. + * No formatter allocation or rollback follows the notification; VM + * execution/release stays locked until registration returns. */ + while(nWarning-- && pVm->pEngine->xConf.xErr) { + pVm->pEngine->xConf.xErr(zWarning, sizeof(zWarning) - 1, pVm->pEngine->xConf.pErrData); + } } - pVm->aMemObj.nUsed = nMem; - if(nFree) { - SyMemcpy(aFree, SySetBasePtr(&pVm->aFreeObj), nFree * sizeof(VmSlot)); - } - pVm->aFreeObj.nUsed = nFree; - SyMemBackendFree(&pVm->sAllocator, aFree); + pVm->bNativeRegister = FALSE; + pVm->nNativeReserve = 0; return rc; } /* @@ -1895,23 +2021,28 @@ static sxi32 VmMountUserClass( ph7_class_attr *pAttr; SyHashEntry *pEntry; sxi32 rc; - if(pClass->bNative) { - /* Registered classes already own their storage and overload chain. */ + if(pClass->bMounting) { return SXRET_OK; } + pClass->bMounting = TRUE; /* Reset the loop cursor */ SyHashResetLoopCursor(&pClass->hAttr); /* Process only static and constant attribute */ while((pEntry = SyHashGetNextEntry(&pClass->hAttr)) != 0) { /* Extract the current attribute */ pAttr = (ph7_class_attr *)pEntry->pUserData; - if((pAttr->iFlags & (PH7_CLASS_ATTR_CONSTANT | PH7_CLASS_ATTR_STATIC)) && pAttr->nIdx == SXU32_HIGH) { + if(pAttr->pClass == pClass && + (pAttr->iFlags & (PH7_CLASS_ATTR_CONSTANT | PH7_CLASS_ATTR_STATIC)) && pAttr->nIdx == SXU32_HIGH) { /* Static/constant storage belongs to the declaring declaration and * is mounted only once, even when the class is mounted again. */ ph7_value *pMemObj, sResult; sxu32 nObjIdx; /* Reserve a memory object for this constant/static attribute */ PH7_VmTypeClass(pVm, pAttr->nType, TRUE); + if(pVm->iPendingTransfer) { + pClass->bMounting = FALSE; + return pVm->iPendingTransfer; + } pMemObj = PH7_ReserveMemObj(&(*pVm)); PH7_MemObjInit(pVm, &sResult); if(pMemObj == 0) { @@ -1920,9 +2051,19 @@ static sxi32 VmMountUserClass( nObjIdx = pMemObj->nIdx; MemObjSetType(pMemObj, (pAttr->nType & MEMOBJ_TYPEMASK)); PH7_MemObjSetDeclaredType(pMemObj, pAttr->nType); - if(SySetUsed(&pAttr->aByteCode) > 0) { + if(SySetUsed(&pAttr->aByteCode) > 0 || pAttr->xNativeInitial || pAttr->pNativeInitial) { + SyHashEntry_Pr *pCursor = pClass->hAttr.pCurrent; /* Initialize attribute default value (any complex expression) */ - VmLocalExec(&(*pVm), &pAttr->aByteCode, &sResult); + rc = VmEvalInitializer(pVm, &pAttr->aByteCode, pAttr->pNativeInitial, + pAttr->xNativeInitial, pAttr->pNativeData, &sResult); + pClass->hAttr.pCurrent = pCursor; + if(rc != SXRET_OK) { + PH7_VmDeferTransfer(pVm, rc, &sResult); + PH7_MemObjRelease(&sResult); + PH7_VmDestroyMemObj(pVm, (ph7_value *)SySetAt(&pVm->aMemObj, nObjIdx)); + pClass->bMounting = FALSE; + return rc; + } pMemObj = (ph7_value *)SySetAt(&pVm->aMemObj, nObjIdx); rc = PH7_MemObjSafeStore(&sResult, pMemObj); pMemObj = (ph7_value *)SySetAt(&pVm->aMemObj, nObjIdx); @@ -1947,9 +2088,10 @@ static sxi32 VmMountUserClass( } } /* Install class methods */ - if(pClass->iFlags & PH7_CLASS_INTERFACE) { + if(pClass->bMethodsMounted || (pClass->iFlags & PH7_CLASS_INTERFACE)) { /* Do not mount interface methods since they are signatures only. */ + pClass->bMounting = FALSE; return SXRET_OK; } /* Install the methods now */ @@ -1959,12 +2101,36 @@ static sxi32 VmMountUserClass( if(pMeth->sFunc.pClass == pClass && (pMeth->iFlags & PH7_CLASS_ATTR_VIRTUAL) == 0) { rc = PH7_VmInstallUserFunction(&(*pVm), &pMeth->sFunc, &pMeth->sVmName); if(rc != SXRET_OK) { + pClass->bMounting = FALSE; return rc; } } } + pClass->bMethodsMounted = TRUE; + pClass->bMounting = FALSE; return SXRET_OK; } +static sxi32 VmMountNativeClasses(ph7_vm *pVm) { + SyHashEntry *pEntry; + sxu32 nClass; + sxi32 rc = SXRET_OK; + do { + nClass = SyHashTotalEntry(&pVm->hClass); + SyHashResetLoopCursor(&pVm->hClass); + while((pEntry = SyHashGetNextEntry(&pVm->hClass)) != 0) { + ph7_class *pClass = (ph7_class *)pEntry->pUserData; + SyHashEntry_Pr *pCursor = pVm->hClass.pCurrent; + if(pClass->bNative) { + rc = VmMountUserClass(pVm, pClass); + } + pVm->hClass.pCurrent = pCursor; + if(rc != SXRET_OK) { + return rc; + } + } + } while(nClass != SyHashTotalEntry(&pVm->hClass)); + return rc; +} /* * Allocate a private frame for attributes of the given * class instance (Object in the PHP jargon). @@ -1994,6 +2160,10 @@ PH7_PRIVATE sxi32 PH7_VmCreateClassInstanceFrame( sxu32 nObjIdx; /* Reserve a memory object for this attribute */ PH7_VmTypeClass(pVm, pAttr->nType, TRUE); + if(pVm->iPendingTransfer) { + SyMemBackendPoolFree(&pVm->sAllocator, pVmAttr); + return PH7_VmTakeTransfer(pVm, pResult); + } pMemObj = PH7_ReserveMemObj(&(*pVm)); if(pMemObj == 0) { SyMemBackendPoolFree(&pVm->sAllocator, pVmAttr); @@ -2003,15 +2173,12 @@ PH7_PRIVATE sxi32 PH7_VmCreateClassInstanceFrame( MemObjSetType(pMemObj, (pAttr->nType & MEMOBJ_TYPEMASK)); PH7_MemObjSetDeclaredType(pMemObj, pAttr->nType); PH7_MemObjInit(pVm, &sValue); - if(pAttr->pNativeInitial) { - rc = PH7_MemObjSafeStore(pAttr->pNativeInitial, pMemObj); - pMemObj = (ph7_value *)SySetAt(&pVm->aMemObj, nObjIdx); - if(rc != SXRET_OK) { - PH7_VmThrowError(pVm, PH7_CTX_ERR, "Cannot assign a value of incompatible type to variable '%z::$%z'", &pClass->sName, &pAttr->sName); - } - } else if(SySetUsed(&pAttr->aByteCode) > 0) { + if(pAttr->pNativeInitial || pAttr->xNativeInitial || SySetUsed(&pAttr->aByteCode) > 0) { + SyHashEntry_Pr *pCursor = pClass->hAttr.pCurrent; /* Initialize attribute default value (any complex expression) */ - rc = VmLocalExec(&(*pVm), &pAttr->aByteCode, &sValue); + rc = VmEvalInitializer(pVm, &pAttr->aByteCode, pAttr->pNativeInitial, + pAttr->xNativeInitial, pAttr->pNativeData, &sValue); + pClass->hAttr.pCurrent = pCursor; pMemObj = (ph7_value *)SySetAt(&pVm->aMemObj, nObjIdx); if(rc != SXRET_OK) { if(rc == PH7_EXCEPTION && pResult) { @@ -2024,6 +2191,13 @@ PH7_PRIVATE sxi32 PH7_VmCreateClassInstanceFrame( } rc = PH7_MemObjSafeStore(&sValue, pMemObj); pMemObj = (ph7_value *)SySetAt(&pVm->aMemObj, nObjIdx); + if(pVm->iPendingTransfer) { + rc = PH7_VmTakeTransfer(pVm, pResult); + PH7_MemObjRelease(&sValue); + PH7_VmDestroyMemObj(pVm, pMemObj); + SyMemBackendPoolFree(&pVm->sAllocator, pVmAttr); + return rc; + } if(rc != SXRET_OK) { PH7_VmThrowError(&(*pVm), PH7_CTX_ERR, "Cannot assign a value of incompatible type to variable '%z::$%z'", &pClass->sName, &pAttr->sName); } @@ -2065,7 +2239,6 @@ PH7_PRIVATE sxi32 PH7_VmCreateClassInstanceFrame( return SXRET_OK; } /* Forward declaration */ -static VmRefObj *VmRefObjExtract(ph7_vm *pVm, sxu32 nObjIdx); /* A recursive array may change node shape, but not through another alias * while that node is bound to a typed reference or retained by a capture. */ PH7_PRIVATE sxi32 PH7_VmRefTypeCompatible(ph7_value *pStorage, sxu32 nType) { @@ -2108,7 +2281,8 @@ static void VmClosureEnvRelease(ph7_vm *pVm, ph7_vm_func *pClosure) { for(n = 0; n < SySetUsed(&pClosure->aClosureEnv); n++) { if(aEnv[n].nIdx != SXU32_HIGH) { VmRefObj *pRef = VmRefObjExtract(pVm, aEnv[n].nIdx); - if(pRef && --pRef->nCapture == 0 && (pRef->iFlags & VM_REF_CAPTURE_RETIRED)) { + if(pRef && --pRef->nCapture == 0 && pRef->nBorrow == 0 && + (pRef->iFlags & VM_REF_CAPTURE_RETIRED)) { PH7_VmUnsetMemObj(pVm, aEnv[n].nIdx, FALSE); } } else { @@ -2350,6 +2524,7 @@ PH7_PRIVATE sxi32 PH7_VmInit( PH7_MemObjInit(&(*pVm), &pVm->aExceptionCB[0]); PH7_MemObjInit(&(*pVm), &pVm->aExceptionCB[1]); PH7_MemObjInit(&(*pVm), &pVm->sAssertCallback); + PH7_MemObjInit(pVm, &pVm->sPendingTransfer); /* Default assertion flags */ pVm->iAssertFlags = PH7_ASSERT_WARNING; /* Issue a warning for each failed assertion */ /* JSON return status */ @@ -2460,11 +2635,17 @@ static ph7_value *VmNewOperandStack( static sxi32 VmRegisterSpecialFunction(ph7_vm *pVm); /* Shared by bytecode returns and native methods, after ordinary argument prep. */ static void VmCheckMissingReturn(ph7_vm *pVm, ph7_vm_func *pFunc) { + if(pVm->iPendingTransfer) { + return; + } if(pFunc->nType && (pFunc->nType & MEMOBJ_VOID) == 0) { PH7_VmThrowError(pVm, PH7_CTX_WARNING, "Missing return value in closure/method returning non-void"); } } static void VmCheckReturn(ph7_vm *pVm, ph7_vm_func *pFunc, ph7_value *pValue) { + if(pVm->iPendingTransfer) { + return; + } if(pFunc->nType & MEMOBJ_NAMED) { PH7_VmTypeClass(pVm, pFunc->nType, TRUE); if(PH7_VmTypeCheck(pValue, pFunc->nType) != SXRET_OK) { @@ -2559,18 +2740,22 @@ PH7_PRIVATE sxi32 PH7_VmMakeReady( /* Initialize and install static and constants class attributes */ SyHashResetLoopCursor(&pVm->hClass); while((pEntry = SyHashGetNextEntry(&pVm->hClass)) != 0) { + SyHashEntry_Pr *pCursor = pVm->hClass.pCurrent; rc = VmMountUserClass(&(*pVm), (ph7_class *)pEntry->pUserData); + pVm->hClass.pCurrent = pCursor; if(rc != SXRET_OK) { return rc; } } /* VM is ready for bytecode execution */ - return SXRET_OK; + return VmMountNativeClasses(pVm); } /* * Reset a Virtual Machine to it's initial state. */ PH7_PRIVATE sxi32 PH7_VmReset(ph7_vm *pVm) { + pVm->iPendingTransfer = 0; + PH7_MemObjRelease(&pVm->sPendingTransfer); if(pVm->nMagic != PH7_VM_RUN && pVm->nMagic != PH7_VM_EXEC && pVm->nMagic != PH7_VM_INCL) { return SXERR_CORRUPT; } @@ -2627,6 +2812,23 @@ static void VmFinalizeObjects(ph7_vm *pVm) { } pClass->hAttr.pCurrent = pNextAttr; } + /* hMethod contains every overload, including unmounted signatures. + * Inherited entries borrow the declaring method and its defaults. */ + SyHashResetLoopCursor(&pClass->hMethod); + while((pAttrEntry = SyHashGetNextEntry(&pClass->hMethod)) != 0) { + ph7_class_method *pMeth = (ph7_class_method *)pAttrEntry->pUserData; + SyHashEntry_Pr *pNextMethod = pClass->hMethod.pCurrent; + if(pMeth->sFunc.pClass == pClass) { + for(n = 0; n < SySetUsed(&pMeth->sFunc.aArgs); n++) { + ph7_vm_func_arg *pArg = (ph7_vm_func_arg *)SySetAt(&pMeth->sFunc.aArgs, n); + ph7_value *pDefault = pArg->pNativeDefault; + if(pDefault && (pDefault->nType & (MEMOBJ_OBJ | MEMOBJ_HASHMAP)) == MEMOBJ_OBJ) { + nFinalized |= PH7_ClassInstanceFinalize((ph7_class_instance *)pDefault->x.pOther); + } + } + } + pClass->hMethod.pCurrent = pNextMethod; + } pVm->hClass.pCurrent = pNextClass; } /* Reacquire indexed values: a destructor may grow aMemObj. Arrays and @@ -2666,6 +2868,25 @@ PH7_PRIVATE sxi32 PH7_VmRelease(ph7_vm *pVm) { pAttr->pNativeInitial = 0; } } + /* Release only owned parameter snapshots, once for each overload. + * Array payloads must go before the indexed sweep, and object callbacks + * were drained above while their declaring modules were still loaded. */ + SyHashResetLoopCursor(&pClass->hMethod); + while((pAttrEntry = SyHashGetNextEntry(&pClass->hMethod)) != 0) { + ph7_class_method *pMeth = (ph7_class_method *)pAttrEntry->pUserData; + sxu32 n; + if(pMeth->sFunc.pClass != pClass) { + continue; + } + for(n = 0; n < SySetUsed(&pMeth->sFunc.aArgs); n++) { + ph7_vm_func_arg *pArg = (ph7_vm_func_arg *)SySetAt(&pMeth->sFunc.aArgs, n); + if(pArg->pNativeDefault) { + PH7_MemObjRelease(pArg->pNativeDefault); + SyMemBackendPoolFree(&pVm->sAllocator, pArg->pNativeDefault); + pArg->pNativeDefault = 0; + } + } + } } /* Captures have the same lifetime as installed runtime closures. Release * them while indexed storage and reference bookkeeping are still valid. */ @@ -2697,6 +2918,8 @@ PH7_PRIVATE sxi32 PH7_VmRelease(ph7_vm *pVm) { SySetRelease(&pVm->aModules); SySetRelease(&pVm->aModuleHandles); SyBlobRelease(&pVm->sArgvEntries); + pVm->iPendingTransfer = 0; + PH7_MemObjRelease(&pVm->sPendingTransfer); /* Release the private memory subsystem */ SyMemBackendRelease(&pVm->sAllocator); return SXRET_OK; @@ -2728,6 +2951,7 @@ static sxi32 VmInitCallContext( pOut->iFlags = iFlags; pOut->pThis = 0; pOut->bResultSet = FALSE; + pOut->pNativeFrame = 0; return SXRET_OK; } /* @@ -2765,7 +2989,67 @@ static void VmReleaseCallContext(ph7_context *pCtx) { SySetRelease(&pCtx->sChunk); } } -/* Borrowed wrappers stay stable even if callback allocations grow aMemObj. */ +static void VmCheckNativeCompletion(ph7_vm *pVm, const SyString *pName, sxi32 rc) { + if(rc == SXERR_MEM) { + PH7_VmMemoryError(pVm); + } else if(rc != PH7_OK && rc != PH7_ABORT && rc != PH7_EXCEPTION) { + PH7_VmThrowError(pVm, PH7_CTX_ERR, "Native callback '%z()' returned invalid completion status %d", pName, rc); + } +} +PH7_PRIVATE void PH7_VmDeferTransfer(ph7_vm *pVm, sxi32 rc, ph7_value *pValue) { + if((rc == PH7_EXCEPTION || rc == PH7_ABORT) && pVm->iPendingTransfer == 0) { + pVm->iPendingTransfer = rc; + if(rc == PH7_EXCEPTION && pValue) { + PH7_MemObjStore(pValue, &pVm->sPendingTransfer); + } + } +} +PH7_PRIVATE sxi32 PH7_VmTakeTransfer(ph7_vm *pVm, ph7_value *pResult) { + sxi32 rc = pVm->iPendingTransfer; + if(rc) { + pVm->iPendingTransfer = 0; + if(rc == PH7_EXCEPTION && pResult) { + PH7_MemObjStore(&pVm->sPendingTransfer, pResult); + } + PH7_MemObjRelease(&pVm->sPendingTransfer); + } + return rc; +} +static sxi32 VmEvalInitializer(ph7_vm *pVm, SySet *pCode, ph7_value *pSnapshot, + ph7_initializer_func xEval, void *pData, ph7_value *pResult) { + if(pVm->iPendingTransfer) { + return PH7_VmTakeTransfer(pVm, pResult); + } + if(xEval) { + ph7_context sCtx; + ph7_user_func sFunc; + ph7_value sThis; + sxi32 rc; + SyZero(&sFunc, sizeof(sFunc)); + sFunc.pUserData = pData; + SyStringInitFromBuf(&sFunc.sName, "[initializer]", sizeof("[initializer]") - 1); + VmInitCallContext(&sCtx, pVm, &sFunc, pResult, 0); + sCtx.pNativeFrame = pVm->pFrame; + PH7_MemObjInit(pVm, &sThis); + if(pVm->pFrame && pVm->pFrame->pThis) { + sThis.x.pOther = pVm->pFrame->pThis; + MemObjSetType(&sThis, MEMOBJ_OBJ); + sCtx.pThis = &sThis; + } + rc = xEval(&sCtx); + VmReleaseCallContext(&sCtx); + if(pVm->iPendingTransfer) { + rc = PH7_VmTakeTransfer(pVm, pResult); + } + VmCheckNativeCompletion(pVm, &sFunc.sName, rc); + return rc; + } + if(pSnapshot) { + return PH7_MemObjLoad(pSnapshot, pResult); + } + return VmLocalExec(pVm, pCode, pResult); +} +/* Owned argv snapshots stay stable across binding writes and arena growth. */ static sxi32 VmCallNativeMethod(ph7_vm *pVm, ph7_vm_func *pFunc, VmFrame *pFrame, ph7_class_instance *pThis, ph7_value *pResult) { ph7_context sCtx; @@ -2773,6 +3057,9 @@ static sxi32 VmCallNativeMethod(ph7_vm *pVm, ph7_vm_func *pFunc, ph7_value *aValue, **apArg; sxu32 n, nArg = SySetUsed(&pFrame->sArg); sxi32 rc; + if(pVm->iPendingTransfer) { + return PH7_VmTakeTransfer(pVm, pResult); + } aValue = (ph7_value *)SyMemBackendAlloc(&pVm->sAllocator, (nArg ? nArg : 1) * (sizeof(ph7_value) + sizeof(ph7_value *))); if(aValue == 0) { @@ -2783,7 +3070,17 @@ static sxi32 VmCallNativeMethod(ph7_vm *pVm, ph7_vm_func *pFunc, for(n = 0; n < nArg; n++) { VmSlot *pSlot = (VmSlot *)SySetAt(&pFrame->sArg, n); PH7_MemObjInit(pVm, &aValue[n]); - PH7_MemObjLoad((ph7_value *)SySetAt(&pVm->aMemObj, pSlot->nIdx), &aValue[n]); + /* Own strings and array contents across binding writes and VM reentry. + * Snapshot retains object identity, just like an ordinary value copy. */ + rc = PH7_MemObjSnapshot((ph7_value *)SySetAt(&pVm->aMemObj, pSlot->nIdx), &aValue[n]); + if(rc != SXRET_OK) { + do { + PH7_MemObjRelease(&aValue[n]); + } while(n-- > 0); + SyMemBackendFree(&pVm->sAllocator, aValue); + PH7_VmMemoryError(pVm); + return PH7_ABORT; + } apArg[n] = &aValue[n]; } PH7_MemObjInit(pVm, &sThis); @@ -2793,9 +3090,14 @@ static sxi32 VmCallNativeMethod(ph7_vm *pVm, ph7_vm_func *pFunc, /* Borrowed: the active frame already retains the instance. */ } VmInitCallContext(&sCtx, pVm, &pFunc->sNative, pResult, 0); + sCtx.pNativeFrame = pFrame; sCtx.pThis = pThis && (((ph7_class_method *)pFunc)->iFlags & PH7_CLASS_ATTR_STATIC) == 0 ? &sThis : 0; rc = pFunc->sNative.xFunc(&sCtx, (int)nArg, apArg); VmReleaseCallContext(&sCtx); + if(pVm->iPendingTransfer) { + rc = PH7_VmTakeTransfer(pVm, pResult); + } + VmCheckNativeCompletion(pVm, &pFunc->sName, rc); for(n = 0; n < nArg; n++) { PH7_MemObjRelease(&aValue[n]); } @@ -2860,6 +3162,33 @@ PH7_PRIVATE ph7_value *PH7_ReserveMemObj(ph7_vm *pVm) { ph7_value *pObj = 0; VmSlot *pSlot; sxu32 nIdx; + if(pVm->bNativeRegister) { + sxu32 nFree = SySetUsed(&pVm->aFreeObj); + sxu32 nNeed, nCapacity = pVm->aFreeObj.nSize; + void *pNew; + if(pVm->nNativeReserve >= SXI32_HIGH - nFree - 1) { + return 0; + } + nNeed = nFree + pVm->nNativeReserve + 1; + if(nNeed > nCapacity) { + nCapacity = nCapacity ? nCapacity : 8; + while(nCapacity < nNeed && nCapacity <= SXI32_HIGH / (2 * sizeof(VmSlot))) { + nCapacity *= 2; + } + if(nCapacity < nNeed) { + return 0; + } + pNew = SyMemBackendRealloc(&pVm->sAllocator, pVm->aFreeObj.pBase, + nCapacity * sizeof(VmSlot)); + if(pNew == 0) { + return 0; + } + pVm->aFreeObj.pBase = pNew; + pVm->aFreeObj.nSize = nCapacity; + } + /* Releasing every owned snapshot during rollback must not allocate. */ + pVm->nNativeReserve++; + } /* Check for a free slot */ nIdx = SXU32_HIGH; /* cc warning */ pSlot = (VmSlot *)SySetPop(&pVm->aFreeObj); @@ -2933,6 +3262,26 @@ static ph7_value *VmCreateMemObj( pObj->nIdx = nIdx; return pObj; } +/* Duplicate formal identifiers are accepted by the parser. The first named + * binding remains visible, but every positional argument still owns a slot. */ +static ph7_value *VmCreateArgument(ph7_vm *pVm, const SyString *pName) { + ph7_value *pValue = VmCreateMemObj(pVm, pName, FALSE); + VmSlot sSlot; + if(pValue) { + return pValue; + } + pValue = PH7_ReserveMemObj(pVm); + if(pValue == 0) { + PH7_VmMemoryError(pVm); + } + sSlot.nIdx = pValue->nIdx; + sSlot.pUserData = 0; + if(SySetPut(&pVm->pFrame->sLocal, &sSlot) != SXRET_OK || + PH7_VmRefObjInstall(pVm, sSlot.nIdx, 0, 0, 0) != SXRET_OK) { + PH7_VmMemoryError(pVm); + } + return (ph7_value *)SySetAt(&pVm->aMemObj, sSlot.nIdx); +} /* * Extract a variable value from the top active VM frame. * Return a pointer to the variable value on success. @@ -2994,6 +3343,21 @@ static ph7_value *VmExtractMemObj( } return pObj; } +PH7_PRIVATE sxi32 PH7_VmContextVar(ph7_context *pCtx, const char *zName, + ph7_value *pValue, sxi32 bStore) { + SyString sName; + ph7_value *pStorage; + if(pCtx == 0 || pValue == 0 || pValue->pVm != pCtx->pVm || + !PH7_IsIdentifier(zName, TRUE)) { + return PH7_CORRUPT; + } + SyStringInitFromBuf(&sName, zName, SyStrlen(zName)); + pStorage = VmExtractMemObj(pCtx->pVm, &sName, FALSE); + if(pStorage == 0) { + return PH7_CORRUPT; + } + return bStore ? PH7_MemObjSafeStore(pValue, pStorage) : PH7_MemObjCopy(pStorage, pValue); +} /* * Extract a superglobal variable such as $_GET,$_POST,$_HEADERS,.... * Return a pointer to the variable value on success.NULL otherwise. @@ -3370,6 +3734,9 @@ PH7_PRIVATE sxi32 PH7_VmThrowError( ) { const char *zErr; sxi32 rc = SXRET_OK; + if(pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } switch(iErr) { case PH7_CTX_WARNING: zErr = "Warning: "; @@ -3504,6 +3871,9 @@ static sxi32 VmByteCodeExec( ph7_value sTransfer; SySet aRegion; sxbool bScopeStopped = FALSE; + if(pVm->bNativeRegister) { + return SXERR_LOCKED; + } VmFrame *pEntryFrame = pVm->pFrame; /* Argument container */ SySetInit(&aArg, &pVm->sAllocator, sizeof(ph7_value *)); @@ -3524,6 +3894,9 @@ Resume: } /* Fetch the instruction to execute */ pInstr = &aInstr[pc]; + if(pVm->iPendingTransfer) { + goto Unwind; + } /* LF_STOP's following transfer must not recreate the released iteration * scope. Other jumps also reconcile their source, including jump chains * that leave and immediately reenter a block without executing its end. */ @@ -3890,6 +4263,9 @@ Resume: pClass = PH7_VmExtractClass(&(*pVm), (const char *)SyBlobData(&pTos->sBlob), SyBlobLength(&pTos->sBlob), FALSE); } + if(pVm->iPendingTransfer) { + goto Unwind; + } if(pClass == 0) { PH7_VmThrowError(&(*pVm), PH7_CTX_ERR, "The type or class name could not be found"); @@ -4468,6 +4844,14 @@ Resume: /* Force a string cast */ PH7_MemObjToString(pTos); } + if(pVm->iPendingTransfer) { + if(pKey) { + PH7_MemObjRelease(pKey); + } + break; + } + /* The conversion may have reentered and grown aMemObj. */ + pObj = (ph7_value *)SySetAt(&pVm->aMemObj, nIdx); if(pKey == 0) { /* Append string */ if(SyBlobLength(&pTos->sBlob) > 0) { @@ -5754,6 +6138,13 @@ Resume: PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot register module '%z'", &pModule.sName); } } + rc = VmMountNativeClasses(pVm); + if(rc == SXERR_MEM) { + PH7_VmMemoryError(pVm); + } + if(rc == PH7_ABORT) { + goto Abort; + } break; } /* @@ -5843,7 +6234,13 @@ Resume: ph7_class_info *pClassInfo = (ph7_class_info *)pInstr->p3; ph7_class *pClass = PH7_VmExtractClass(pVm, pClassInfo->sName.zString, pClassInfo->sName.nByte, FALSE); ph7_class *pBase = 0; + if(pVm->iPendingTransfer) { + goto Unwind; + } rc = PH7_ClassBuildMro(pVm, pClass); + if(pVm->iPendingTransfer) { + goto Unwind; + } if(rc != SXRET_OK) { goto Abort; } @@ -5863,6 +6260,9 @@ Resume: SyString *apImplements; while(SySetGetNextEntry(&pClassInfo->sImplements, (void **)&apImplements) == SXRET_OK) { pBase = PH7_VmExtractClass(pVm, apImplements->zString, apImplements->nByte, FALSE); + if(pVm->iPendingTransfer) { + goto Unwind; + } if(pBase == 0) { /* Non-existent interface */ PH7_VmThrowError(&(*pVm), PH7_CTX_ERR, "Call to non-existent interface '%z'", &apImplements->zString); @@ -5888,11 +6288,17 @@ Resume: ph7_class_info *pClassInfo = (ph7_class_info *)pInstr->p3; ph7_class *pClass = PH7_VmExtractClass(pVm, pClassInfo->sName.zString, pClassInfo->sName.nByte, FALSE); ph7_class *pBase = 0; + if(pVm->iPendingTransfer) { + goto Unwind; + } if(pInstr->iP1) { /* This interface inherits from other interface */ SyString *apExtends; while(SySetGetNextEntry(&pClassInfo->sExtends, (void **)&apExtends) == SXRET_OK) { pBase = PH7_VmExtractClass(pVm, apExtends->zString, apExtends->nByte, FALSE); + if(pVm->iPendingTransfer) { + goto Unwind; + } if(pBase == 0) { /* Non-existent base interface */ PH7_VmThrowError(&(*pVm), PH7_CTX_ERR, "Call to non-existent base interface '%z'", &apExtends->zString); @@ -6152,6 +6558,9 @@ Resume: if(SyBlobLength(&pNos->sBlob) > 0) { pClass = PH7_VmExtractClass(&(*pVm), (const char *)SyBlobData(&pNos->sBlob), SyBlobLength(&pNos->sBlob), FALSE); + if(pVm->iPendingTransfer) { + goto Unwind; + } } } if(pClass == 0) { @@ -6271,6 +6680,9 @@ Resume: /* Try to extract the desired class */ pClass = PH7_VmExtractClass(&(*pVm), (const char *)SyBlobData(&pTos->sBlob), SyBlobLength(&pTos->sBlob), FALSE); + if(pVm->iPendingTransfer) { + goto Unwind; + } } else if(pTos->nType & MEMOBJ_OBJ) { /* Take the base class from the loaded instance */ pClass = ((ph7_class_instance *)pTos->x.pOther)->pClass; @@ -6297,7 +6709,7 @@ Resume: SySetPut(&aArg, (const void *)&pArg); pArg++; } - rc = VmCallClassMethod(&(*pVm), pNew, pCons, &sTransfer, (int)SySetUsed(&aArg), (ph7_value **)SySetBasePtr(&aArg), FALSE); + rc = VmCallClassMethod(&(*pVm), pNew, pCons, &sTransfer, (int)SySetUsed(&aArg), (ph7_value **)SySetBasePtr(&aArg), FALSE, FALSE); /* TICKET 1433-52: Unsetting $this in the constructor body */ if(pNew->iRef < 1) { pNew->iRef = 1; @@ -6446,7 +6858,52 @@ Resume: SyString sName; /* Extract function name */ /* Synthetic calls have no preceding instruction at pc == 0. */ - if((pTos->nType & (MEMOBJ_OBJ | MEMOBJ_HASHMAP)) == MEMOBJ_OBJ) { + if(pTos->nType & MEMOBJ_HASHMAP) { + ph7_hashmap *pMap = (ph7_hashmap *)pTos->x.pOther; + ph7_value sTarget, sMethod; + ph7_class *pClass = 0; + ph7_class_method *pMeth = 0; + PH7_MemObjInit(pVm, &sTarget); + PH7_MemObjInit(pVm, &sMethod); + if(pMap && pMap->nEntry == 2) { + PH7_MemObjStore((ph7_value *)SySetAt(&pVm->aMemObj, + pMap->pFirst->nValIdx), &sTarget); + PH7_MemObjStore((ph7_value *)SySetAt(&pVm->aMemObj, + pMap->pFirst->pPrev->nValIdx), &sMethod); + if(!(sTarget.nType & MEMOBJ_OBJ) || sTarget.x.pOther) { + pClass = VmExtractClassFromValue(pVm, &sTarget); + } + if(pClass) { + pClass = PH7_VmExtractClass(pVm, pClass->sName.zString, + pClass->sName.nByte, FALSE); + } + if(pClass && (sMethod.nType & MEMOBJ_STRING)) { + SyStringInitFromBuf(&sName, SyBlobData(&sMethod.sBlob), SyBlobLength(&sMethod.sBlob)); + pMeth = VmMethodSeed(pVm, pClass, &sName, 0, FALSE); + } + } + if(pMeth) { + /* Normalize once into the ordinary receiver/name CALL + * representation. Source and native reentry share this + * path, including lexical private lookup and __invoke. */ + PH7_MemObjRelease(pTos); + PH7_MemObjStore(&sTarget, pTos); + pTos->nIdx = SXU32_HIGH; + pTos++; + SyBlobAppend(&pTos->sBlob, pMeth->sVmName.zString, pMeth->sVmName.nByte); + MemObjSetType(pTos, MEMOBJ_STRING); + pTos->nIdx = SXU32_HIGH; + } + PH7_MemObjRelease(&sTarget); + PH7_MemObjRelease(&sMethod); + if(pMeth == 0) { + /* Preserve the existing NULL result for non-callable + * arrays without recursively invoking this same opcode. */ + VmPopOperand(&pTos, pInstr->iP1); + PH7_MemObjRelease(pTos); + break; + } + } else if((pTos->nType & (MEMOBJ_OBJ | MEMOBJ_HASHMAP)) == MEMOBJ_OBJ) { ph7_class_instance *pThis = (ph7_class_instance *)pTos->x.pOther; ph7_class_method *pMeth; if(pThis == 0) { @@ -6466,25 +6923,7 @@ Resume: } else if(pTos->nType & MEMOBJ_STRING && pc > 0 && aInstr[pc - 1].iOp == PH7_OP_LOADV) { PH7_VmThrowError(&(*pVm), PH7_CTX_ERR, "Calling a non-callable object"); } else if((pTos->nType & (MEMOBJ_CALL | MEMOBJ_STRING)) == 0) { - if(pTos->nType & MEMOBJ_HASHMAP) { - ph7_value sResult; - SySetReset(&aArg); - while(pArg < pTos) { - SySetPut(&aArg, (const void *)&pArg); - pArg++; - } - PH7_MemObjInit(pVm, &sResult); - /* May be a class instance and it's static method */ - PH7_VmCallUserFunction(pVm, pTos, (int)SySetUsed(&aArg), (ph7_value **)SySetBasePtr(&aArg), &sResult); - SySetReset(&aArg); - /* Pop given arguments */ - if(pInstr->iP1 > 0) { - VmPopOperand(&pTos, pInstr->iP1); - } - /* Copy result */ - PH7_MemObjStore(&sResult, pTos); - PH7_MemObjRelease(&sResult); - } else { + { /* Raise exception: Invalid function name */ PH7_VmThrowError(&(*pVm), PH7_CTX_WARNING, "Invalid function name"); /* Pop given arguments */ @@ -6535,6 +6974,9 @@ Resume: /* "Late Static Binding" class name */ pSelf = PH7_VmExtractClass(&(*pVm), (const char *)SyBlobData(&pTarget->sBlob), SyBlobLength(&pTarget->sBlob), FALSE); + if(pVm->iPendingTransfer) { + goto Unwind; + } } if(pSelf == 0) { pSelf = (ph7_class *)pVmFunc->pUserData; @@ -6581,23 +7023,30 @@ Resume: PH7_VmMemoryError(&(*pVm)); } if(pThis && pVmFunc->iFlags & VM_FUNC_CLASS_METHOD) { - /* Install the '$parent' variable */ - static const SyString sParent = { "parent", sizeof("parent") - 1 }; - pObj = VmCreateMemObj(&(*pVm), &sParent, FALSE); - if(pObj) { - /* Reflect the change */ - pObj->iFlags = MEMOBJ_PARENTOBJ; - pObj->x.pOther = pThis; - MemObjSetType(pObj, MEMOBJ_OBJ); - } - /* Install the '$this' variable */ - static const SyString sThis = { "this", sizeof("this") - 1 }; - pObj = VmCreateMemObj(&(*pVm), &sThis, FALSE); - if(pObj) { - /* Reflect the change */ - pObj->iFlags = MEMOBJ_THISOBJ; - pObj->x.pOther = pThis; - MemObjSetType(pObj, MEMOBJ_OBJ); + static const SyString aName[] = { + { "parent", sizeof("parent") - 1 }, + { "this", sizeof("this") - 1 } + }; + static const sxi32 aFlags[] = { MEMOBJ_PARENTOBJ, MEMOBJ_THISOBJ }; + sxu32 i, j; + for(i = 0; i < SX_ARRAYSIZE(aName); i++) { + /* Explicit formals shadow the implicit bindings. The + * receiver remains in the frame, not in a positional + * argument slot, for both native and source methods. */ + for(j = 0; j < SySetUsed(&pVmFunc->aArgs); j++) { + if(SyStringCmp(&aName[i], &aFormalArg[j].sName, SyMemcmp) == 0) { + break; + } + } + if(j < SySetUsed(&pVmFunc->aArgs)) { + continue; + } + pObj = VmCreateMemObj(&(*pVm), &aName[i], FALSE); + if(pObj) { + pObj->iFlags = aFlags[i]; + pObj->x.pOther = pThis; + MemObjSetType(pObj, MEMOBJ_OBJ); + } } } /* Push arguments in the local frame */ @@ -6641,23 +7090,43 @@ Resume: "constant", &pVmFunc->sName, n + 1); } /* Switch to pass by value */ - pObj = VmCreateMemObj(&(*pVm), &aFormalArg[n].sName, FALSE); + pObj = VmCreateArgument(pVm, &aFormalArg[n].sName); } else { SyHashEntry *pRefEntry; /* Install the referenced variable in the private function frame */ pRefEntry = SyHashGet(&pFrame->hVar, SyStringData(&aFormalArg[n].sName), SyStringLength(&aFormalArg[n].sName)); if(pRefEntry == 0) { - SyHashInsert(&pFrame->hVar, SyStringData(&aFormalArg[n].sName), - SyStringLength(&aFormalArg[n].sName), SX_INT_TO_PTR(pArg->nIdx)); - sArg.nIdx = pArg->nIdx; - sArg.pUserData = 0; - SySetPut(&pFrame->sArg, (const void *)&sArg); + if(SyHashInsert(&pFrame->hVar, SyStringData(&aFormalArg[n].sName), + SyStringLength(&aFormalArg[n].sName), SX_INT_TO_PTR(pArg->nIdx)) != SXRET_OK) { + PH7_VmMemoryError(pVm); + } + } + sArg.nIdx = pArg->nIdx; + sArg.pUserData = 0; + if(SySetPut(&pFrame->sArg, &sArg) != SXRET_OK || + SySetPut(&pFrame->sArgPin, &sArg) != SXRET_OK) { + PH7_VmMemoryError(pVm); + } + /* A live reference argument owns its indexed + * binding with the same retirement mechanism + * as a using(&...) capture. + * Arena growth or a reentrant unset cannot + * recycle that index during either body kind. */ + { + VmRefObj *pRef = VmRefObjExtract(pVm, sArg.nIdx); + if(pRef == 0) { + if(PH7_VmRefObjInstall(pVm, sArg.nIdx, 0, 0, 0) != SXRET_OK) { + PH7_VmMemoryError(pVm); + } + pRef = VmRefObjExtract(pVm, sArg.nIdx); + } + pRef->nBorrow++; } pObj = 0; } } else { /* Pass by value, make a copy of the given argument */ - pObj = VmCreateMemObj(&(*pVm), &aFormalArg[n].sName, FALSE); + pObj = VmCreateArgument(pVm, &aFormalArg[n].sName); } } else { char zName[32]; @@ -6750,14 +7219,16 @@ Resume: } /* Process default values */ while(n < SySetUsed(&pVmFunc->aArgs)) { - if(SySetUsed(&aFormalArg[n].aByteCode) > 0) { - pObj = VmCreateMemObj(&(*pVm), &aFormalArg[n].sName, FALSE); + if(VmArgHasDefault(&aFormalArg[n])) { + pObj = VmCreateArgument(pVm, &aFormalArg[n].sName); if(pObj) { ph7_value sDefault; sxu32 nObjIdx = pObj->nIdx; PH7_MemObjInit(pVm, &sDefault); /* Evaluate the default value and extract it's result */ - rc = VmLocalExec(&(*pVm), &aFormalArg[n].aByteCode, &sDefault); + rc = VmEvalInitializer(pVm, &aFormalArg[n].aByteCode, + aFormalArg[n].pNativeDefault, aFormalArg[n].xNativeDefault, + aFormalArg[n].pNativeData, &sDefault); pObj = (ph7_value *)SySetAt(&pVm->aMemObj, nObjIdx); PH7_MemObjStore(&sDefault, pObj); PH7_MemObjRelease(&sDefault); @@ -6800,11 +7271,12 @@ Resume: } pObj->nType = pTmp->nType; PH7_VmDestroyMemObj(&(*pVm), pTmp); - /* Insert argument index */ - sArg.nIdx = pObj->nIdx; - sArg.pUserData = 0; - SySetPut(&pFrame->sArg, (const void *)&sArg); } + /* Every prepared default occupies a positional slot, + * including nominal and nominal-array arguments. */ + sArg.nIdx = nObjIdx; + sArg.pUserData = 0; + SySetPut(&pFrame->sArg, (const void *)&sArg); } } ++n; @@ -6877,6 +7349,12 @@ Resume: rc = pFunc->xFunc(&sCtx, (int)SySetUsed(&aArg), (ph7_value **)SySetBasePtr(&aArg)); /* Release the call context */ VmReleaseCallContext(&sCtx); + /* Scalar conversion failures retain their original transfer. + * Consume it here even when the builtin returned ABORT, so + * normal shutdown callbacks do not inherit a stale carrier. */ + if(pVm->iPendingTransfer) { + rc = PH7_VmTakeTransfer(pVm, &sRet); + } if(rc == PH7_ABORT) { PH7_MemObjRelease(&sRet); goto Abort; @@ -6915,6 +7393,9 @@ Resume: if((pOut->nType & MEMOBJ_STRING) == 0) { PH7_MemObjToString(pOut); } + if(pVm->iPendingTransfer) { + break; + } if(SyBlobLength(&pOut->sBlob) > 0) { /*SyBlobNullAppend(&pOut->sBlob);*/ /* Invoke the output consumer callback */ @@ -6927,13 +7408,33 @@ Resume: } pOut++; } + if(pVm->iPendingTransfer) { + break; + } pTos = &pCur[-1]; break; } } /* Switch() */ + if(pVm->iPendingTransfer) { + rc = PH7_VmTakeTransfer(pVm, &sTransfer); + if(rc == PH7_ABORT) { + goto Abort; + } + iTransfer = VM_TRANSFER_THROW; + nTarget = pc + 1; + goto Unwind; + } pc++; /* Next instruction in the stream */ } /* For(;;) */ Unwind: + if(pVm->iPendingTransfer) { + rc = PH7_VmTakeTransfer(pVm, &sTransfer); + if(rc == PH7_ABORT) { + goto Abort; + } + iTransfer = VM_TRANSFER_THROW; + nTarget = pc + 1; + } /* Freeze a completion before running handlers. Each invocation consumes its * own regions inside-out; a handler completion replaces, never combines with, * the pending completion. The compiled finally remains reusable. */ @@ -6960,6 +7461,13 @@ Unwind: PH7_MemObjInit(pVm, &sHandler); if(iTransfer == VM_TRANSFER_THROW && (sTransfer.nType & MEMOBJ_OBJ)) { pCatch = VmFindCatch(pVm, &sRegion.sException, (ph7_class_instance *)sTransfer.x.pOther); + if(pVm->iPendingTransfer) { + rc = PH7_VmTakeTransfer(pVm, &sTransfer); + if(rc == PH7_ABORT) { + PH7_MemObjRelease(&sHandler); + goto Abort; + } + } } if(pCatch) { rc = VmExecExceptionBlock(pVm, &sRegion.sException, pCatch, @@ -7058,6 +7566,9 @@ Complete: } goto Cleanup; Done: + if(pVm->iPendingTransfer) { + goto Unwind; + } rc = SXRET_OK; goto Cleanup; Abort: @@ -7208,10 +7719,34 @@ PH7_PRIVATE sxi32 PH7_VmByteCodeExec(ph7_vm *pVm) { } /* Set the execution magic number */ pVm->nMagic = PH7_VM_EXEC; + rc = VmMountNativeClasses(pVm); + if(rc == SXERR_MEM) { + PH7_VmMemoryError(pVm); + } + if(rc != SXRET_OK) { + if(pVm->iPendingTransfer == PH7_EXCEPTION) { + VmUncaughtException(pVm, (ph7_class_instance *)pVm->sPendingTransfer.x.pOther); + } + PH7_VmTakeTransfer(pVm, 0); + rc = SXRET_OK; + goto Shutdown; + } /* Execute the byte code */ - VmByteCodeExec(&(*pVm), (VmInstr *)SySetBasePtr(pVm->pByteContainer), pVm->aOps, -1, 0, FALSE); + rc = VmByteCodeExec(&(*pVm), (VmInstr *)SySetBasePtr(pVm->pByteContainer), pVm->aOps, -1, 0, FALSE); + if(rc == PH7_ABORT || rc == PH7_EXCEPTION) { + rc = SXRET_OK; + goto Shutdown; + } /* Extract the entry class */ pClass = PH7_VmExtractClass(&(*pVm), "Program", 7, TRUE /* Only loadable class but not 'interface' or 'virtual' class*/); + if(pVm->iPendingTransfer) { + if(pVm->iPendingTransfer == PH7_EXCEPTION) { + VmUncaughtException(pVm, (ph7_class_instance *)pVm->sPendingTransfer.x.pOther); + } + PH7_VmTakeTransfer(pVm, 0); + rc = SXRET_OK; + goto Shutdown; + } if(!pClass) { PH7_VmThrowError(&(*pVm), PH7_CTX_ERR, "Cannot find an entry 'Program' class"); } @@ -7223,7 +7758,7 @@ PH7_PRIVATE sxi32 PH7_VmByteCodeExec(ph7_vm *pVm) { pMethod = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1); if(rc == SXRET_OK && pMethod) { /* Use ordinary constructor access and overload selection, with no arguments. */ - rc = VmCallClassMethod(pVm, pInstance, pMethod, &pResult, 0, 0, FALSE); + rc = VmCallClassMethod(pVm, pInstance, pMethod, &pResult, 0, 0, FALSE, FALSE); if(pInstance->iRef < 1) { pInstance->iRef = 1; } @@ -7269,7 +7804,7 @@ PH7_PRIVATE sxi32 PH7_VmByteCodeExec(ph7_vm *pVm) { PH7_MemObjInit(pVm, &pResult); /* Call entry point */ VmCallClassMethod(pVm, pInstance, pMethod, &pResult, - (int)SySetUsed(&pMethod->sFunc.aArgs), &pArgs, VM_CALL_ENTRY); + (int)SySetUsed(&pMethod->sFunc.aArgs), &pArgs, VM_CALL_ENTRY, FALSE); if(!pVm->iExitStatus) { if(pMethod->sFunc.nType == MEMOBJ_INT) { pVm->iExitStatus = ph7_value_to_int(&pResult); @@ -7303,6 +7838,9 @@ PH7_PRIVATE sxi32 PH7_VmOutputConsume( ) { ph7_output_consumer *pCons = &pVm->sVmConsumer; sxi32 rc = SXRET_OK; + if(pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } /* Call the output consumer */ if(pString->nByte > 0) { rc = pCons->xConsumer((const void *)pString->zString, pString->nByte, pCons->pUserData); @@ -7398,8 +7936,6 @@ static int vm_builtin_func_exists(ph7_context *pCtx, int nArg, ph7_value **apArg ph7_result_bool(pCtx, res); return SXRET_OK; } -/* Forward declaration */ -static ph7_class *VmExtractClassFromValue(ph7_vm *pVm, ph7_value *pArg); /* * Verify that the contents of a variable can be called as a function. * [i.e: Whether it is callable or not]. @@ -8330,7 +8866,8 @@ static int vm_builtin_is_subclass_of(ph7_context *pCtx, int nArg, ph7_value **ap ph7_value *pResult, /* Store method return value here. NULL otherwise */ int nArg, /* Total number of given arguments */ ph7_value **apArg, /* Method arguments */ - sxi32 bInternal /* VM-owned lifecycle call, or VM_CALL_ENTRY */ + sxi32 bInternal, /* VM-owned lifecycle call, or VM_CALL_ENTRY */ + sxi32 bParent ) { ph7_value *aStack; VmInstr aInstr[2]; @@ -8346,7 +8883,11 @@ static int vm_builtin_is_subclass_of(ph7_context *pCtx, int nArg, ph7_value **ap } /* Fill the operand stack with the given arguments */ for(i = 0 ; i < nArg ; i++) { - PH7_MemObjLoad(apArg[i], &aStack[i]); + ph7_value *pValue = apArg[i]; + if(pValue->iFlags & MEMOBJ_INDEX_HANDLE) { + pValue = (ph7_value *)SySetAt(&pVm->aMemObj, pValue->nIdx); + } + PH7_MemObjLoad(pValue, &aStack[i]); /* * Symisc eXtension: * Parameters to [call_user_func()] can be passed by reference. @@ -8362,9 +8903,12 @@ static int vm_builtin_is_subclass_of(ph7_context *pCtx, int nArg, ph7_value **ap pThis->iRef++; /* Increment reference count */ aStack[i].x.pOther = pThis; aStack[i].nType = MEMOBJ_OBJ; + if(bParent) { + aStack[i].iFlags = MEMOBJ_PARENTOBJ; + } } pSeed = VmMethodSeed(pVm, pThis ? pThis->pClass : pMethod->sFunc.pClass, - &pMethod->sFunc.sName, pMethod, FALSE); + &pMethod->sFunc.sName, pMethod, bParent); if(pSeed == 0 || ((iEntry & 1) && pSeed != pMethod)) { PH7_VmThrowError(pVm, PH7_CTX_ERR, "Cannot call virtual method '%z::%z()'", &pMethod->sFunc.pClass->sName, &pMethod->sFunc.sName); @@ -8408,7 +8952,34 @@ static int vm_builtin_is_subclass_of(ph7_context *pCtx, int nArg, ph7_value **ap } PH7_PRIVATE sxi32 PH7_VmCallClassMethod(ph7_vm *pVm, ph7_class_instance *pThis, ph7_class_method *pMethod, ph7_value *pResult, int nArg, ph7_value **apArg) { - return VmCallClassMethod(pVm, pThis, pMethod, pResult, nArg, apArg, TRUE); + return VmCallClassMethod(pVm, pThis, pMethod, pResult, nArg, apArg, TRUE, FALSE); +} +PH7_PRIVATE sxi32 PH7_VmContextParent(ph7_context *pCtx, const char *zMethod, + int nArg, ph7_value **apArg, ph7_value *pResult) { + ph7_class *pScope, *pLookup; + ph7_class_instance *pThis; + ph7_class_method *pMethod; + SyString sName; + if(pCtx == 0 || zMethod == 0 || pResult == 0 || pResult->pVm != pCtx->pVm || + nArg < 0 || (nArg && apArg == 0)) { + return PH7_CORRUPT; + } + pScope = VmMethodClass(pCtx->pVm); + if(pScope == 0) { + return PH7_CORRUPT; + } + pThis = pCtx->pVm->pFrame->pThis; + if(pThis == 0) { + /* The language's cooperative $parent binding requires a receiver. */ + return PH7_CORRUPT; + } + pLookup = pThis ? pThis->pClass : pScope; + SyStringInitFromBuf(&sName, zMethod, SyStrlen(zMethod)); + pMethod = VmMethodSeed(pCtx->pVm, pLookup, &sName, 0, TRUE); + if(pMethod == 0) { + return PH7_CORRUPT; + } + return VmCallClassMethod(pCtx->pVm, pThis, pMethod, pResult, nArg, apArg, FALSE, TRUE); } /* * Call a user defined or foreign function where the name of the function @@ -8428,7 +8999,13 @@ PH7_PRIVATE sxi32 PH7_VmCallUserFunction( VmInstr aInstr[2]; sxi32 rc; int i; - if((pFunc->nType & (MEMOBJ_CALL | MEMOBJ_STRING)) == 0) { + /* The scalar conversion carrier belongs to the enclosing evaluator. + * A builtin must not start another callback (or consume that carrier) + * after a conversion has already transferred control. */ + if(pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } + if((pFunc->nType & (MEMOBJ_CALL | MEMOBJ_STRING | MEMOBJ_HASHMAP | MEMOBJ_OBJ)) == 0) { /* Don't bother processing,it's invalid anyway */ if(pResult) { /* Assume a null return value */ @@ -8443,7 +9020,11 @@ PH7_PRIVATE sxi32 PH7_VmCallUserFunction( } /* Fill the operand stack with the given arguments */ for(i = 0 ; i < nArg ; i++) { - PH7_MemObjLoad(apArg[i], &aStack[i]); + ph7_value *pValue = apArg[i]; + if(pValue->iFlags & MEMOBJ_INDEX_HANDLE) { + pValue = (ph7_value *)SySetAt(&pVm->aMemObj, pValue->nIdx); + } + PH7_MemObjLoad(pValue, &aStack[i]); /* * Symisc eXtension: * Parameters to [call_user_func()] can be passed by reference. @@ -9097,6 +9678,9 @@ static int vm_builtin_rand_str(ph7_context *pCtx, int nArg, ph7_value **apArg) { } } /* Generate the random string */ + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } PH7_VmRandomString(pCtx->pVm, zString, iLen); /* Return the generated string */ ph7_result_string(pCtx, zString, iLen); /* Will make it's own copy */ @@ -9156,6 +9740,9 @@ static int vm_builtin_random_bytes(ph7_context *pCtx, int nArg, ph7_value **apAr PH7_VmThrowError(pCtx->pVm, PH7_CTX_ERR, "Expecting length argument"); } iLen = (sxu32)ph7_value_to_int(apArg[0]); + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } zBuf = SyMemBackendPoolAlloc(&pCtx->pVm->sAllocator, iLen); if(zBuf == 0) { PH7_VmMemoryError(pCtx->pVm); @@ -9277,6 +9864,9 @@ static int vm_builtin_print(ph7_context *pCtx, int nArg, ph7_value **apArg) { /* Output */ for(i = 0 ; i < nArg ; ++i) { zData = ph7_value_to_string(apArg[i], &nDataLen); + if(pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } if(nDataLen > 0) { rc = pVm->sVmConsumer.xConsumer((const void *)zData, (unsigned int)nDataLen, pVm->sVmConsumer.pUserData); if(rc == SXERR_ABORT) { @@ -9327,7 +9917,7 @@ PH7_PRIVATE sxi32 PH7_VmUnsetMemObj(ph7_vm *pVm, sxu32 nObjIdx, int bForce) { ph7_value *pObj; VmRefObj *pRef; pRef = VmRefObjExtract(pVm, nObjIdx); - if(pRef && pRef->nCapture) { + if(pRef && (pRef->nCapture || pRef->nBorrow)) { VmRefObjUnlink(pVm, pRef); return SXRET_OK; } @@ -9361,7 +9951,7 @@ PH7_PRIVATE sxi32 PH7_VmDestroyMemObj(ph7_vm *pVm, ph7_value *pObj) { VmRefObj *pRef; if(pObj) { pRef = VmRefObjExtract(pVm, pObj->nIdx); - if(pRef && pRef->nCapture) { + if(pRef && (pRef->nCapture || pRef->nBorrow)) { VmRefObjUnlink(pVm, pRef); return SXRET_OK; } @@ -9677,7 +10267,7 @@ static int vm_builtin_get_memory_usage(ph7_context *pCtx, int nArg, ph7_value ** */ static int vm_builtin_assert_options(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_vm *pVm = pCtx->pVm; - int iOld, iNew, iValue; + int iOld, iNew, iValue, iFlags; if(nArg < 1 || !ph7_value_is_int(apArg[0])) { /* Missing/Invalid arguments, return FALSE */ ph7_result_bool(pCtx, 0); @@ -9685,43 +10275,48 @@ static int vm_builtin_assert_options(ph7_context *pCtx, int nArg, ph7_value **ap } /* Save old assertion flags */ iOld = pVm->iAssertFlags; + iFlags = iOld; /* Extract the new flags */ iNew = ph7_value_to_int(apArg[0]); if(iNew == PH7_ASSERT_DISABLE) { - pVm->iAssertFlags &= ~PH7_ASSERT_DISABLE; + iFlags &= ~PH7_ASSERT_DISABLE; if(nArg > 1) { iValue = !ph7_value_to_bool(apArg[1]); if(iValue) { /* Disable assertion */ - pVm->iAssertFlags |= PH7_ASSERT_DISABLE; + iFlags |= PH7_ASSERT_DISABLE; } } } else if(iNew == PH7_ASSERT_WARNING) { - pVm->iAssertFlags &= ~PH7_ASSERT_WARNING; + iFlags &= ~PH7_ASSERT_WARNING; if(nArg > 1) { iValue = ph7_value_to_bool(apArg[1]); if(iValue) { /* Issue a warning for each failed assertion */ - pVm->iAssertFlags |= PH7_ASSERT_WARNING; + iFlags |= PH7_ASSERT_WARNING; } } } else if(iNew == PH7_ASSERT_BAIL) { - pVm->iAssertFlags &= ~PH7_ASSERT_BAIL; + iFlags &= ~PH7_ASSERT_BAIL; if(nArg > 1) { iValue = ph7_value_to_bool(apArg[1]); if(iValue) { /* Terminate execution on failed assertions */ - pVm->iAssertFlags |= PH7_ASSERT_BAIL; + iFlags |= PH7_ASSERT_BAIL; } } } else if(iNew == PH7_ASSERT_CALLBACK) { - pVm->iAssertFlags &= ~PH7_ASSERT_CALLBACK; + iFlags &= ~PH7_ASSERT_CALLBACK; if(nArg > 1 && ph7_value_is_callable(apArg[1])) { /* Callback to call on failed assertions */ PH7_MemObjStore(apArg[1], &pVm->sAssertCallback); - pVm->iAssertFlags |= PH7_ASSERT_CALLBACK; + iFlags |= PH7_ASSERT_CALLBACK; } } + if(pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } + pVm->iAssertFlags = iFlags; /* Return the old flags */ ph7_result_int(pCtx, iOld); return PH7_OK; @@ -9766,6 +10361,9 @@ static int vm_builtin_assert(ph7_context *pCtx, int nArg, ph7_value **apArg) { /* Perform a boolean cast */ iResult = ph7_value_to_bool(apArg[0]); } + if(pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } if(!iResult) { /* Assertion failed */ if(iFlags & PH7_ASSERT_CALLBACK) { @@ -10123,6 +10721,9 @@ static ph7_exception_block *VmFindCatch( for(j = 0; j < SySetUsed(&pException->sEntry); j++) { SyString *pName = &aCatch[j].sClass; ph7_class *pClass = PH7_VmExtractClass(pVm, pName->zString, pName->nByte, TRUE); + if(pVm->iPendingTransfer) { + return 0; + } if(pClass && VmInstanceOf(pVm, pThis->pClass, pClass)) { return &aCatch[j]; } @@ -10733,6 +11334,9 @@ static int vm_builtin_extract(ph7_context *pCtx, int nArg, ph7_value **apArg) { } } sAux.pVm = pCtx->pVm; + if(pCtx->pVm->iPendingTransfer) { + return pCtx->pVm->iPendingTransfer; + } /* Invoke the worker callback */ PH7_HashmapWalk(pMap, VmExtractCallback, &sAux); /* Number of variables successfully imported */ @@ -11778,6 +12382,88 @@ static sxi32 VmRegisterSpecialFunction(ph7_vm *pVm) { } return SXRET_OK; } +/* Resolve hierarchy metadata independently of execution readiness. */ +static sxi32 VmEnsureNativeClass(ph7_vm *pVm, ph7_class *pClass) { + SySet sInterfaces; + sxu32 i; + sxi32 rc; + if(!pClass->bNative || pClass->iNativeState != 0) { + return SXRET_OK; + } + pClass->iNativeState = 1; + SySetInit(&sInterfaces, &pVm->sAllocator, sizeof(ph7_class *)); + rc = PH7_ClassBuildMro(pVm, pClass); + if(rc == SXRET_OK) { + rc = PH7_ClassCollectInterfaces(pVm, pClass, &sInterfaces); + } + if(pClass->iFlags & PH7_CLASS_INTERFACE) { + for(i = 0; i < SySetUsed(&sInterfaces) && rc == SXRET_OK; i++) { + ph7_class *pBase = *(ph7_class **)SySetAt(&sInterfaces, i); + if(pBase != pClass) { + rc = PH7_ClassInterfaceInherit(pClass, pBase); + } + } + } else { + for(i = 1; i < SySetUsed(&pClass->aMro) && rc == SXRET_OK; i++) { + rc = PH7_ClassInherit(pVm, pClass, *(ph7_class **)SySetAt(&pClass->aMro, i)); + } + for(i = 0; i < SySetUsed(&sInterfaces) && rc == SXRET_OK; i++) { + ph7_class *pInterface = *(ph7_class **)SySetAt(&sInterfaces, i); + sxu32 j; + for(j = 0; j < SySetUsed(&pClass->aInterface); j++) { + if(*(ph7_class **)SySetAt(&pClass->aInterface, j) == pInterface) { + break; + } + } + if(j == SySetUsed(&pClass->aInterface)) { + rc = PH7_ClassImplement(pVm, pClass, pInterface); + } + } + } + SySetRelease(&sInterfaces); + if(rc == SXERR_MEM) { + PH7_VmMemoryError(pVm); + } + pClass->iNativeState = rc == SXRET_OK ? 2 : 0; + return rc; +} +/* Runtime class use, not the kind/completion of the registering callback, + * makes an accepted declaration ready. Do not run initializers while a + * transfer is pending, or while registration/hierarchy construction is active. */ +static sxi32 VmReadyNativeClass(ph7_vm *pVm, ph7_class *pClass) { + sxu32 i; + sxi32 rc; + if(!pClass->bNative || pClass->iNativeState != 2 || pClass->bMounting || pClass->bMethodsMounted || + (pVm->nMagic != PH7_VM_EXEC && pVm->nMagic != PH7_VM_INCL)) { + return SXRET_OK; + } + if(pVm->iPendingTransfer) { + return pVm->iPendingTransfer; + } + /* Inherited methods/storage belong to their declaring classes. */ + for(i = SySetUsed(&pClass->aMro); i > 0; i--) { + ph7_class *pBase = *(ph7_class **)SySetAt(&pClass->aMro, i - 1); + if(pBase != pClass && pBase->bNative && !pBase->bMethodsMounted) { + rc = VmMountUserClass(pVm, pBase); + if(rc != SXRET_OK) { + goto Done; + } + } + } + for(i = 0; i < SySetUsed(&pClass->aInterface); i++) { + ph7_class *pInterface = *(ph7_class **)SySetAt(&pClass->aInterface, i); + rc = VmMountUserClass(pVm, pInterface); + if(rc != SXRET_OK) { + goto Done; + } + } + rc = VmMountUserClass(pVm, pClass); +Done: + if(rc == SXERR_MEM) { + PH7_VmMemoryError(pVm); + } + return rc; +} /* * Check if the given name refer to an installed class. * Return a pointer to that class on success. NULL on failure. @@ -11792,6 +12478,20 @@ PH7_PRIVATE ph7_class *PH7_VmExtractClass( ) { SyHashEntry *pEntry; ph7_class *pClass; + if(pVm->bNativeRegister) { + if(pVm->pStagedClass && pVm->pStagedClass->sName.nByte == nByte && + SyMemcmp(pVm->pStagedClass->sName.zString, zName, nByte) == 0) { + return pVm->pStagedClass; + } + pEntry = SyHashGet(&pVm->hClass, zName, nByte); + if(pEntry == 0 && pVm->pClassJournal) { + pVm->bClassDeferred = TRUE; + } + return pEntry ? (ph7_class *)pEntry->pUserData : 0; + } + if(pVm->iPendingTransfer) { + return 0; + } /* Perform a hash lookup */ pEntry = SyHashGet(&pVm->hClass, (const void *)zName, nByte); if(pEntry == 0) { @@ -11799,6 +12499,7 @@ PH7_PRIVATE ph7_class *PH7_VmExtractClass( ph7_value sResult, sName; VmAutoLoadCB *sEntry; sxu32 n, nEntry; + sxi32 rc; /* Point to the stack of registered callbacks */ nEntry = SySetUsed(&pVm->aAutoLoad); for(n = 0; n < nEntry; n++) { @@ -11809,9 +12510,15 @@ PH7_PRIVATE ph7_class *PH7_VmExtractClass( apArg[0] = &sName; /* Call autoloader */ PH7_MemObjInit(pVm, &sResult); - PH7_VmCallUserFunction(pVm, &sEntry->sCallback, 1, apArg, &sResult); + rc = PH7_VmCallUserFunction(pVm, &sEntry->sCallback, 1, apArg, &sResult); + /* Preserve the completion and its exception object before + * releasing callback storage or making a registered class ready. */ + PH7_VmDeferTransfer(pVm, rc, &sResult); PH7_MemObjRelease(&sResult); PH7_MemObjRelease(&sName); + if(rc != SXRET_OK || pVm->iPendingTransfer) { + return 0; + } /* Perform a hash lookup once again */ pEntry = SyHashGet(&pVm->hClass, (const void *)zName, nByte); if(pEntry) { @@ -11826,6 +12533,10 @@ PH7_PRIVATE ph7_class *PH7_VmExtractClass( } } pClass = (ph7_class *)pEntry->pUserData; + if(VmEnsureNativeClass(pVm, pClass) != SXRET_OK || + VmReadyNativeClass(pVm, pClass) != SXRET_OK) { + return 0; + } if(!iLoadable) { /* Return the class absolutely */ return pClass; @@ -11995,7 +12706,7 @@ static sxi32 VmRefObjUnlink(ph7_vm *pVm, VmRefObj *pRef) { PH7_HashmapUnlinkNode(apNode[n], FALSE); } } - if(pRef->nCapture) { + if(pRef->nCapture || pRef->nBorrow) { /* Names can disappear (including explicit unset), but captures still * own the binding's contents and prevent reuse of its index. */ SySetReset(&pRef->aReference); diff --git a/include/ph7.h b/include/ph7.h index 2c45c22..1939b8a 100644 --- a/include/ph7.h +++ b/include/ph7.h @@ -546,19 +546,31 @@ typedef struct ph7_type_def { const char *zClass; /* Required only for PH7_TYPE_NAMED; self is allowed. */ int bArray; /* Zero or one: the language's T[] annotation. */ } ph7_type_def; +/* Evaluators use ph7_result_* and return PH7_OK, PH7_ABORT or PH7_EXCEPTION. + * They run at the same evaluation point as the corresponding source expression. */ +typedef int (*ph7_initializer_func)(ph7_context *); typedef struct ph7_field_def { const char *zName; ph7_type_def sType; const ph7_value *pInitial; unsigned int iFlags; + ph7_initializer_func xInitial; + void *pInitialData; } ph7_field_def; typedef struct ph7_constant_def { const char *zName; const ph7_value *pValue; + unsigned int iFlags; + ph7_initializer_func xInitial; + void *pInitialData; } ph7_constant_def; typedef struct ph7_param_def { - const char *zName; /* Exact lowercase this/parent are reserved, even for static methods. */ + const char *zName; /* Explicit parameters shadow implicit this/parent bindings. */ ph7_type_def sType; + unsigned int iFlags; + const ph7_value *pDefault; + ph7_initializer_func xDefault; + void *pDefaultData; } ph7_param_def; typedef struct ph7_method_def { const char *zName; @@ -570,6 +582,8 @@ typedef struct ph7_method_def { unsigned int iFlags; } ph7_method_def; typedef struct ph7_class_def { + unsigned int nSize; /* sizeof(ph7_class_def), checked before any later field */ + unsigned int nVersion; /* PH7_CLASS_DEF_VERSION; covers all nested record layouts */ const char *zName; const ph7_field_def *aField; unsigned int nField; @@ -577,13 +591,55 @@ typedef struct ph7_class_def { unsigned int nConstant; const ph7_method_def *aMethod; unsigned int nMethod; + unsigned int iFlags; + const char *const *azBase; + unsigned int nBase; + const char *const *azInterface; + unsigned int nInterface; + /* Optional declaration order: indices into fields followed by constants. + * NULL/0 keeps the default: all fields, then all constants. Otherwise + * supply every index exactly once, in source declaration order. */ + const unsigned int *aMemberOrder; + unsigned int nMemberOrder; } ph7_class_def; +#define PH7_CLASS_DEF_VERSION 2 #define PH7_MEMBER_STATIC 0x01 +#define PH7_MEMBER_VIRTUAL 0x04 +#define PH7_MEMBER_FINAL 0x08 +#define PH7_MEMBER_PUBLIC 0x10 +#define PH7_MEMBER_PROTECTED 0x20 +#define PH7_MEMBER_PRIVATE 0x40 +#define PH7_PARAM_REF 0x01 +#define PH7_DECL_FINAL 0x01 +#define PH7_DECL_INTERFACE 0x02 +#define PH7_DECL_VIRTUAL 0x04 /* Return an exception object using ph7_result_value(), then this status. */ #define PH7_EXCEPTION (-255) PH7_APIEXPORT int ph7_create_class(ph7_vm *pVm, const ph7_class_def *pDef); /* Borrowed receiver, valid only during this callback; NULL for static calls. */ PH7_APIEXPORT ph7_value *ph7_context_this(ph7_context *pCtx); +/* Indexed operations reacquire moving VM storage on every call. argv contains + * by-value snapshots; use these operations for immediate reference semantics. */ +PH7_APIEXPORT int ph7_context_arg_value(ph7_context *pCtx, unsigned int nArg, ph7_value *pOut); +PH7_APIEXPORT int ph7_context_arg_store(ph7_context *pCtx, unsigned int nArg, ph7_value *pValue); +/* A forwarding handle is borrowed until this callback returns. Calls reacquire + * its live indexed binding; ordinary value setters still mutate only its copy. */ +PH7_APIEXPORT int ph7_context_arg_bind(ph7_context *pCtx, unsigned int nArg, ph7_value *pOut); +/* pObject selects instance storage; otherwise zClass selects static/constant + * storage. Access is checked in the callback's declaring language scope. */ +PH7_APIEXPORT int ph7_context_attr_value(ph7_context *pCtx, ph7_value *pObject, + const char *zClass, const char *zName, ph7_value *pOut); +PH7_APIEXPORT int ph7_context_attr_store(ph7_context *pCtx, ph7_value *pObject, + const char *zClass, const char *zName, ph7_value *pValue); +PH7_APIEXPORT int ph7_context_call(ph7_context *pCtx, ph7_value *pCallable, + int nArg, ph7_value **apArg, ph7_value *pResult); +PH7_APIEXPORT int ph7_context_parent(ph7_context *pCtx, const char *zMethod, + int nArg, ph7_value **apArg, ph7_value *pResult); +PH7_APIEXPORT int ph7_context_var_value(ph7_context *pCtx, const char *zName, ph7_value *pOut); +PH7_APIEXPORT int ph7_context_var_store(ph7_context *pCtx, const char *zName, ph7_value *pValue); +/* Legacy scalar conversion APIs cannot return an exception status. Query this + * before further native side effects; returning it propagates the completion. */ +PH7_APIEXPORT int ph7_context_status(ph7_context *pCtx); PH7_APIEXPORT int ph7_create_function(ph7_vm *pVm, const char *zName, int (*xFunc)(ph7_context *, int, ph7_value **), void *pUserData); PH7_APIEXPORT int ph7_delete_function(ph7_vm *pVm, const char *zName); PH7_APIEXPORT int ph7_create_constant(ph7_vm *pVm, const char *zName, void (*xExpand)(ph7_value *, void *), void *pUserData); diff --git a/include/ph7int.h b/include/ph7int.h index 94186a3..35796e6 100644 --- a/include/ph7int.h +++ b/include/ph7int.h @@ -627,6 +627,7 @@ struct ph7_value { #define MEMOBJ_VARIABLE 0 /* Memory value is variable */ #define MEMOBJ_PARENTOBJ 1 /* Memory value is 'parent' object */ #define MEMOBJ_THISOBJ 2 /* Memory value is 'this' object */ +#define MEMOBJ_INDEX_HANDLE 4 /* Native context forwarding handle, not a value flag */ /* Allowed variable data types. */ #define MEMOBJ_BOOL 0x0001 /* Memory value is a boolean */ @@ -758,6 +759,7 @@ struct ph7_context { sxi32 iFlags; /* Call flags */ ph7_value *pThis; /* Stable borrowed native method receiver */ sxi32 bResultSet; /* Distinguish explicit NULL from a bare return */ + void *pNativeFrame; /* Borrowed argument frame for indexed context operations */ }; /* * Each hashmap entry [i.e: array(4,5,6)] is recorded in an instance @@ -951,6 +953,9 @@ struct ph7_vm_func_arg { sxu32 nType; /* Type of this argument [i.e: array, int, string, float, object, etc.] */ SyString sClass; /* Class name if the argument expect a class instance [i.e: function foo(BaseClass $bar){} ] */ sxi32 iFlags; /* Configuration flags */ + ph7_value *pNativeDefault; /* Owned snapshot, distinct from an absent default */ + ph7_initializer_func xNativeDefault; + void *pNativeData; }; /* * Each static variable is parsed out and remembered in an instance @@ -1071,6 +1076,10 @@ struct ph7_class { SySet aMro; /* C3 linearization, including this class first */ sxi32 iMroState; /* 0: unbuilt, 1: building, 2: ready */ sxi32 bNative; /* Public native declaration */ + sxi32 iNativeState; /* 0: pending, 1: initializing, 2: usable */ + sxi32 bMounting; /* Reentrant static initializer guard */ + sxi32 bMethodsMounted; /* Concrete declarations enter the function table once */ + sxu32 nNativeWarnings; /* Accepted declaration diagnostics, delivered after commit */ }; /* Class configuration flags */ #define PH7_CLASS_FINAL 0x001 /* Class is final [cannot be extended] */ @@ -1094,6 +1103,8 @@ struct ph7_class_attr { sxu32 nIdx; /* Attribute index */ sxu32 nLine; /* Line number on which this attribute was defined */ ph7_value *pNativeInitial; /* Owned native declaration snapshot, if present */ + ph7_initializer_func xNativeInitial; + void *pNativeData; }; /* Attribute configuration */ #define PH7_CLASS_ATTR_STATIC 0x001 /* Static attribute */ @@ -1256,6 +1267,13 @@ struct ph7_vm { void *pStderr; /* STDERR IO stream */ sxbool bDebug; /* TRUE to enable debugging */ sxbool bErrReport; /* TRUE to report all runtime Error/Warning/Notice/Deprecated */ + SySet *pClassJournal; /* Non-reentrant, callback-free metadata preparation */ + ph7_class *pStagedClass; /* Unpublished declaration visible only to preparation */ + sxi32 bClassDeferred; /* A forward hierarchy name is not installed yet */ + sxi32 bNativeRegister; /* Callback-free declaration transaction is active */ + sxu32 nNativeReserve; /* Conservative rollback free-slot capacity bound */ + sxi32 iPendingTransfer; /* Conversion/readiness completion crossing scalar APIs */ + ph7_value sPendingTransfer; int nExceptDepth; /* Exception depth */ int closure_cnt; /* Loaded closures counter */ int json_rc; /* JSON return status [refer to json_encode()/json_decode()] */ @@ -1286,6 +1304,7 @@ struct VmFrame { SyHash hConst; /* Constant hashtable for fast lookup */ SyHash hVar; /* Variable hashtable for fast lookup */ SySet sArg; /* Function arguments container */ + SySet sArgPin; /* Indexed reference arguments retained through reentry */ SySet sRef; /* Local reference table (VmSlot instance) */ SySet sConstDecl; /* Constants already declared during this invocation */ sxi32 iFlags; /* Frame configuration flags (See below) */ @@ -1336,6 +1355,7 @@ struct VmRefObj { SySet aArrEntries; /* Foreign hashmap entries [i.e: array(&$a) ] */ sxu32 nIdx; /* Referenced object index */ sxu32 nCapture; /* Closure owners: keep contents and index alive */ + sxu32 nBorrow; /* Active reference argument handles retain the same index */ sxi32 iFlags; /* Configuration flags */ VmRefObj *pNextCollide, *pPrevCollide; /* Collision link */ VmRefObj *pNext, *pPrev; /* List of all referenced objects */ @@ -1745,6 +1765,20 @@ PH7_PRIVATE sxi32 PH7_IsIdentifier(const char *zName, sxi32 bKeyword); PH7_PRIVATE sxi32 PH7_IsMethodName(const char *zName); PH7_PRIVATE sxi32 PH7_IsReservedConstant(const SyString *pName); PH7_PRIVATE sxi32 PH7_VmCreateNativeClass(ph7_vm *pVm, const ph7_class_def *pDef); +PH7_PRIVATE const char *PH7_ClassMethodDeclarationError(ph7_class *pClass, + const SyString *pName, sxu32 nType, sxi32 iProtection, sxi32 iFlags); +#define PH7_INTERFACE_VISIBILITY_ERROR "interface: Access type must be public" +PH7_PRIVATE sxi32 PH7_ClassConstantProtection(ph7_class *pClass, sxi32 iProtection); +PH7_PRIVATE sxi32 PH7_VmContextAttr(ph7_context *pCtx, ph7_value *pObject, + const char *zClass, const char *zName, ph7_value *pValue, sxi32 bStore); +PH7_PRIVATE sxi32 PH7_ClassPrepareNative(ph7_vm *pVm, ph7_class *pClass); +PH7_PRIVATE sxi32 PH7_VmContextParent(ph7_context *pCtx, const char *zMethod, + int nArg, ph7_value **apArg, ph7_value *pResult); +PH7_PRIVATE void PH7_VmDeferTransfer(ph7_vm *pVm, sxi32 rc, ph7_value *pValue); +PH7_PRIVATE sxi32 PH7_VmTakeTransfer(ph7_vm *pVm, ph7_value *pResult); +PH7_PRIVATE sxi32 PH7_VmContextVar(ph7_context *pCtx, const char *zName, + ph7_value *pValue, sxi32 bStore); +PH7_PRIVATE sxi32 PH7_MemObjCopy(ph7_value *pSrc, ph7_value *pDest); PH7_PRIVATE ph7_value *PH7_ReserveConstObj(ph7_vm *pVm, sxu32 *pIndex); PH7_PRIVATE sxi32 PH7_VmOutputConsume(ph7_vm *pVm, SyString *pString); PH7_PRIVATE sxi32 PH7_VmOutputConsumeAp(ph7_vm *pVm, const char *zFormat, va_list ap);