From e99462aea14e6872c5d7619913da75366171e6e0 Mon Sep 17 00:00:00 2001 From: Rafal Kupiec Date: Sun, 22 Nov 2026 16:25:36 +0100 Subject: [PATCH] Harden XmlReader --- modules/xml/lib.c | 10 +- modules/xml/lib.h | 11 +- modules/xml/xml.c | 618 ++++++++++++++++++++++++++++------------------ modules/xml/xml.h | 29 +-- 4 files changed, 408 insertions(+), 260 deletions(-) diff --git a/modules/xml/lib.c b/modules/xml/lib.c index 2407d34..56c5053 100644 --- a/modules/xml/lib.c +++ b/modules/xml/lib.c @@ -8,6 +8,10 @@ */ #include "lib.h" +/* Shared key for the default namespace declaration. Declared at file scope so + * the stored byte sequence stays alive for the lifetime of the parser. */ +static const char sDefaultNsKey[] = { SXML_DEFAULT_NS_KEY, 0 }; + /* Tokenize an entire XML input */ static sxi32 XML_Tokenize(SyStream *pStream, SyToken *pToken, void *pUserData, void *pUnused2) { SyXMLParser *pParse = (SyXMLParser *)pUserData; @@ -351,8 +355,8 @@ static sxi32 XMLProcessNamesSpace(SyXMLParser *pParse, SyXMLRawStrNS *pTag, SyTo *pDup = *pUri; /* Structure assignment */ /* Save the namespace */ if(pPrefix->nByte == 0) { - pPrefix->zString = "Default"; - pPrefix->nByte = sizeof("Default") - 1; + pPrefix->zString = sDefaultNsKey; + pPrefix->nByte = SXML_DEFAULT_NS_KEY_LEN; } SyHashInsert(&pParse->hns, (const void *)pPrefix->zString, pPrefix->nByte, pDup); /* Peek the last inserted entry */ @@ -622,7 +626,7 @@ static sxi32 XMLExtractNS(SyXMLParser *pParse, SyToken *pToken, SyXMLRawStrNS *p rc = SyByteFind(pTag->zString, pTag->nByte, ':', &nOfft); if(rc != SXRET_OK) { /* Check if there is a default namespace */ - pEntry = SyHashGet(&pParse->hns, "Default", sizeof("Default") - 1); + pEntry = SyHashGet(&pParse->hns, sDefaultNsKey, SXML_DEFAULT_NS_KEY_LEN); if(pEntry) { /* Extract the ns URI */ pUri = (SyXMLRawStr *)pEntry->pUserData; diff --git a/modules/xml/lib.h b/modules/xml/lib.h index ef46ec9..14488f4 100644 --- a/modules/xml/lib.h +++ b/modules/xml/lib.h @@ -63,9 +63,18 @@ enum xml_err_code { SXML_ERROR_UNKNOWN_ENCODING, SXML_ERROR_INCORRECT_ENCODING, SXML_ERROR_UNCLOSED_CDATA_SECTION, - SXML_ERROR_EXTERNAL_ENTITY_HANDLING + SXML_ERROR_EXTERNAL_ENTITY_HANDLING, + /* Module-level conditions (not produced by the SAX tokenizer). */ + SXML_ERROR_INVALID_OPERATION, + SXML_ERROR_TYPE_MISMATCH }; +/* SyHashGet() ignores zero-length keys, so the default namespace cannot be + * stored under "". Use a non-printable one-byte sentinel instead. */ +#define SXML_DEFAULT_NS_KEY '\x01' +#define SXML_DEFAULT_NS_KEY_STR "\x01" +#define SXML_DEFAULT_NS_KEY_LEN 1 + /* * An XML raw text,CDATA,tag name and son is parsed out and stored * in an instance of the following structure. diff --git a/modules/xml/xml.c b/modules/xml/xml.c index 0c756c3..6c33284 100644 --- a/modules/xml/xml.c +++ b/modules/xml/xml.c @@ -13,8 +13,10 @@ /* * Security note: the underlying SAX engine never resolves external entities * and installs no entity handlers. OnDoctype therefore exists solely so a - * host can apply a DTD policy: returning PH7_ABORT from the callback stops - * the document before the remainder is parsed (see lib.c ProcessXML). The + * host can apply a DTD policy: the handler's return value is IGNORED (it is a + * void method), so rejecting a document means throwing from OnDoctype. The + * exception is propagated through XmlPropagate() and aborts token processing + * before the remainder of the document is parsed (see lib.c ProcessXML). The * internal subset is only recognised when '[' is the LAST non-whitespace * character on the DOCTYPE line (immediately before the line break): the * lexer stops scanning that line at '>' and records the last non-space byte. @@ -25,10 +27,9 @@ /* ------------------------------------------------------------------ */ /* Engine lifetime */ /* ------------------------------------------------------------------ */ -static ph7_xml_engine *VmCreateXMLEngine(ph7_context *pCtx, int process_ns, int ns_sep) { +static ph7_xml_engine *VmCreateXMLEngine(ph7_context *pCtx, int process_ns) { ph7_xml_engine *pEngine; ph7_vm *pVm = pCtx->pVm; - sxu32 n; pEngine = (ph7_xml_engine *)SyMemBackendAlloc(&pVm->sAllocator, sizeof(ph7_xml_engine)); if(pEngine == 0) { return 0; @@ -36,39 +37,41 @@ static ph7_xml_engine *VmCreateXMLEngine(ph7_context *pCtx, int process_ns, int SyZero(pEngine, sizeof(ph7_xml_engine)); pEngine->pVm = pVm; pEngine->pCtx = 0; - pEngine->ns_sep = ns_sep; SyXMLParserInit(&pEngine->sParser, &pVm->sAllocator, process_ns ? SXML_ENABLE_NAMESPACE : 0); SyBlobInit(&pEngine->sErr, &pVm->sAllocator); - PH7_MemObjInit(pVm, &pEngine->sParserValue); PH7_MemObjInit(pVm, &pEngine->sReaderValue); PH7_MemObjInit(pVm, &pEngine->sHandler); PH7_MemObjInit(pVm, &pEngine->sAttrs); PH7_MemObjInit(pVm, &pEngine->sLocalName); PH7_MemObjInit(pVm, &pEngine->sNsUri); PH7_MemObjInit(pVm, &pEngine->sPrefix); - for(n = 0 ; n < SX_ARRAYSIZE(pEngine->aCB) ; ++n) { - PH7_MemObjInit(pVm, &pEngine->aCB[n]); - } - ph7_value_resource(&pEngine->sParserValue, pEngine); + SySetInit(&pEngine->sElemStack, &pVm->sAllocator, sizeof(ph7_xml_elem_snapshot)); pEngine->iErrCode = SXML_ERROR_NONE; pEngine->nMagic = XML_ENGINE_MAGIC; return pEngine; } +/* Drop every open-element snapshot. Called on abort-recovery and at teardown + * so a handler exception in the middle of a document never leaks a snapshot. */ +static void XmlElemStackClear(ph7_xml_engine *pEngine) { + ph7_xml_elem_snapshot *pSnap; + while((pSnap = (ph7_xml_elem_snapshot *)SySetPop(&pEngine->sElemStack)) != 0) { + PH7_MemObjRelease(&pSnap->sLocalName); + PH7_MemObjRelease(&pSnap->sNsUri); + PH7_MemObjRelease(&pSnap->sPrefix); + } +} static void VmReleaseXMLEngine(ph7_xml_engine *pEngine) { ph7_vm *pVm = pEngine->pVm; - sxu32 n; + XmlElemStackClear(pEngine); + SySetRelease(&pEngine->sElemStack); SyBlobRelease(&pEngine->sErr); SyXMLParserRelease(&pEngine->sParser); - PH7_MemObjRelease(&pEngine->sParserValue); PH7_MemObjRelease(&pEngine->sReaderValue); PH7_MemObjRelease(&pEngine->sHandler); PH7_MemObjRelease(&pEngine->sAttrs); PH7_MemObjRelease(&pEngine->sLocalName); PH7_MemObjRelease(&pEngine->sNsUri); PH7_MemObjRelease(&pEngine->sPrefix); - for(n = 0 ; n < SX_ARRAYSIZE(pEngine->aCB) ; ++n) { - PH7_MemObjRelease(&pEngine->aCB[n]); - } pEngine->nMagic = 0x2621; SyMemBackendFree(&pVm->sAllocator, pEngine); } @@ -95,9 +98,9 @@ static void XmlTrackPos(ph7_xml_engine *pEngine, SyXMLRawStr *pRaw) { pEngine->nCurLine = pRaw ? pRaw->nLine : 0; pEngine->iCurByte = 0; pEngine->nCurCol = 0; - /* Some SAX strings are static literals (e.g. the empty default-namespace - * prefix in lib.c), not slices of the input buffer. Never subtract or scan - * across unrelated allocations. */ + /* Some SAX strings are static literals (e.g. the default-namespace key in + * lib.c), not slices of the input buffer. Never subtract or scan across + * unrelated allocations. */ if(zInput == 0 || zEnd == 0 || z == 0 || z < zInput || z > zEnd) { return; } @@ -107,9 +110,59 @@ static void XmlTrackPos(ph7_xml_engine *pEngine, SyXMLRawStr *pRaw) { while(p > zInput && p[-1] != '\n') { --p; } - pEngine->nCurCol = (sxu32)(z - p); + /* Columns exposed by the typed API are 1-based, matching the line + * numbering of the underlying token. */ + pEngine->nCurCol = (sxu32)(z - p) + 1; } } +/* The engine's QName fields always describe the innermost open element: + * start/end events set them to that element, text/PI/DOCTYPE events simply + * read them. The stack keeps deep snapshots so an end event can restore the + * enclosing element for subsequent events. */ +static void XmlElemRestoreSlot(ph7_xml_engine *pEngine, ph7_value *pSlot, ph7_value *pSrc) { + PH7_MemObjRelease(pSlot); + PH7_MemObjInit(pEngine->pVm, pSlot); + (void)PH7_MemObjStore(pSrc, pSlot); +} +static int XmlElemPush(ph7_xml_engine *pEngine) { + ph7_xml_elem_snapshot sSnap; + PH7_MemObjInit(pEngine->pVm, &sSnap.sLocalName); + PH7_MemObjInit(pEngine->pVm, &sSnap.sNsUri); + PH7_MemObjInit(pEngine->pVm, &sSnap.sPrefix); + if(PH7_MemObjSnapshot(&pEngine->sLocalName, &sSnap.sLocalName) != SXRET_OK || + PH7_MemObjSnapshot(&pEngine->sNsUri, &sSnap.sNsUri) != SXRET_OK || + PH7_MemObjSnapshot(&pEngine->sPrefix, &sSnap.sPrefix) != SXRET_OK || + SySetPut(&pEngine->sElemStack, &sSnap) != SXRET_OK) { + PH7_MemObjRelease(&sSnap.sLocalName); + PH7_MemObjRelease(&sSnap.sNsUri); + PH7_MemObjRelease(&sSnap.sPrefix); + /* SXERR_ABORT alone is not enough: Parse() checks bAbort/bError to + * decide the result. Without this flag an allocation failure here + * would be reported as a successful (but truncated) document. */ + pEngine->bAbort = TRUE; + return SXERR_ABORT; + } + return SXRET_OK; +} +/* Drop the snapshot of the element that just closed and restore its parent. + * When the root closes the stack becomes empty: keep the root's fields so the + * getters still report the last element after Parse() returns. */ +static void XmlElemEnd(ph7_xml_engine *pEngine) { + ph7_xml_elem_snapshot *pSnap = (ph7_xml_elem_snapshot *)SySetPop(&pEngine->sElemStack); + ph7_xml_elem_snapshot *pParent; + if(pSnap == 0) { + return; + } + pParent = (ph7_xml_elem_snapshot *)SySetPeek(&pEngine->sElemStack); + if(pParent) { + XmlElemRestoreSlot(pEngine, &pEngine->sLocalName, &pParent->sLocalName); + XmlElemRestoreSlot(pEngine, &pEngine->sNsUri, &pParent->sNsUri); + XmlElemRestoreSlot(pEngine, &pEngine->sPrefix, &pParent->sPrefix); + } + PH7_MemObjRelease(&pSnap->sLocalName); + PH7_MemObjRelease(&pSnap->sNsUri); + PH7_MemObjRelease(&pSnap->sPrefix); +} /* ------------------------------------------------------------------ */ /* Callback dispatch */ @@ -136,36 +189,23 @@ static sxi32 XmlCallHandler(ph7_xml_engine *pEngine, const char *zMethod, return SXRET_OK; } pMeth = PH7_ClassExtractMethod(pThis->pClass, zMethod, (sxu32)SyStrlen(zMethod)); - if(pMeth == 0) { + /* Only public methods are dispatchable from the SAX callbacks. A script + * subclass may narrow an inherited method's visibility via PH7's internal + * API; such a method must never be invoked from native code. */ + if(pMeth == 0 || pMeth->iProtection != PH7_CLASS_PROT_PUBLIC) { return SXRET_OK; } PH7_MemObjInit(pEngine->pVm, &sResult); rc = PH7_VmCallClassMethod(pEngine->pVm, pThis, pMeth, &sResult, nArg, apArg); return XmlPropagate(pEngine, &sResult, rc); } -static sxi32 XmlCallCallback(ph7_xml_engine *pEngine, int nSlot, ph7_value **apArg, int nArg) { - ph7_value *pCallback = &pEngine->aCB[nSlot]; - ph7_value sResult; - sxi32 rc; - if(!PH7_VmIsCallable(pEngine->pVm, pCallback, 0)) { - return SXRET_OK; - } - PH7_MemObjInit(pEngine->pVm, &sResult); - rc = PH7_VmCallUserFunction(pEngine->pVm, pCallback, nArg, apArg, &sResult); - return XmlPropagate(pEngine, &sResult, rc); -} -/* A typed IXmlHandler wins over a convenience callback; both receive the - * current XmlReader object as their first argument. */ -static sxi32 XmlNotify(ph7_xml_engine *pEngine, int nSlot, const char *zMethod, +/* Any non-OK result from a handler (including a deferred exception) aborts + * SAX token processing. */ +static sxi32 XmlNotify(ph7_xml_engine *pEngine, const char *zMethod, ph7_value **apArg, int nArg) { - sxi32 rc; - if(ph7_value_is_object(&pEngine->sHandler)) { - rc = XmlCallHandler(pEngine, zMethod, apArg, nArg); - } else { - rc = XmlCallCallback(pEngine, nSlot, apArg, nArg); - } + sxi32 rc = XmlCallHandler(pEngine, zMethod, apArg, nArg); if(rc != PH7_OK) { - pEngine->bAbort = TRUE; /* PH7_ABORT / PH7_EXCEPTION from a user handler */ + pEngine->bAbort = TRUE; } return rc; } @@ -173,17 +213,12 @@ static sxi32 XmlNotify(ph7_xml_engine *pEngine, int nSlot, const char *zMethod, /* ------------------------------------------------------------------ */ /* SAX values */ /* ------------------------------------------------------------------ */ -static ph7_value *VmXMLValue(ph7_xml_engine *pEngine, SyXMLRawStr *pXML, SyXMLRawStr *pNsUri) { +static ph7_value *VmXMLValue(ph7_xml_engine *pEngine, SyXMLRawStr *pXML) { ph7_value *pValue = ph7_context_new_scalar(pEngine->pCtx); if(pValue == 0) { PH7_VmMemoryError(pEngine->pCtx->pVm); return 0; } - if(pNsUri && pNsUri->nByte > 0) { - /* Dead in the typed API: every caller passes pNsUri == 0. Kept only so - * the reserved ns_sep field remains self-consistent. */ - ph7_value_string_format(pValue, "%.*s%c", pNsUri->nByte, pNsUri->zString, pEngine->ns_sep); - } ph7_value_string(pValue, pXML->zString, (int)pXML->nByte); return pValue; } @@ -225,10 +260,20 @@ static sxi32 VmXMLStartElementHandler(SyXMLRawStr *pStart, SyXMLRawStr *pNS, XmlTrackPos(pEngine, pStart); XmlSetString(pEngine, &pEngine->sLocalName, pStart->zString, (int)pStart->nByte); XmlSetString(pEngine, &pEngine->sNsUri, pNS ? pNS->zString : 0, pNS ? (int)pNS->nByte : 0); - XmlSetString(pEngine, &pEngine->sPrefix, pPrefix ? pPrefix->zString : 0, pPrefix ? (int)pPrefix->nByte : 0); + /* lib.c extracts the QName prefix independently of the namespace flag; + * expose it only when namespace processing is actually enabled. */ + if(pEngine->sParser.nFlags & SXML_ENABLE_NAMESPACE) { + XmlSetString(pEngine, &pEngine->sPrefix, pPrefix ? pPrefix->zString : 0, + pPrefix ? (int)pPrefix->nByte : 0); + } else { + XmlSetString(pEngine, &pEngine->sPrefix, "", 0); + } + if(XmlElemPush(pEngine) != SXRET_OK) { + return SXERR_ABORT; + } pEngine->bEmptyElement = bEmpty ? TRUE : FALSE; ++pEngine->nDepth; - pTag = VmXMLValue(pEngine, pStart, 0); /* local name only; never glue URI + separator */ + pTag = VmXMLValue(pEngine, pStart); /* local name only; never glue URI + separator */ pAttr = VmXMLAttrValue(pEngine, aAttr, nAttr); if(pTag == 0 || pAttr == 0) { return SXRET_OK; @@ -239,9 +284,12 @@ static sxi32 VmXMLStartElementHandler(SyXMLRawStr *pStart, SyXMLRawStr *pNS, apArg[0] = &pEngine->sReaderValue; apArg[1] = pTag; apArg[2] = pAttr; - (void)XmlNotify(pEngine, PH7_XML_START_TAG, "OnStartElement", apArg, 3); + (void)XmlNotify(pEngine, "OnStartElement", apArg, 3); ph7_context_release_value(pEngine->pCtx, pTag); ph7_context_release_value(pEngine->pCtx, pAttr); + /* Attributes are meaningful only while OnStartElement runs. */ + PH7_MemObjRelease(&pEngine->sAttrs); + PH7_MemObjInit(pEngine->pVm, &pEngine->sAttrs); return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } static sxi32 VmXMLEndElementHandler(SyXMLRawStr *pEnd, SyXMLRawStr *pNS, @@ -252,20 +300,27 @@ static sxi32 VmXMLEndElementHandler(SyXMLRawStr *pEnd, SyXMLRawStr *pNS, XmlTrackPos(pEngine, pEnd); XmlSetString(pEngine, &pEngine->sLocalName, pEnd->zString, (int)pEnd->nByte); XmlSetString(pEngine, &pEngine->sNsUri, pNS ? pNS->zString : 0, pNS ? (int)pNS->nByte : 0); - XmlSetString(pEngine, &pEngine->sPrefix, pPrefix ? pPrefix->zString : 0, - pPrefix ? (int)pPrefix->nByte : 0); + if(pEngine->sParser.nFlags & SXML_ENABLE_NAMESPACE) { + XmlSetString(pEngine, &pEngine->sPrefix, pPrefix ? pPrefix->zString : 0, + pPrefix ? (int)pPrefix->nByte : 0); + } else { + XmlSetString(pEngine, &pEngine->sPrefix, "", 0); + } pEngine->bEmptyElement = FALSE; if(pEngine->nDepth > 0) { --pEngine->nDepth; } - pTag = VmXMLValue(pEngine, pEnd, 0); + pTag = VmXMLValue(pEngine, pEnd); if(pTag == 0) { return SXRET_OK; } apArg[0] = &pEngine->sReaderValue; apArg[1] = pTag; - (void)XmlNotify(pEngine, PH7_XML_END_TAG, "OnEndElement", apArg, 2); + (void)XmlNotify(pEngine, "OnEndElement", apArg, 2); ph7_context_release_value(pEngine->pCtx, pTag); + XmlElemEnd(pEngine); + PH7_MemObjRelease(&pEngine->sAttrs); + PH7_MemObjInit(pEngine->pVm, &pEngine->sAttrs); return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } static sxi32 VmXMLTextHandler(SyXMLRawStr *pText, void *pUserData) { @@ -273,13 +328,14 @@ static sxi32 VmXMLTextHandler(SyXMLRawStr *pText, void *pUserData) { ph7_value *apArg[2]; ph7_value *pData; XmlTrackPos(pEngine, pText); - pData = VmXMLValue(pEngine, pText, 0); + /* LocalName/Prefix/NamespaceUri keep the innermost open element. */ + pData = VmXMLValue(pEngine, pText); if(pData == 0) { return SXRET_OK; } apArg[0] = &pEngine->sReaderValue; apArg[1] = pData; - (void)XmlNotify(pEngine, PH7_XML_CDATA, "OnText", apArg, 2); + (void)XmlNotify(pEngine, "OnText", apArg, 2); ph7_context_release_value(pEngine->pCtx, pData); return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } @@ -288,50 +344,68 @@ static sxi32 VmXMLPIHandler(SyXMLRawStr *pTargetStr, SyXMLRawStr *pDataStr, void ph7_value *apArg[3]; ph7_value *pTarget, *pData; XmlTrackPos(pEngine, pTargetStr); - pTarget = VmXMLValue(pEngine, pTargetStr, 0); - pData = VmXMLValue(pEngine, pDataStr, 0); + pTarget = VmXMLValue(pEngine, pTargetStr); + pData = VmXMLValue(pEngine, pDataStr); if(pTarget == 0 || pData == 0) { return SXRET_OK; } apArg[0] = &pEngine->sReaderValue; apArg[1] = pTarget; apArg[2] = pData; - (void)XmlNotify(pEngine, PH7_XML_PI, "OnProcessingInstruction", apArg, 3); + (void)XmlNotify(pEngine, "OnProcessingInstruction", apArg, 3); ph7_context_release_value(pEngine->pCtx, pTarget); ph7_context_release_value(pEngine->pCtx, pData); return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } +/* The default namespace is stored under a one-byte internal hash key. That + * sentinel is an implementation detail: map it back to the empty prefix before + * it reaches a typed OnStartNamespace/OnEndNamespace handler. lib.c sets the + * sentinel after invoking the start callback, so on that path this is purely + * defensive; the end callback reads the key straight from the hash entry and + * really does receive it. */ +static void XmlPublicNsPrefix(SyXMLRawStr *pOut, SyXMLRawStr *pIn) { + *pOut = *pIn; + if(pOut->nByte == SXML_DEFAULT_NS_KEY_LEN && pOut->zString != 0 && + SyMemcmp(pOut->zString, SXML_DEFAULT_NS_KEY_STR, SXML_DEFAULT_NS_KEY_LEN) == 0) { + pOut->zString = ""; + pOut->nByte = 0; + } +} /* lib.c forwards (prefix, uri) in that order. */ static sxi32 VmXMLNSStartHandler(SyXMLRawStr *pPrefixStr, SyXMLRawStr *pUriStr, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; + SyXMLRawStr sPrefix; ph7_value *apArg[3]; ph7_value *pPrefix, *pUri; - XmlTrackPos(pEngine, pPrefixStr); - pPrefix = VmXMLValue(pEngine, pPrefixStr, 0); - pUri = VmXMLValue(pEngine, pUriStr, 0); + XmlPublicNsPrefix(&sPrefix, pPrefixStr); + XmlTrackPos(pEngine, &sPrefix); + pPrefix = VmXMLValue(pEngine, &sPrefix); + pUri = VmXMLValue(pEngine, pUriStr); if(pPrefix == 0 || pUri == 0) { return SXRET_OK; } apArg[0] = &pEngine->sReaderValue; apArg[1] = pPrefix; apArg[2] = pUri; - (void)XmlNotify(pEngine, PH7_XML_NS_START, "OnStartNamespace", apArg, 3); + (void)XmlNotify(pEngine, "OnStartNamespace", apArg, 3); ph7_context_release_value(pEngine->pCtx, pPrefix); ph7_context_release_value(pEngine->pCtx, pUri); return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } static sxi32 VmXMLNSEndHandler(SyXMLRawStr *pPrefixStr, void *pUserData) { ph7_xml_engine *pEngine = (ph7_xml_engine *)pUserData; + SyXMLRawStr sPrefix; ph7_value *apArg[2]; ph7_value *pPrefix; - XmlTrackPos(pEngine, pPrefixStr); - pPrefix = VmXMLValue(pEngine, pPrefixStr, 0); + XmlPublicNsPrefix(&sPrefix, pPrefixStr); + XmlTrackPos(pEngine, &sPrefix); + pPrefix = VmXMLValue(pEngine, &sPrefix); if(pPrefix == 0) { return SXRET_OK; } apArg[0] = &pEngine->sReaderValue; apArg[1] = pPrefix; - (void)XmlNotify(pEngine, PH7_XML_NS_END, "OnEndNamespace", apArg, 2); + (void)XmlNotify(pEngine, "OnEndNamespace", apArg, 2); ph7_context_release_value(pEngine->pCtx, pPrefix); return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } @@ -340,13 +414,13 @@ static sxi32 VmXMLDoctypeHandler(SyXMLRawStr *pRaw, void *pUserData) { ph7_value *apArg[2]; ph7_value *pText; XmlTrackPos(pEngine, pRaw); - pText = VmXMLValue(pEngine, pRaw, 0); /* raw text is not NUL-terminated */ + pText = VmXMLValue(pEngine, pRaw); /* raw text is not NUL-terminated */ if(pText == 0) { return SXRET_OK; } apArg[0] = &pEngine->sReaderValue; apArg[1] = pText; - (void)XmlNotify(pEngine, PH7_XML_DOCTYPE, "OnDoctype", apArg, 2); + (void)XmlNotify(pEngine, "OnDoctype", apArg, 2); ph7_context_release_value(pEngine->pCtx, pText); return pEngine->bAbort ? SXERR_ABORT : SXRET_OK; } @@ -393,14 +467,61 @@ static sxi32 VmXMLErrorHandler(const char *zMessage, sxi32 iErrCode, SyToken *pT /* ------------------------------------------------------------------ */ /* XmlException support */ /* ------------------------------------------------------------------ */ -static int XmlThrowException(ph7_context *pCtx, ph7_xml_engine *pEngine) { +/* Fetch an inherited (protected/private) attribute slot straight off the + * instance, exactly as the JSON module does. */ +static ph7_value *XmlInstField(ph7_class_instance *pInst, const char *zName) { + SyString s; + if(pInst == 0) { + return 0; + } + SyStringInitFromBuf(&s, zName, (sxu32)SyStrlen(zName)); + return PH7_ClassInstanceFetchAttr(pInst, &s); +} +/* Stamp the inherited Exception file/line with the first script frame of the + * active call stack. Native frames ([NATIVE], line 0) are skipped so the base + * getters describe the place in the script that raised the error, not the + * SAX input position (which lives in inputLine/inputColumn). */ +static void XmlStampSite(ph7_vm *pVm, ph7_class_instance *pInst) { + SySet sTrace; + VmDebugTrace *pTrace; + ph7_value *pField; + if(VmExtractDebugTrace(pVm, &sTrace) != SXRET_OK) { + return; + } + while(SySetGetNextEntry(&sTrace, (void **)&pTrace) == SXRET_OK) { + if(pTrace->pFile == 0 || pTrace->nLine == 0) { + continue; + } + if(pTrace->pFile->nByte == sizeof("[NATIVE]") - 1 && + SyMemcmp(pTrace->pFile->zString, "[NATIVE]", sizeof("[NATIVE]") - 1) == 0) { + continue; + } + pField = XmlInstField(pInst, "file"); + if(pField) { + PH7_MemObjRelease(pField); + PH7_MemObjInit(pVm, pField); + (void)ph7_value_string(pField, pTrace->pFile->zString, (int)pTrace->pFile->nByte); + } + pField = XmlInstField(pInst, "line"); + if(pField) { + (void)ph7_value_int64(pField, (ph7_int64)pTrace->nLine); + } + break; + } + SySetRelease(&sTrace); +} +/* Throw a real XmlException object with the given code/message and input + * position. Temporary scalars are always released and the instance reference + * dropped on every error path. */ +static int XmlThrow(ph7_context *pCtx, int nErr, const char *zMsg, + sxu32 nLine, sxu32 nCol) { ph7_vm *pVm = pCtx->pVm; ph7_class *pClass; - ph7_class_instance *pInst = 0; + ph7_class_instance *pInst; ph7_class_method *pCons; - ph7_value *pObj, *apArg[4]; - ph7_value *pMsg, *pCode, *pLine, *pCol; + ph7_value *pObj, *apArg[4], *aTmp[4]; sxi32 rc; + sxu32 n; if(pVm->iPendingTransfer) { return PH7_EXCEPTION; /* a handler exception takes precedence */ } @@ -410,39 +531,71 @@ static int XmlThrowException(ph7_context *pCtx, ph7_xml_engine *pEngine) { } pInst = PH7_NewClassInstance(pVm, pClass); if(pInst == 0) { + PH7_VmMemoryError(pVm); return PH7_ABORT; } + for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) { + aTmp[n] = ph7_context_new_scalar(pCtx); + if(aTmp[n] == 0) { + while(n > 0) { + --n; + ph7_context_release_value(pCtx, aTmp[n]); + } + PH7_ClassInstanceUnref(pInst); + PH7_VmMemoryError(pVm); + return PH7_ABORT; + } + } + pObj = ph7_context_new_scalar(pCtx); + if(pObj == 0) { + for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) { + ph7_context_release_value(pCtx, aTmp[n]); + } + PH7_ClassInstanceUnref(pInst); + PH7_VmMemoryError(pVm); + return PH7_ABORT; + } + ph7_value_string(aTmp[0], zMsg, -1); + ph7_value_int64(aTmp[1], nErr); + ph7_value_int64(aTmp[2], (ph7_int64)nLine); + ph7_value_int64(aTmp[3], (ph7_int64)nCol); + for(n = 0 ; n < SX_ARRAYSIZE(apArg) ; ++n) { + apArg[n] = aTmp[n]; + } pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1); - pMsg = ph7_context_new_scalar(pCtx); - pCode = ph7_context_new_scalar(pCtx); - pLine = ph7_context_new_scalar(pCtx); - pCol = ph7_context_new_scalar(pCtx); - pObj = ph7_context_new_scalar(pCtx); - if(pMsg == 0 || pCode == 0 || pLine == 0 || pCol == 0 || pObj == 0) { - return PH7_ABORT; - } - ph7_value_string(pMsg, SyBlobData(&pEngine->sErr), (int)SyBlobLength(&pEngine->sErr)); - ph7_value_int64(pCode, pEngine->iErrCode); - ph7_value_int64(pLine, pEngine->nErrLine); - ph7_value_int64(pCol, pEngine->nErrCol); - apArg[0] = pMsg; - apArg[1] = pCode; - apArg[2] = pLine; - apArg[3] = pCol; if(pCons) { rc = PH7_VmCallClassMethod(pVm, pInst, pCons, 0, 4, apArg); if(pInst->iRef < 1) { pInst->iRef = 1; } - if(rc != SXRET_OK) { + for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) { + ph7_context_release_value(pCtx, aTmp[n]); + } + if(rc != PH7_OK) { + ph7_context_release_value(pCtx, pObj); + PH7_ClassInstanceUnref(pInst); return rc; } + } else { + for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) { + ph7_context_release_value(pCtx, aTmp[n]); + } + } + /* Base Exception fields describe the throwing script, not the XML input. */ + XmlStampSite(pVm, pInst); + if(pInst->iRef < 1) { + pInst->iRef = 1; } PH7_MemObjRelease(pObj); pObj->x.pOther = pInst; MemObjSetType(pObj, MEMOBJ_OBJ); - (void)ph7_result_value(pCtx, pObj); - return PH7_EXCEPTION; + rc = ph7_result_value(pCtx, pObj); + ph7_context_release_value(pCtx, pObj); + return rc == PH7_OK ? PH7_EXCEPTION : rc; +} +static int XmlReentryGuard(ph7_context *pCtx) { + return XmlThrow(pCtx, SXML_ERROR_INVALID_OPERATION, + "XmlReader cannot be modified while Parse() is running", 0, 0); } /* ------------------------------------------------------------------ */ @@ -455,26 +608,25 @@ static int XmlHandlerNoop(ph7_context *pCtx, int nArg, ph7_value **apArg) { return PH7_OK; /* void result */ } static int XmlExceptionConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { - static const char *const azField[] = { "xmlMessage", "xmlCode", "xmlLine", "xmlColumn" }; + ph7_vm *pVm = pCtx->pVm; + ph7_class *pBase; + ph7_class_method *pCons; ph7_value *pThis = ph7_context_this(pCtx); sxi32 rc; - sxu32 n; SXUNUSED(nArg); - for(n = 0 ; n < SX_ARRAYSIZE(azField) ; ++n) { - rc = ph7_context_attr_store(pCtx, pThis, 0, azField[n], apArg[n]); - if(rc != PH7_OK) { - return rc; - } - } - /* Mirror the three fields inherited Exception::getMessage()/getCode()/ - * getLine() read, so catch(Exception $e) observes the same values as the - * typed getters. apArg[2] is the line; apArg[3] is the column. */ - rc = ph7_context_attr_store(pCtx, pThis, 0, "message", apArg[0]); - if(rc != PH7_OK) { return rc; } - rc = ph7_context_attr_store(pCtx, pThis, 0, "code", apArg[1]); - if(rc != PH7_OK) { return rc; } - rc = ph7_context_attr_store(pCtx, pThis, 0, "line", apArg[2]); - if(rc != PH7_OK) { return rc; } + /* Run the base constructor so message/code/file/line/trace/previous keep + * ordinary Exception semantics for directly constructed instances. */ + pBase = PH7_VmExtractClass(pVm, "Exception", sizeof("Exception") - 1, FALSE); + if(pBase == 0) return PH7_ABORT; + pCons = PH7_ClassExtractMethod(pBase, "__construct", sizeof("__construct") - 1); + if(pCons == 0) return PH7_ABORT; + rc = PH7_VmCallClassMethod(pVm, (ph7_class_instance *)pThis->x.pOther, pCons, 0, 2, apArg); + if(rc != PH7_OK) return rc; + /* XML-specific 1-based input position, independent of the script site. */ + rc = ph7_context_attr_store(pCtx, pThis, 0, "inputLine", apArg[2]); + if(rc != PH7_OK) return rc; + rc = ph7_context_attr_store(pCtx, pThis, 0, "inputColumn", apArg[3]); + if(rc != PH7_OK) return rc; return PH7_OK; } static int XmlExceptionField(ph7_context *pCtx, int nArg, ph7_value **apArg) { @@ -514,6 +666,8 @@ static int XmlExceptionGetDescription(ph7_context *pCtx, int nArg, ph7_value **a case SXML_ERROR_UNKNOWN_ENCODING: return ph7_result_string(pCtx, "Unknown encoding", -1); case SXML_ERROR_UNCLOSED_CDATA_SECTION: return ph7_result_string(pCtx, "Unclosed CDATA section", -1); case SXML_ERROR_EXTERNAL_ENTITY_HANDLING: return ph7_result_string(pCtx, "External entity handling", -1); + case SXML_ERROR_INVALID_OPERATION: return ph7_result_string(pCtx, "Invalid operation", -1); + case SXML_ERROR_TYPE_MISMATCH: return ph7_result_string(pCtx, "Type mismatch", -1); default: return ph7_result_string(pCtx, "Unknown error code", -1); } } @@ -535,8 +689,17 @@ static ph7_xml_engine *XmlReaderEngine(ph7_context *pCtx) { ph7_context_release_value(pCtx, pRes); return pEngine; } -static int XmlReaderCreate(ph7_context *pCtx, int process_ns, int ns_sep) { - ph7_xml_engine *pEngine = VmCreateXMLEngine(pCtx, process_ns, ns_sep); +/* Every public accessor shares the same closed-reader diagnostic. */ +static ph7_xml_engine *XmlReaderEngineOrThrow(ph7_context *pCtx) { + ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + if(pEngine == 0) { + (void)XmlThrow(pCtx, SXML_ERROR_INVALID_OPERATION, "XmlReader is closed", 0, 0); + return 0; + } + return pEngine; +} +static int XmlReaderCreate(ph7_context *pCtx, int process_ns) { + ph7_xml_engine *pEngine = VmCreateXMLEngine(pCtx, process_ns); ph7_value *pRes; if(pEngine == 0) { PH7_VmMemoryError(pCtx->pVm); @@ -560,25 +723,12 @@ static int XmlReaderCreate(ph7_context *pCtx, int process_ns, int ns_sep) { return PH7_OK; } } -static int XmlReaderConstruct0(ph7_context *pCtx, int nArg, ph7_value **apArg) { - SXUNUSED(nArg); - SXUNUSED(apArg); - return XmlReaderCreate(pCtx, FALSE, ':'); +static int XmlReaderConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + /* A single bool argument defaults to FALSE; there is no separator knob. */ + return XmlReaderCreate(pCtx, + nArg > 0 && ph7_value_to_bool(apArg[0]) ? TRUE : FALSE); } -static int XmlReaderConstruct2(ph7_context *pCtx, int nArg, ph7_value **apArg) { - /* $separator is accepted for API compatibility but reserved/ignored: the - * typed getters forward the QName components verbatim instead of gluing - * URI + separator + local name. */ - int ns_sep = ':'; - if(nArg > 1 && ph7_value_is_string(apArg[1])) { - const char *zSep = ph7_value_to_string(apArg[1], 0); - if(zSep && zSep[0] != 0) { - ns_sep = zSep[0]; - } - } - return XmlReaderCreate(pCtx, ph7_value_to_bool(apArg[0]) ? TRUE : FALSE, ns_sep); -} -static int XmlReaderCloseCtx(ph7_context *pCtx) { +static int XmlReaderCloseCtx(ph7_context *pCtx, int bDestruct) { ph7_value *pRes = ph7_context_new_scalar(pCtx); ph7_xml_engine *pEngine; if(pRes == 0) { @@ -588,8 +738,15 @@ static int XmlReaderCloseCtx(ph7_context *pCtx) { ph7_value_is_resource(pRes)) { pEngine = (ph7_xml_engine *)ph7_value_to_resource(pRes); if(!IS_INVALID_XML_ENGINE(pEngine)) { + if(pEngine->iNest > 0) { + /* sReaderValue still owns a reference; an explicit Close() is + * rejected while Parse() is running, while __destruct simply + * leaves the engine alive for the active Parse(). */ + ph7_context_release_value(pCtx, pRes); + return bDestruct ? PH7_OK : XmlReentryGuard(pCtx); + } VmReleaseXMLEngine(pEngine); - ph7_value_resource(pRes, 0); /* invalidate: future access is harmless */ + ph7_value_resource(pRes, 0); /* invalidate: future access throws */ (void)ph7_context_attr_store(pCtx, ph7_context_this(pCtx), 0, "resource", pRes); } } @@ -599,33 +756,35 @@ static int XmlReaderCloseCtx(ph7_context *pCtx) { static int XmlReaderClose(ph7_context *pCtx, int nArg, ph7_value **apArg) { SXUNUSED(nArg); SXUNUSED(apArg); - return XmlReaderCloseCtx(pCtx); + return XmlReaderCloseCtx(pCtx, 0); } static int XmlReaderDestruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { SXUNUSED(nArg); SXUNUSED(apArg); - return XmlReaderCloseCtx(pCtx); + return XmlReaderCloseCtx(pCtx, 1); } static int XmlReaderParse(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_xml_engine *pEngine; SyXMLParser *pParser; const char *zData; int nByte; - SXUNUSED(nArg); /* isFinal stays ignored, as in the underlying engine */ + /* XTY(MIXED) keeps non-string arguments out of the VM's overload filter so + * this callback can report a typed diagnostic for them. */ if(nArg < 1 || !ph7_value_is_string(apArg[0])) { - return PH7_ABORT; + return XmlThrow(pCtx, SXML_ERROR_TYPE_MISMATCH, + "XmlReader::Parse() expects a string", 0, 0); } - pEngine = XmlReaderEngine(pCtx); + pEngine = XmlReaderEngineOrThrow(pCtx); if(pEngine == 0) { - return PH7_ABORT; + return PH7_EXCEPTION; } if(pEngine->iNest > 0) { - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "Recursive call to %s, PH7 is returning false", ph7_function_name(pCtx)); - return PH7_ABORT; + return XmlThrow(pCtx, SXML_ERROR_INVALID_OPERATION, + "Parse() cannot be called recursively", 0, 0); } pEngine->pCtx = pCtx; /* Reset all transient state, including after a previous abort. */ + XmlElemStackClear(pEngine); pEngine->iErrCode = SXML_ERROR_NONE; pEngine->bError = FALSE; pEngine->bAbort = FALSE; @@ -661,7 +820,10 @@ static int XmlReaderParse(ph7_context *pCtx, int nArg, ph7_value **apArg) { return PH7_EXCEPTION; /* exception from a user handler */ } if(pEngine->bError) { - return XmlThrowException(pCtx, pEngine); + /* Make the SAX message NUL-terminated for the typed scalar. */ + SyBlobNullAppend(&pEngine->sErr); + return XmlThrow(pCtx, pEngine->iErrCode, SyBlobData(&pEngine->sErr), + pEngine->nErrLine, pEngine->nErrCol); } if(pEngine->bAbort) { return PH7_ABORT; /* e.g. exit() from OnDoctype rejects the document */ @@ -669,52 +831,52 @@ static int XmlReaderParse(ph7_context *pCtx, int nArg, ph7_value **apArg) { return PH7_OK; /* void */ } static int XmlReaderCurrentLine(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SXUNUSED(nArg); SXUNUSED(apArg); - return pEngine ? ph7_result_int64(pCtx, pEngine->nCurLine) : PH7_ABORT; + return pEngine ? ph7_result_int64(pCtx, pEngine->nCurLine) : PH7_EXCEPTION; } static int XmlReaderCurrentByteIndex(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SXUNUSED(nArg); SXUNUSED(apArg); - return pEngine ? ph7_result_int64(pCtx, pEngine->iCurByte) : PH7_ABORT; + return pEngine ? ph7_result_int64(pCtx, pEngine->iCurByte) : PH7_EXCEPTION; } static int XmlReaderCurrentColumn(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SXUNUSED(nArg); SXUNUSED(apArg); - return pEngine ? ph7_result_int64(pCtx, pEngine->nCurCol) : PH7_ABORT; + return pEngine ? ph7_result_int64(pCtx, pEngine->nCurCol) : PH7_EXCEPTION; } static int XmlReaderDepth(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SXUNUSED(nArg); SXUNUSED(apArg); - return pEngine ? ph7_result_int64(pCtx, pEngine->nDepth) : PH7_ABORT; + return pEngine ? ph7_result_int64(pCtx, pEngine->nDepth) : PH7_EXCEPTION; } static int XmlReaderIsEmptyElement(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SXUNUSED(nArg); SXUNUSED(apArg); - return pEngine ? ph7_result_bool(pCtx, pEngine->bEmptyElement) : PH7_ABORT; + return pEngine ? ph7_result_bool(pCtx, pEngine->bEmptyElement) : PH7_EXCEPTION; } static int XmlReaderStringField(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_xml_engine *pEngine; SXUNUSED(nArg); SXUNUSED(apArg); - pEngine = XmlReaderEngine(pCtx); + pEngine = XmlReaderEngineOrThrow(pCtx); if(pEngine == 0) { - return PH7_ABORT; + return PH7_EXCEPTION; } return ph7_result_value(pCtx, (ph7_value *)((char *)pEngine + (size_t)(uintptr_t)ph7_context_user_data(pCtx))); } static int XmlReaderGetAttributeCount(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SXUNUSED(nArg); SXUNUSED(apArg); if(pEngine == 0) { - return PH7_ABORT; + return PH7_EXCEPTION; } return ph7_result_int64(pCtx, ph7_value_is_array(&pEngine->sAttrs) ? ph7_array_count(&pEngine->sAttrs) : 0); } @@ -735,12 +897,12 @@ static int XmlAttrWalker(ph7_value *pKey, ph7_value *pValue, void *pUserData) { return 0; } static int XmlReaderAttributeAt(ph7_context *pCtx, int nArg, ph7_value **apArg, int wantName) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); ph7_value *pName, *pValue, *pOut; struct XmlAttrWalk sWalk; SXUNUSED(nArg); if(pEngine == 0) { - return PH7_ABORT; + return PH7_EXCEPTION; } pName = ph7_context_new_scalar(pCtx); pValue = ph7_context_new_scalar(pCtx); @@ -764,13 +926,13 @@ static int XmlReaderGetAttributeValue(ph7_context *pCtx, int nArg, ph7_value **a return XmlReaderAttributeAt(pCtx, nArg, apArg, FALSE); } static int XmlReaderGetAttribute(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); ph7_value *pValue; int nLen; const char *zName; SXUNUSED(nArg); if(pEngine == 0) { - return PH7_ABORT; + return PH7_EXCEPTION; } zName = ph7_value_to_string(apArg[0], &nLen); if(ph7_context_status(pCtx) != PH7_OK) { @@ -780,13 +942,13 @@ static int XmlReaderGetAttribute(ph7_context *pCtx, int nArg, ph7_value **apArg) return pValue ? ph7_result_value(pCtx, pValue) : ph7_result_string(pCtx, "", 0); } static int XmlReaderHasAttribute(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); ph7_value *pValue; int nLen; const char *zName; SXUNUSED(nArg); if(pEngine == 0) { - return PH7_ABORT; + return PH7_EXCEPTION; } zName = ph7_value_to_string(apArg[0], &nLen); if(ph7_context_status(pCtx) != PH7_OK) { @@ -796,21 +958,21 @@ static int XmlReaderHasAttribute(ph7_context *pCtx, int nArg, ph7_value **apArg) return ph7_result_bool(pCtx, pValue != 0); } static int XmlReaderLookupNamespace(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SyHashEntry *pEntry; const char *zPrefix; int nLen; SXUNUSED(nArg); if(pEngine == 0) { - return PH7_ABORT; + return PH7_EXCEPTION; } zPrefix = ph7_value_to_string(apArg[0], &nLen); if(ph7_context_status(pCtx) != PH7_OK) { return ph7_context_status(pCtx); } if(nLen == 0) { - zPrefix = "Default"; - nLen = sizeof("Default") - 1; + zPrefix = SXML_DEFAULT_NS_KEY_STR; + nLen = SXML_DEFAULT_NS_KEY_LEN; } /* Visibility is limited to the current element: lib.c removes the hash * entry in XMLnsUnlink() when the element closes. */ @@ -822,47 +984,32 @@ static int XmlReaderLookupNamespace(ph7_context *pCtx, int nArg, ph7_value **apA return ph7_result_string(pCtx, "", 0); } static int XmlReaderSetHandler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SXUNUSED(nArg); if(pEngine == 0) { - return PH7_ABORT; + return PH7_EXCEPTION; + } + if(pEngine->iNest > 0) { + return XmlReentryGuard(pCtx); } PH7_MemObjRelease(&pEngine->sHandler); PH7_MemObjInit(pCtx->pVm, &pEngine->sHandler); PH7_MemObjStore(apArg[0], &pEngine->sHandler); return PH7_OK; } -static int XmlReaderSetCallback(ph7_context *pCtx, int nArg, ph7_value **apArg) { - int nSlot = (int)(long)ph7_context_user_data(pCtx); - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); - SXUNUSED(nArg); - if(pEngine == 0 || nSlot < 0 || nSlot >= XML_TOTAL_HANDLER) { - return PH7_ABORT; - } - PH7_MemObjRelease(&pEngine->aCB[nSlot]); - PH7_MemObjInit(pCtx->pVm, &pEngine->aCB[nSlot]); - PH7_MemObjStore(apArg[0], &pEngine->aCB[nSlot]); - return PH7_OK; -} static int XmlReaderClearHandler(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); + ph7_xml_engine *pEngine = XmlReaderEngineOrThrow(pCtx); SXUNUSED(nArg); SXUNUSED(apArg); - if(pEngine == 0) return PH7_ABORT; + if(pEngine == 0) { + return PH7_EXCEPTION; + } + if(pEngine->iNest > 0) { + return XmlReentryGuard(pCtx); + } PH7_MemObjRelease(&pEngine->sHandler); PH7_MemObjInit(pCtx->pVm, &pEngine->sHandler); return PH7_OK; /* void */ } -static int XmlReaderClearCallbacks(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_xml_engine *pEngine = XmlReaderEngine(pCtx); - sxu32 n; - SXUNUSED(nArg); SXUNUSED(apArg); - if(pEngine == 0) return PH7_ABORT; - for(n = 0 ; n < SX_ARRAYSIZE(pEngine->aCB) ; ++n) { - PH7_MemObjRelease(&pEngine->aCB[n]); - PH7_MemObjInit(pCtx->pVm, &pEngine->aCB[n]); - } - return PH7_OK; /* void */ -} /* ------------------------------------------------------------------ */ /* Native class registration */ @@ -895,7 +1042,9 @@ static ph7_constant_def aExceptionConst[] = { { "ERROR_UNKNOWN_ENCODING", 0, PH7_MEMBER_PUBLIC, 0, 0 }, { "ERROR_INCORRECT_ENCODING", 0, PH7_MEMBER_PUBLIC, 0, 0 }, { "ERROR_UNCLOSED_CDATA_SECTION", 0, PH7_MEMBER_PUBLIC, 0, 0 }, - { "ERROR_EXTERNAL_ENTITY_HANDLING", 0, PH7_MEMBER_PUBLIC, 0, 0 } + { "ERROR_EXTERNAL_ENTITY_HANDLING", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_INVALID_OPERATION", 0, PH7_MEMBER_PUBLIC, 0, 0 }, + { "ERROR_TYPE_MISMATCH", 0, PH7_MEMBER_PUBLIC, 0, 0 } }; /* Same order as aExceptionConst and enum xml_err_code. */ static const int aExceptionConstValue[] = { @@ -907,23 +1056,19 @@ static const int aExceptionConstValue[] = { SXML_ERROR_BAD_CHAR_REF, SXML_ERROR_BINARY_ENTITY_REF, SXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, SXML_ERROR_MISPLACED_XML_PI, SXML_ERROR_UNKNOWN_ENCODING, SXML_ERROR_INCORRECT_ENCODING, - SXML_ERROR_UNCLOSED_CDATA_SECTION, SXML_ERROR_EXTERNAL_ENTITY_HANDLING + SXML_ERROR_UNCLOSED_CDATA_SECTION, SXML_ERROR_EXTERNAL_ENTITY_HANDLING, + SXML_ERROR_INVALID_OPERATION, SXML_ERROR_TYPE_MISMATCH }; static sxi32 XmlRegisterClasses(ph7_vm *pVm) { static const ph7_param_def aReaderInt[] = { XP("index", INT) }; static const ph7_param_def aReaderString[] = { XP("name", STRING) }; static const ph7_param_def aReaderPrefix[] = { XP("prefix", STRING) }; - static ph7_param_def aCtor2[] = { - XP("namespaces", BOOL), { "separator", XTY(STRING), 0, 0, 0, 0 } - }; - static ph7_param_def aParse[] = { - XP("data", STRING), { "isFinal", XTY(BOOL), 0, 0, 0, 0 } - }; + static ph7_param_def aCtor[] = { XP("namespaces", BOOL) }; + static const ph7_param_def aParse[] = { XP("data", MIXED) }; static const ph7_param_def aSetHandler[] = { { "handler", XNM("IXmlHandler"), 0, 0, 0, 0 } }; - static const ph7_param_def aCallback[] = { XP("fn", CALLBACK) }; - static const ph7_param_def aExcCtor[] = { - XP("message", STRING), XP("code", INT), XP("line", INT), XP("column", INT) + static ph7_param_def aExcCtor[] = { + XP("message", STRING), XP("code", INT), XP("inputLine", INT), XP("inputColumn", INT) }; static const ph7_param_def aExcDesc[] = { XP("code", INT) }; /* IXmlHandler signatures */ @@ -978,27 +1123,25 @@ static sxi32 XmlRegisterClasses(ph7_vm *pVm) { { "OnError", XTY(VOID), aOnError, 4, XmlHandlerNoop, 0, PH7_MEMBER_PUBLIC } }; static const char *const aHandlerIf[] = { "IXmlHandler" }; + /* Declared private fields are required: PH7_VmContextAttr() resolves + * attributes through the class table, so a dynamic attr_store() alone + * would fail. The base Exception supplies message/code/file/line. */ static const ph7_field_def aExcField[] = { - { "xmlMessage", XTY(STRING), 0, PH7_MEMBER_PRIVATE, 0, 0 }, - { "xmlCode", XTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, - { "xmlLine", XTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, - { "xmlColumn", XTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 } + { "inputLine", XTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 }, + { "inputColumn", XTY(INT), 0, PH7_MEMBER_PRIVATE, 0, 0 } }; static const char *const aExcBase[] = { "Exception" }; static const ph7_method_def aExcMethod[] = { { "__construct", XTY(VOID), aExcCtor, 4, XmlExceptionConstruct, 0, 0 }, - { "GetMessage", XTY(STRING), 0, 0, XmlExceptionField, (void *)"xmlMessage", PH7_MEMBER_PUBLIC }, - { "GetCode", XTY(INT), 0, 0, XmlExceptionField, (void *)"xmlCode", PH7_MEMBER_PUBLIC }, - { "GetLine", XTY(INT), 0, 0, XmlExceptionField, (void *)"xmlLine", PH7_MEMBER_PUBLIC }, - { "GetColumn", XTY(INT), 0, 0, XmlExceptionField, (void *)"xmlColumn", PH7_MEMBER_PUBLIC }, + { "GetInputLine", XTY(INT), 0, 0, XmlExceptionField, (void *)"inputLine", PH7_MEMBER_PUBLIC }, + { "GetInputColumn", XTY(INT), 0, 0, XmlExceptionField, (void *)"inputColumn", PH7_MEMBER_PUBLIC }, { "GetDescription", XTY(STRING), aExcDesc, 1, XmlExceptionGetDescription, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC } }; /* XmlReader methods */ static const ph7_method_def aReaderMethod[] = { - { "__construct", XTY(VOID), 0, 0, XmlReaderConstruct0, 0, 0 }, - { "__construct", XTY(VOID), aCtor2, 2, XmlReaderConstruct2, 0, 0 }, - { "Parse", XTY(VOID), aParse, 2, XmlReaderParse, 0, PH7_MEMBER_PUBLIC }, + { "__construct", XTY(VOID), aCtor, 1, XmlReaderConstruct, 0, 0 }, + { "Parse", XTY(VOID), aParse, 1, XmlReaderParse, 0, PH7_MEMBER_PUBLIC }, { "Close", XTY(VOID), 0, 0, XmlReaderClose, 0, PH7_MEMBER_PUBLIC }, { "__destruct", XTY(VOID), 0, 0, XmlReaderDestruct, 0, 0 }, { "CurrentLine", XTY(INT), 0, 0, XmlReaderCurrentLine, 0, PH7_MEMBER_PUBLIC }, @@ -1016,15 +1159,7 @@ static sxi32 XmlRegisterClasses(ph7_vm *pVm) { { "HasAttribute", XTY(BOOL), aReaderString, 1, XmlReaderHasAttribute, 0, PH7_MEMBER_PUBLIC }, { "LookupNamespace", XTY(STRING), aReaderPrefix, 1, XmlReaderLookupNamespace, 0, PH7_MEMBER_PUBLIC }, { "SetHandler", XTY(VOID), aSetHandler, 1, XmlReaderSetHandler, 0, PH7_MEMBER_PUBLIC }, - { "ClearHandler", XTY(VOID), 0, 0, XmlReaderClearHandler, 0, PH7_MEMBER_PUBLIC }, - { "ClearCallbacks", XTY(VOID), 0, 0, XmlReaderClearCallbacks, 0, PH7_MEMBER_PUBLIC }, - { "OnStartElement", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_START_TAG, PH7_MEMBER_PUBLIC }, - { "OnEndElement", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_END_TAG, PH7_MEMBER_PUBLIC }, - { "OnText", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_CDATA, PH7_MEMBER_PUBLIC }, - { "OnProcessingInstruction", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_PI, PH7_MEMBER_PUBLIC }, - { "OnStartNamespace", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_NS_START, PH7_MEMBER_PUBLIC }, - { "OnEndNamespace", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_NS_END, PH7_MEMBER_PUBLIC }, - { "OnDoctype", XTY(VOID), aCallback, 1, XmlReaderSetCallback, (void *)(long)PH7_XML_DOCTYPE, PH7_MEMBER_PUBLIC } + { "ClearHandler", XTY(VOID), 0, 0, XmlReaderClearHandler, 0, PH7_MEMBER_PUBLIC } }; static const ph7_field_def aReaderField[] = { { "resource", XTY(RESOURCE), 0, PH7_MEMBER_PRIVATE, 0, 0 } @@ -1042,15 +1177,19 @@ static sxi32 XmlRegisterClasses(ph7_vm *pVm) { ph7_class_def sReader = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, "XmlReader", aReaderField, SX_ARRAYSIZE(aReaderField), 0, 0, aReaderMethod, SX_ARRAYSIZE(aReaderMethod), 0, 0, 0, 0, 0, 0, 0 }; - ph7_value *pSep = ph7_new_scalar(pVm); - ph7_value *pTrue = ph7_new_scalar(pVm); + ph7_value *aDefault[SX_ARRAYSIZE(aExcCtor) + 1]; ph7_value *apErrVal[SX_ARRAYSIZE(aExceptionConst)]; sxu32 n; sxi32 rc; - if(pSep == 0 || pTrue == 0) { - if(pSep) ph7_release_value(pVm, pSep); - if(pTrue) ph7_release_value(pVm, pTrue); - return PH7_ABORT; + for(n = 0 ; n < SX_ARRAYSIZE(aDefault) ; ++n) { + aDefault[n] = ph7_new_scalar(pVm); + if(aDefault[n] == 0) { + while(n > 0) { + --n; + ph7_release_value(pVm, aDefault[n]); + } + return PH7_ABORT; + } } for(n = 0 ; n < SX_ARRAYSIZE(aExceptionConst) ; ++n) { apErrVal[n] = ph7_new_scalar(pVm); @@ -1060,17 +1199,20 @@ static sxi32 XmlRegisterClasses(ph7_vm *pVm) { ph7_release_value(pVm, apErrVal[n]); aExceptionConst[n].pValue = 0; } - ph7_release_value(pVm, pSep); - ph7_release_value(pVm, pTrue); + for(n = 0 ; n < SX_ARRAYSIZE(aDefault) ; ++n) { + ph7_release_value(pVm, aDefault[n]); + } return PH7_ABORT; } ph7_value_int(apErrVal[n], aExceptionConstValue[n]); aExceptionConst[n].pValue = apErrVal[n]; } - ph7_value_string(pSep, ":", 1); - ph7_value_bool(pTrue, 1); - aCtor2[1].pDefault = pSep; - aParse[1].pDefault = pTrue; + ph7_value_bool(aDefault[0], 0); /* XmlReader(bool namespaces = false) */ + ph7_value_int(aDefault[1], 0); /* inputLine = 0 */ + ph7_value_int(aDefault[2], 0); /* inputColumn = 0 */ + aCtor[0].pDefault = aDefault[0]; + aExcCtor[2].pDefault = aDefault[1]; + aExcCtor[3].pDefault = aDefault[2]; rc = ph7_create_class(pVm, &sIface); if(rc == PH7_OK) rc = ph7_create_class(pVm, &sHandler); if(rc == PH7_OK) rc = ph7_create_class(pVm, &sExc); @@ -1079,10 +1221,12 @@ static sxi32 XmlRegisterClasses(ph7_vm *pVm) { ph7_release_value(pVm, apErrVal[n]); aExceptionConst[n].pValue = 0; /* static table: no dangling pointer across VMs */ } - aCtor2[1].pDefault = 0; - aParse[1].pDefault = 0; - ph7_release_value(pVm, pSep); - ph7_release_value(pVm, pTrue); + aCtor[0].pDefault = 0; + aExcCtor[2].pDefault = 0; + aExcCtor[3].pDefault = 0; + for(n = 0 ; n < SX_ARRAYSIZE(aDefault) ; ++n) { + ph7_release_value(pVm, aDefault[n]); + } return rc; } diff --git a/modules/xml/xml.h b/modules/xml/xml.h index ce8a2ed..b10bf6d 100644 --- a/modules/xml/xml.h +++ b/modules/xml/xml.h @@ -16,22 +16,17 @@ #define MODULE_DESC "XML Module" #define MODULE_VER 1.0 -#define XML_TOTAL_HANDLER (PH7_XML_DOCTYPE + 1) #define XML_ENGINE_MAGIC 0x851EFC52 #define IS_INVALID_XML_ENGINE(XML) (XML == 0 || (XML)->nMagic != XML_ENGINE_MAGIC) -enum ph7_xml_handler_id { - PH7_XML_START_TAG = 0, /* Start element */ - PH7_XML_END_TAG, /* End element */ - PH7_XML_CDATA, /* Character data */ - PH7_XML_PI, /* Processing instruction */ - PH7_XML_DEF, /* Default (unused) */ - PH7_XML_UNPED, /* Unparsed entity (unused) */ - PH7_XML_ND, /* Notation declaration (unused) */ - PH7_XML_EER, /* External entity reference (unused) */ - PH7_XML_NS_START, /* Start namespace declaration */ - PH7_XML_NS_END, /* End namespace declaration */ - PH7_XML_DOCTYPE /* DOCTYPE directive */ +/* One snapshot of the QName fields of an open element. The stack of these + * lets the end handler restore the parent (enclosing) element after its own + * callback, and gives text/PI/DOCTYPE callbacks the enclosing element. */ +typedef struct ph7_xml_elem_snapshot ph7_xml_elem_snapshot; +struct ph7_xml_elem_snapshot { + ph7_value sLocalName; + ph7_value sNsUri; + ph7_value sPrefix; }; /* @@ -45,17 +40,13 @@ struct ph7_xml_engine { ph7_vm *pVm; /* VM that owns this instance */ ph7_context *pCtx; /* Current call context */ SyXMLParser sParser; /* Underlying SAX parser */ - ph7_value aCB[XML_TOTAL_HANDLER]; /* Convenience callbacks by event id */ - ph7_value sParserValue; /* Resource value holding this engine */ ph7_value sReaderValue; /* XmlReader object, owned only across Parse() */ ph7_value sHandler; /* IXmlHandler implementation, when installed */ ph7_value sAttrs; /* Snapshot of the current element attributes */ - ph7_value sLocalName; /* Current element local name */ + ph7_value sLocalName; /* Current (innermost open) element local name */ ph7_value sNsUri; /* Current element namespace URI */ ph7_value sPrefix; /* Current element prefix */ - /* Reserved: the public API forwards QName components separately and never - * concatenates URI + separator + local name, so this value is unused. */ - int ns_sep; + SySet sElemStack; /* Stack of open-element QName snapshots */ SyBlob sErr; /* Last SAX error message */ sxi32 iErrCode; /* Last SAX error code */ sxu32 nErrLine; /* Line of the last SAX error */