Add TextWriter, IOException, per-VM module data and pre-load imports; Add console module with Console class
This commit is contained in:
@@ -3786,87 +3786,6 @@ static int PH7_builtin_sprintf(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
PH7_InputFormat(sprintfConsumer, pCtx, zFormat, nLen, nArg, apArg, 0, FALSE);
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* Callback [i.e: Formatted input consumer] of the printf function.
|
||||
*/
|
||||
static int printfConsumer(ph7_context *pCtx, const char *zInput, int nLen, void *pUserData) {
|
||||
ph7_int64 *pCounter = (ph7_int64 *)pUserData;
|
||||
/* Call the VM output consumer directly */
|
||||
ph7_context_output(pCtx, zInput, nLen);
|
||||
/* Increment counter */
|
||||
*pCounter += nLen;
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* int64 printf(string $format[,mixed $args[,mixed $... ]])
|
||||
* Output a formatted string.
|
||||
* Parameters
|
||||
* $format
|
||||
* See sprintf() for a description of format.
|
||||
* Return
|
||||
* The length of the outputted string.
|
||||
*/
|
||||
static int PH7_builtin_printf(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_int64 nCounter = 0;
|
||||
const char *zFormat;
|
||||
int nLen;
|
||||
if(nArg < 1 || !ph7_value_is_string(apArg[0])) {
|
||||
/* Missing/Invalid arguments, return 0 */
|
||||
ph7_result_int(pCtx, 0);
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Extract the string format */
|
||||
zFormat = ph7_value_to_string(apArg[0], &nLen);
|
||||
if(nLen < 1) {
|
||||
/* Empty string */
|
||||
ph7_result_int(pCtx, 0);
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Format the string */
|
||||
PH7_InputFormat(printfConsumer, pCtx, zFormat, nLen, nArg, apArg, (void *)&nCounter, FALSE);
|
||||
/* Return the length of the outputted string */
|
||||
ph7_result_int64(pCtx, nCounter);
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* int vprintf(string $format,array $args)
|
||||
* Output a formatted string.
|
||||
* Parameters
|
||||
* $format
|
||||
* See sprintf() for a description of format.
|
||||
* Return
|
||||
* The length of the outputted string.
|
||||
*/
|
||||
static int PH7_builtin_vprintf(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_int64 nCounter = 0;
|
||||
const char *zFormat;
|
||||
ph7_hashmap *pMap;
|
||||
SySet sArg;
|
||||
int nLen, n;
|
||||
if(nArg < 2 || !ph7_value_is_string(apArg[0]) || !ph7_value_is_array(apArg[1])) {
|
||||
/* Missing/Invalid arguments, return 0 */
|
||||
ph7_result_int(pCtx, 0);
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Extract the string format */
|
||||
zFormat = ph7_value_to_string(apArg[0], &nLen);
|
||||
if(nLen < 1) {
|
||||
/* Empty string */
|
||||
ph7_result_int(pCtx, 0);
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Point to the hashmap */
|
||||
pMap = (ph7_hashmap *)apArg[1]->x.pOther;
|
||||
/* Extract arguments from the hashmap */
|
||||
n = PH7_HashmapValuesToSet(pMap, &sArg);
|
||||
/* Format the string */
|
||||
PH7_InputFormat(printfConsumer, pCtx, zFormat, nLen, n, (ph7_value **)SySetBasePtr(&sArg), (void *)&nCounter, TRUE);
|
||||
/* Return the length of the outputted string */
|
||||
ph7_result_int64(pCtx, nCounter);
|
||||
/* Release the container */
|
||||
SySetRelease(&sArg);
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* int vsprintf(string $format,array $args)
|
||||
* Output a formatted string.
|
||||
@@ -7457,8 +7376,6 @@ static const ph7_builtin_func aBuiltInFunc[] = {
|
||||
{ "str_repeat", PH7_builtin_str_repeat },
|
||||
{ "nl2br", PH7_builtin_nl2br },
|
||||
{ "sprintf", PH7_builtin_sprintf },
|
||||
{ "printf", PH7_builtin_printf },
|
||||
{ "vprintf", PH7_builtin_vprintf },
|
||||
{ "vsprintf", PH7_builtin_vsprintf },
|
||||
{ "size_format", PH7_builtin_size_format},
|
||||
{ "md5", PH7_builtin_md5 },
|
||||
|
||||
@@ -302,6 +302,136 @@ static sxi32 StdConvert(ph7_context *pCtx, sxi32 nArg, ph7_value **apArg) {
|
||||
return rc == PH7_OK ? ph7_result_value(pCtx, pValue) : rc;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* IOException: a core Exception subclass carrying an error code. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
static const char *IoErrorDescription(int nErr) {
|
||||
switch(nErr) {
|
||||
case 0: return "No error";
|
||||
case 1: return "Invalid argument";
|
||||
case 2: return "I/O error";
|
||||
default: return "Unknown error code";
|
||||
}
|
||||
}
|
||||
/* Stamp file/line with the first script frame of the active call stack.
|
||||
* Native frames ([NATIVE], line 0) are skipped so a catch(Exception $e)
|
||||
* observes the script location that raised the error. */
|
||||
static ph7_value *IoInstField(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);
|
||||
}
|
||||
static void IOExceptionStamp(ph7_vm *pVm, ph7_class_instance *pInst) {
|
||||
ph7_value *pField;
|
||||
SySet sTrace;
|
||||
VmDebugTrace *pTrace;
|
||||
if(pInst == 0 || 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 = IoInstField(pInst, "file");
|
||||
if(pField) {
|
||||
PH7_MemObjRelease(pField);
|
||||
PH7_MemObjInit(pVm, pField);
|
||||
(void)ph7_value_string(pField, pTrace->pFile->zString, (int)pTrace->pFile->nByte);
|
||||
}
|
||||
pField = IoInstField(pInst, "line");
|
||||
if(pField) {
|
||||
(void)ph7_value_int64(pField, (ph7_int64)pTrace->nLine);
|
||||
}
|
||||
break;
|
||||
}
|
||||
SySetRelease(&sTrace);
|
||||
}
|
||||
static sxi32 IOExceptionConstruct(ph7_context *pCtx, sxi32 nArg, ph7_value **apArg) {
|
||||
ph7_value *pResult = ph7_context_new_scalar(pCtx);
|
||||
ph7_value *pThis = ph7_context_this(pCtx);
|
||||
ph7_class_instance *pInst;
|
||||
sxi32 rc;
|
||||
if(pResult == 0) {
|
||||
return PH7_NOMEM;
|
||||
}
|
||||
/* Let the base Exception constructor own message/code/file/line/trace.
|
||||
* parent:: is required: a plain dispatch would resolve back here. */
|
||||
rc = ph7_context_parent(pCtx, "__construct", nArg > 2 ? 3 : 2, apArg, pResult);
|
||||
if(rc != PH7_OK) {
|
||||
return rc;
|
||||
}
|
||||
if(pThis && pThis->x.pOther) {
|
||||
pInst = (ph7_class_instance *)pThis->x.pOther;
|
||||
IOExceptionStamp(pCtx->pVm, pInst);
|
||||
}
|
||||
return PH7_OK;
|
||||
}
|
||||
static sxi32 IOExceptionDescription(ph7_context *pCtx, sxi32 nArg, ph7_value **apArg) {
|
||||
int nErr = nArg > 0 ? ph7_value_to_int(apArg[0]) : -1;
|
||||
return ph7_result_string(pCtx, IoErrorDescription(nErr), -1);
|
||||
}
|
||||
/* Core-owned IOException throw used by both the Console module and TextWriter
|
||||
* so the same validation produces the same exception on every call path.
|
||||
* The constructor stamps file/line; the pending transfer is left for the VM
|
||||
* unwinder. Full cleanup on every failure path. */
|
||||
PH7_PRIVATE sxi32 PH7_VmThrowIoException(ph7_context *pCtx, int nCode, const char *zMsg) {
|
||||
ph7_vm *pVm = pCtx->pVm;
|
||||
ph7_class *pClass;
|
||||
ph7_class_instance *pInst;
|
||||
ph7_class_method *pCons;
|
||||
ph7_value *pResult, *pObj, *apArg[2];
|
||||
sxi32 rc;
|
||||
if(pVm->iPendingTransfer) {
|
||||
return PH7_EXCEPTION;
|
||||
}
|
||||
pClass = PH7_VmExtractClass(pVm, "IOException", sizeof("IOException") - 1, TRUE);
|
||||
if(pClass == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pInst = PH7_NewClassInstance(pVm, pClass);
|
||||
if(pInst == 0) {
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pResult = ph7_context_new_scalar(pCtx);
|
||||
apArg[0] = ph7_context_new_scalar(pCtx);
|
||||
apArg[1] = ph7_context_new_scalar(pCtx);
|
||||
pObj = ph7_context_new_scalar(pCtx);
|
||||
if(pResult == 0 || apArg[0] == 0 || apArg[1] == 0 || pObj == 0) {
|
||||
PH7_ClassInstanceUnref(pInst);
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
ph7_value_string(apArg[0], zMsg, -1);
|
||||
ph7_value_int(apArg[1], nCode);
|
||||
pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1);
|
||||
if(pCons) {
|
||||
rc = PH7_VmCallClassMethod(pVm, pInst, pCons, pResult, 2, apArg);
|
||||
if(pInst->iRef < 1) {
|
||||
pInst->iRef = 1;
|
||||
}
|
||||
if(rc != PH7_OK) {
|
||||
PH7_ClassInstanceUnref(pInst);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
if(pInst->iRef < 1) {
|
||||
pInst->iRef = 1;
|
||||
}
|
||||
PH7_MemObjRelease(pObj);
|
||||
pObj->x.pOther = pInst;
|
||||
MemObjSetType(pObj, MEMOBJ_OBJ);
|
||||
rc = ph7_result_value(pCtx, pObj);
|
||||
return rc == PH7_OK ? PH7_EXCEPTION : rc;
|
||||
}
|
||||
|
||||
PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
ph7_value *apValue[4] = { 0, 0, 0, 0 };
|
||||
static const ph7_type_def aConversion[] = {
|
||||
@@ -376,14 +506,49 @@ PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
{ .zName = "__toString", .sResult = { PH7_TYPE_STRING, 0, 0 }, .xFunc = StdConvert, .pUserData = (void *)&aConversion[3] },
|
||||
{ .zName = "__construct", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aValueParam, .nParam = 1, .xFunc = StdConstruct, .iFlags = PH7_MEMBER_PRIVATE }
|
||||
};
|
||||
static ph7_constant_def aIoConst[] = {
|
||||
{ .zName = "ERROR_NONE", .iFlags = PH7_MEMBER_PUBLIC },
|
||||
{ .zName = "ERROR_ARGUMENT", .iFlags = PH7_MEMBER_PUBLIC },
|
||||
{ .zName = "ERROR_IO", .iFlags = PH7_MEMBER_PUBLIC }
|
||||
};
|
||||
static ph7_param_def aIoParam[] = {
|
||||
{ .zName = "message", .sType = { PH7_TYPE_STRING, 0, 0 } },
|
||||
{ .zName = "code", .sType = { PH7_TYPE_INT, 0, 0 } }
|
||||
};
|
||||
static const ph7_param_def aIoDescParam[] = {
|
||||
{ .zName = "code", .sType = { PH7_TYPE_INT, 0, 0 } }
|
||||
};
|
||||
static ph7_param_def aPrintLineParam[] = {
|
||||
{ .zName = "value", .sType = { PH7_TYPE_MIXED, 0, 0 } }
|
||||
};
|
||||
static const ph7_method_def aIoMethod[] = {
|
||||
{ .zName = "__construct", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aIoParam, .nParam = 2, .xFunc = IOExceptionConstruct },
|
||||
{ .zName = "GetDescription", .sResult = { PH7_TYPE_STRING, 0, 0 }, .aParam = aIoDescParam, .nParam = 1, .xFunc = IOExceptionDescription,
|
||||
.iFlags = PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC }
|
||||
};
|
||||
static const ph7_field_def aTextWriterField[] = {
|
||||
{ .zName = "handle", .sType = { PH7_TYPE_RESOURCE, 0, 0 }, .iFlags = PH7_MEMBER_PRIVATE }
|
||||
};
|
||||
static const ph7_method_def aTextWriterMethod[] = {
|
||||
{ .zName = "__construct", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aValueParam, .nParam = 1, .xFunc = TextWriterConstruct, .iFlags = PH7_MEMBER_PRIVATE },
|
||||
{ .zName = "__destruct", .sResult = { PH7_TYPE_VOID, 0, 0 }, .xFunc = TextWriterDestruct },
|
||||
{ .zName = "__clone", .sResult = { PH7_TYPE_VOID, 0, 0 }, .xFunc = TextWriterClone, .iFlags = PH7_MEMBER_PRIVATE },
|
||||
{ .zName = "Print", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aValueParam, .nParam = 1, .xFunc = TextWriterPrint, .iFlags = PH7_MEMBER_PUBLIC | PH7_MEMBER_VARIADIC },
|
||||
{ .zName = "PrintLine", .sResult = { PH7_TYPE_VOID, 0, 0 }, .aParam = aPrintLineParam, .nParam = 1, .xFunc = TextWriterPrintLine, .iFlags = PH7_MEMBER_PUBLIC | PH7_MEMBER_VARIADIC },
|
||||
{ .zName = "Flush", .sResult = { PH7_TYPE_VOID, 0, 0 }, .xFunc = TextWriterFlush }
|
||||
};
|
||||
static const char *const aIoBase[] = { "Exception" };
|
||||
ph7_class_def aClass[] = {
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "Exception", .aField = aExceptionField, .nField = SX_ARRAYSIZE(aExceptionField), .aMethod = aExceptionMethod, .nMethod = SX_ARRAYSIZE(aExceptionMethod) },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "IOException", .aConstant = aIoConst, .nConstant = SX_ARRAYSIZE(aIoConst), .aMethod = aIoMethod, .nMethod = SX_ARRAYSIZE(aIoMethod), .azBase = aIoBase, .nBase = 1 },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "TextWriter", .aField = aTextWriterField, .nField = SX_ARRAYSIZE(aTextWriterField), .aMethod = aTextWriterMethod, .nMethod = SX_ARRAYSIZE(aTextWriterMethod) },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "Iterator", .aMethod = aIteratorMethod, .nMethod = SX_ARRAYSIZE(aIteratorMethod), .iFlags = PH7_DECL_INTERFACE },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "IteratorAggregate", .aMethod = aAggregateMethod, .nMethod = SX_ARRAYSIZE(aAggregateMethod), .iFlags = PH7_DECL_INTERFACE },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "Serializable", .aMethod = aSerializableMethod, .nMethod = SX_ARRAYSIZE(aSerializableMethod), .iFlags = PH7_DECL_INTERFACE },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "Directory", .aField = aDirectoryField, .nField = SX_ARRAYSIZE(aDirectoryField), .aMethod = aDirectoryMethod, .nMethod = SX_ARRAYSIZE(aDirectoryMethod) },
|
||||
{ .nSize = sizeof(ph7_class_def), .nVersion = PH7_CLASS_DEF_VERSION, .zName = "stdClass", .aField = aStdField, .nField = SX_ARRAYSIZE(aStdField), .aMethod = aStdMethod, .nMethod = SX_ARRAYSIZE(aStdMethod) }
|
||||
};
|
||||
ph7_value *apIoValue[SX_ARRAYSIZE(aIoConst)] = { 0 };
|
||||
sxi32 rc = PH7_NOMEM;
|
||||
sxu32 n;
|
||||
for(n = 0; n < SX_ARRAYSIZE(apValue); n++) {
|
||||
@@ -392,6 +557,14 @@ PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
goto Cleanup;
|
||||
}
|
||||
}
|
||||
for(n = 0; n < SX_ARRAYSIZE(apIoValue); n++) {
|
||||
apIoValue[n] = ph7_new_scalar(pVm);
|
||||
if(apIoValue[n] == 0) {
|
||||
goto Cleanup;
|
||||
}
|
||||
ph7_value_int(apIoValue[n], (int)n);
|
||||
aIoConst[n].pValue = apIoValue[n];
|
||||
}
|
||||
rc = ph7_value_string(apValue[0], "Unknown exception", -1);
|
||||
if(rc == PH7_OK) {
|
||||
rc = ph7_value_string(apValue[1], "", 0);
|
||||
@@ -407,6 +580,9 @@ PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
aExceptionParam[0].pDefault = apValue[1];
|
||||
aExceptionParam[1].pDefault = apValue[2];
|
||||
aExceptionParam[2].pDefault = apValue[3];
|
||||
aIoParam[0].pDefault = apValue[1];
|
||||
aIoParam[1].pDefault = apValue[2];
|
||||
aPrintLineParam[0].pDefault = apValue[1];
|
||||
for(n = 0; n < SX_ARRAYSIZE(aClass); n++) {
|
||||
rc = ph7_create_class(pVm, &aClass[n]);
|
||||
if(rc != PH7_OK) {
|
||||
@@ -414,6 +590,12 @@ PH7_PRIVATE sxi32 PH7_VmInstallBuiltinClasses(ph7_vm *pVm) {
|
||||
}
|
||||
}
|
||||
Cleanup:
|
||||
for(n = 0; n < SX_ARRAYSIZE(apIoValue); n++) {
|
||||
if(apIoValue[n]) {
|
||||
ph7_release_value(pVm, apIoValue[n]);
|
||||
aIoConst[n].pValue = 0;
|
||||
}
|
||||
}
|
||||
for(n = 0; n < SX_ARRAYSIZE(apValue); n++) {
|
||||
if(apValue[n]) {
|
||||
ph7_release_value(pVm, apValue[n]);
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* @PROJECT PH7 Engine for the AerScript Interpreter
|
||||
* @COPYRIGHT See COPYING in the top level directory
|
||||
* @FILE engine/textwriter.c
|
||||
* @DESCRIPTION TextWriter core class support and its C API
|
||||
* @DEVELOPERS Rafal Kupiec <belliash@codingworkshop.eu.org>
|
||||
*/
|
||||
#include "ph7int.h"
|
||||
|
||||
/* A backend is stored as a resource in TextWriter->handle. The wrapper is
|
||||
* refcounted because cloning an instance copies the resource pointer: each
|
||||
* live instance owns one reference and releases it from its destructor. */
|
||||
typedef struct text_writer_backend {
|
||||
ph7_text_writer_methods sMethods;
|
||||
void *pUserData;
|
||||
int nRef;
|
||||
} text_writer_backend;
|
||||
|
||||
/* Adapter between PH7_InputFormat's consumer and a backend xWrite callback. */
|
||||
typedef struct text_writer_sink {
|
||||
int (*xWrite)(void *, const void *, unsigned int);
|
||||
void *pUserData;
|
||||
} text_writer_sink;
|
||||
|
||||
static int TextWriterSink(ph7_context *pCtx, const char *zData, int nLen, void *pUserData) {
|
||||
text_writer_sink *pSink = (text_writer_sink *)pUserData;
|
||||
SXUNUSED(pCtx);
|
||||
if(nLen > 0 && pSink->xWrite) {
|
||||
return pSink->xWrite(pSink->pUserData, zData, (unsigned int)nLen);
|
||||
}
|
||||
return SXRET_OK;
|
||||
}
|
||||
|
||||
/* Fetch the backend wrapper owned by the current TextWriter instance. */
|
||||
static text_writer_backend *TextWriterFetch(ph7_context *pCtx) {
|
||||
ph7_class_instance *pInst;
|
||||
ph7_value *pThis, *pField;
|
||||
SyString sName;
|
||||
pThis = ph7_context_this(pCtx);
|
||||
if(pThis == 0 || (pThis->nType & MEMOBJ_OBJ) == 0 || pThis->x.pOther == 0) {
|
||||
return 0;
|
||||
}
|
||||
pInst = (ph7_class_instance *)pThis->x.pOther;
|
||||
SyStringInitFromBuf(&sName, "handle", sizeof("handle") - 1);
|
||||
pField = PH7_ClassInstanceFetchAttr(pInst, &sName);
|
||||
if(pField == 0 || (pField->nType & MEMOBJ_RES) == 0 || pField->x.pOther == 0) {
|
||||
return 0;
|
||||
}
|
||||
return (text_writer_backend *)pField->x.pOther;
|
||||
}
|
||||
|
||||
/* Single shared implementation of the Console/TextWriter print rule: with one
|
||||
* argument the value is written literally (a lone '%' is ordinary text), with
|
||||
* several the first argument is the format string. bLine appends the EOL. */
|
||||
int ph7_text_writer_emit(ph7_context *pCtx,
|
||||
int (*xWrite)(void *, const void *, unsigned int),
|
||||
void *pUserData, int nArg, ph7_value **apArg, int bLine) {
|
||||
text_writer_sink sSink;
|
||||
const char *zFormat;
|
||||
int nByte, rc;
|
||||
/* Single rule for every caller (Console::Print and TextWriter::Print):
|
||||
* with several arguments the first one must be a string format. */
|
||||
if(nArg > 1 && !ph7_value_is_string(apArg[0])) {
|
||||
return PH7_VmThrowIoException(pCtx, 1, "Format must be a string");
|
||||
}
|
||||
if(nArg < 1) {
|
||||
rc = SXRET_OK;
|
||||
} else if(nArg == 1) {
|
||||
zFormat = ph7_value_to_string(apArg[0], &nByte);
|
||||
if(pCtx->pVm->iPendingTransfer) {
|
||||
return pCtx->pVm->iPendingTransfer;
|
||||
}
|
||||
rc = xWrite && nByte > 0 ? xWrite(pUserData, zFormat, (unsigned int)nByte) : SXRET_OK;
|
||||
} else {
|
||||
sSink.xWrite = xWrite;
|
||||
sSink.pUserData = pUserData;
|
||||
zFormat = ph7_value_to_string(apArg[0], &nByte);
|
||||
if(pCtx->pVm->iPendingTransfer) {
|
||||
return pCtx->pVm->iPendingTransfer;
|
||||
}
|
||||
rc = PH7_InputFormat(TextWriterSink, pCtx, zFormat, nByte, nArg, apArg, &sSink, FALSE);
|
||||
}
|
||||
if(rc == SXRET_OK && bLine) {
|
||||
#ifdef __WINNT__
|
||||
static const char zEOL[] = "\r\n";
|
||||
#else
|
||||
static const char zEOL[] = "\n";
|
||||
#endif
|
||||
if(xWrite && xWrite(pUserData, zEOL, (unsigned int)(sizeof(zEOL) - 1)) != SXRET_OK) {
|
||||
rc = PH7_ABORT;
|
||||
}
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Create a TextWriter instance around a backend and store it in pResult. */
|
||||
int ph7_text_writer_new(ph7_context *pCtx, const ph7_text_writer_methods *pMethods,
|
||||
void *pUserData, ph7_value *pResult) {
|
||||
ph7_vm *pVm = pCtx->pVm;
|
||||
text_writer_backend *pBackend;
|
||||
ph7_class *pClass;
|
||||
ph7_class_instance *pInst;
|
||||
ph7_value *pField;
|
||||
SyString sName;
|
||||
pClass = PH7_VmExtractClass(pVm, "TextWriter", sizeof("TextWriter") - 1, TRUE);
|
||||
if(pClass == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pBackend = (text_writer_backend *)SyMemBackendAlloc(&pVm->sAllocator, sizeof(text_writer_backend));
|
||||
if(pBackend == 0) {
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pBackend->sMethods = *pMethods;
|
||||
pBackend->pUserData = pUserData;
|
||||
pBackend->nRef = 1;
|
||||
pInst = PH7_NewClassInstance(pVm, pClass);
|
||||
if(pInst == 0) {
|
||||
SyMemBackendFree(&pVm->sAllocator, pBackend);
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
SyStringInitFromBuf(&sName, "handle", sizeof("handle") - 1);
|
||||
pField = PH7_ClassInstanceFetchAttr(pInst, &sName);
|
||||
if(pField == 0) {
|
||||
PH7_ClassInstanceUnref(pInst);
|
||||
SyMemBackendFree(&pVm->sAllocator, pBackend);
|
||||
PH7_VmMemoryError(pVm);
|
||||
return PH7_ABORT;
|
||||
}
|
||||
ph7_value_resource(pField, pBackend);
|
||||
PH7_MemObjRelease(pResult);
|
||||
pResult->x.pOther = pInst;
|
||||
MemObjSetType(pResult, MEMOBJ_OBJ);
|
||||
return PH7_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Native callbacks for the core TextWriter class */
|
||||
/* ------------------------------------------------------------------ */
|
||||
int TextWriterConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
ph7_class_instance *pInst;
|
||||
ph7_value *pField;
|
||||
SyString sName;
|
||||
ph7_value *pThis = ph7_context_this(pCtx);
|
||||
if(pThis == 0 || (pThis->nType & MEMOBJ_OBJ) == 0 || pThis->x.pOther == 0 || nArg < 1) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
pInst = (ph7_class_instance *)pThis->x.pOther;
|
||||
SyStringInitFromBuf(&sName, "handle", sizeof("handle") - 1);
|
||||
pField = PH7_ClassInstanceFetchAttr(pInst, &sName);
|
||||
if(pField == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
return ph7_value_resource(pField, ph7_value_to_resource(apArg[0])) == PH7_OK ? PH7_OK : PH7_ABORT;
|
||||
}
|
||||
|
||||
int TextWriterDestruct(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
text_writer_backend *pBackend = TextWriterFetch(pCtx);
|
||||
ph7_vm *pVm = pCtx->pVm;
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
if(pBackend == 0) {
|
||||
return PH7_OK;
|
||||
}
|
||||
ph7_class_instance *pInst;
|
||||
ph7_value *pField;
|
||||
SyString sName;
|
||||
/* Drop this instance's reference unconditionally: an explicit second
|
||||
* __destruct() must be a no-op instead of a use-after-free, and a clone
|
||||
* that outlives this instance must not keep a dangling handle. Each
|
||||
* instance owns its own field, so a co-owner's pointer is untouched. */
|
||||
pInst = (ph7_class_instance *)ph7_context_this(pCtx)->x.pOther;
|
||||
SyStringInitFromBuf(&sName, "handle", sizeof("handle") - 1);
|
||||
pField = PH7_ClassInstanceFetchAttr(pInst, &sName);
|
||||
if(pField) {
|
||||
ph7_value_resource(pField, 0);
|
||||
}
|
||||
if(--pBackend->nRef <= 0) {
|
||||
if(pBackend->sMethods.xRelease) {
|
||||
pBackend->sMethods.xRelease(pBackend->pUserData);
|
||||
}
|
||||
SyMemBackendFree(&pVm->sAllocator, pBackend);
|
||||
}
|
||||
return PH7_OK;
|
||||
}
|
||||
|
||||
int TextWriterClone(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
text_writer_backend *pBackend = TextWriterFetch(pCtx);
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
/* Clone copies the resource pointer; own a reference for the new instance. */
|
||||
if(pBackend) {
|
||||
pBackend->nRef++;
|
||||
}
|
||||
return PH7_OK;
|
||||
}
|
||||
|
||||
static int TextWriterEmitThis(ph7_context *pCtx, int nArg, ph7_value **apArg, int bLine) {
|
||||
text_writer_backend *pBackend = TextWriterFetch(pCtx);
|
||||
if(pBackend == 0 || pBackend->sMethods.xWrite == 0) {
|
||||
return PH7_ABORT;
|
||||
}
|
||||
return ph7_text_writer_emit(pCtx, pBackend->sMethods.xWrite, pBackend->pUserData,
|
||||
nArg, apArg, bLine);
|
||||
}
|
||||
|
||||
int TextWriterPrint(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
return TextWriterEmitThis(pCtx, nArg, apArg, 0);
|
||||
}
|
||||
|
||||
int TextWriterPrintLine(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
return TextWriterEmitThis(pCtx, nArg, apArg, 1);
|
||||
}
|
||||
|
||||
int TextWriterFlush(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
text_writer_backend *pBackend = TextWriterFetch(pCtx);
|
||||
SXUNUSED(nArg);
|
||||
SXUNUSED(apArg);
|
||||
if(pBackend == 0) {
|
||||
return PH7_OK;
|
||||
}
|
||||
if(pBackend->sMethods.xFlush) {
|
||||
return pBackend->sMethods.xFlush(pBackend->pUserData);
|
||||
}
|
||||
return SXRET_OK;
|
||||
}
|
||||
+125
-5
@@ -7799,6 +7799,12 @@ struct ph7_stream_data {
|
||||
void *pHandle; /* Stream handle */
|
||||
ph7_output_consumer sConsumer; /* VM output consumer */
|
||||
} x;
|
||||
/* One-byte-at-a-time look-ahead from Console::Read() must be able to give
|
||||
* an unused byte back to the shared stdin stream, otherwise fgets()/fread()
|
||||
* would silently lose data. Served before any real read. */
|
||||
int nUnread; /* Number of pending bytes */
|
||||
int iUnread; /* Index of the next pending byte */
|
||||
unsigned char aUnread[4]; /* Pending bytes, in stream order */
|
||||
};
|
||||
/*
|
||||
* Allocate a new instance of the ph7_stream_data structure.
|
||||
@@ -7894,6 +7900,7 @@ static int PHPStreamData_Open(const char *zName, int iMode, ph7_value *pResource
|
||||
/* ph7_int64 (*xRead)(void *,void *,ph7_int64) */
|
||||
static ph7_int64 PHPStreamData_Read(void *pHandle, void *pBuffer, ph7_int64 nDatatoRead) {
|
||||
ph7_stream_data *pData = (ph7_stream_data *)pHandle;
|
||||
ph7_int64 nServed = 0;
|
||||
if(pData == 0) {
|
||||
return -1;
|
||||
}
|
||||
@@ -7901,6 +7908,22 @@ static ph7_int64 PHPStreamData_Read(void *pHandle, void *pBuffer, ph7_int64 nDat
|
||||
/* Forbidden */
|
||||
return -1;
|
||||
}
|
||||
/* Give back bytes that Console::Read() looked ahead but did not consume. */
|
||||
while(pData->nUnread > 0 && nServed < nDatatoRead) {
|
||||
/* Both sides must use the same ring arithmetic (C2): the writer uses
|
||||
* (iUnread + nUnread) % 4, so a bare iUnread++ would read past the
|
||||
* array after four wrap-around cycles. */
|
||||
((unsigned char *)pBuffer)[nServed++] = pData->aUnread[pData->iUnread];
|
||||
pData->iUnread = (pData->iUnread + 1) % SX_ARRAYSIZE(pData->aUnread);
|
||||
if(--pData->nUnread == 0) {
|
||||
pData->iUnread = 0;
|
||||
}
|
||||
}
|
||||
if(nServed >= nDatatoRead) {
|
||||
return nServed;
|
||||
}
|
||||
nDatatoRead -= nServed;
|
||||
pBuffer = (void *)(((unsigned char *)pBuffer) + nServed);
|
||||
#ifdef __WINNT__
|
||||
{
|
||||
DWORD nRd;
|
||||
@@ -7908,9 +7931,9 @@ static ph7_int64 PHPStreamData_Read(void *pHandle, void *pBuffer, ph7_int64 nDat
|
||||
rc = ReadFile(pData->x.pHandle, pBuffer, (DWORD)nDatatoRead, &nRd, 0);
|
||||
if(!rc) {
|
||||
/* IO error */
|
||||
return -1;
|
||||
return nServed > 0 ? nServed : -1;
|
||||
}
|
||||
return (ph7_int64)nRd;
|
||||
return nServed + (ph7_int64)nRd;
|
||||
}
|
||||
#elif defined(__UNIXES__)
|
||||
{
|
||||
@@ -7919,12 +7942,12 @@ static ph7_int64 PHPStreamData_Read(void *pHandle, void *pBuffer, ph7_int64 nDat
|
||||
fd = SX_PTR_TO_INT(pData->x.pHandle);
|
||||
nRd = read(fd, pBuffer, (size_t)nDatatoRead);
|
||||
if(nRd < 1) {
|
||||
return -1;
|
||||
return nServed > 0 ? nServed : -1;
|
||||
}
|
||||
return (ph7_int64)nRd;
|
||||
return nServed + (ph7_int64)nRd;
|
||||
}
|
||||
#else
|
||||
return -1;
|
||||
return nServed > 0 ? nServed : -1;
|
||||
#endif
|
||||
}
|
||||
/* ph7_int64 (*xWrite)(void *,const void *,ph7_int64) */
|
||||
@@ -8160,6 +8183,103 @@ PH7_PRIVATE void *PH7_ExportStdin(ph7_vm *pVm) {
|
||||
return pVm->pStdin;
|
||||
}
|
||||
}
|
||||
/* Give one byte back to the shared stdin stream. When the byte still lives in
|
||||
* io_private's working buffer we simply rewind the offset; otherwise it goes
|
||||
* into php://stdin's low-level pending queue so fgets()/fread() see it next. */
|
||||
PH7_PRIVATE void PH7_StdinUnread(ph7_vm *pVm, unsigned char c) {
|
||||
io_private *pIn = (io_private *)pVm->pStdin;
|
||||
ph7_stream_data *pData;
|
||||
if(pIn == 0 || IO_PRIVATE_INVALID(pIn)) {
|
||||
return;
|
||||
}
|
||||
if(pIn->nOfft > 0 && pIn->nOfft <= SyBlobLength(&pIn->sBuffer)) {
|
||||
pIn->nOfft--;
|
||||
return;
|
||||
}
|
||||
pData = (ph7_stream_data *)pIn->pHandle;
|
||||
if(pData != 0 && pData->iType == PH7_IO_STREAM_STDIN && pData->nUnread < (int)SX_ARRAYSIZE(pData->aUnread)) {
|
||||
pData->aUnread[(pData->iUnread + pData->nUnread) % SX_ARRAYSIZE(pData->aUnread)] = c;
|
||||
pData->nUnread++;
|
||||
}
|
||||
}
|
||||
/* Read one line from the shared stdin handle. StreamReadLine() consults the
|
||||
* same xRead (and therefore the same pending-unread queue) as Console::Read,
|
||||
* fgets() and fread(), so mixing the readers never loses a byte. The returned
|
||||
* buffer is a VM-owned copy: StreamReadLine() may reset its working buffer as
|
||||
* soon as it returns. NULL means EOF without data. */
|
||||
PH7_PRIVATE char *PH7_StdinReadLine(ph7_vm *pVm, int *pLen) {
|
||||
io_private *pIn = (io_private *)PH7_ExportStdin(pVm);
|
||||
const char *zLine;
|
||||
ph7_int64 n;
|
||||
char *pOut;
|
||||
if(pLen == 0) {
|
||||
return 0;
|
||||
}
|
||||
*pLen = 0;
|
||||
if(pIn == 0) {
|
||||
return 0;
|
||||
}
|
||||
n = StreamReadLine(pIn, &zLine, -1);
|
||||
if(n < 1 || n > 0x7FFFFFFF) {
|
||||
return 0;
|
||||
}
|
||||
pOut = (char *)SyMemBackendAlloc(&pVm->sAllocator, (sxu32)(n + 1));
|
||||
if(pOut == 0) {
|
||||
return 0;
|
||||
}
|
||||
SyMemcpy(zLine, pOut, (sxu32)n);
|
||||
pOut[n] = 0;
|
||||
*pLen = (int)n;
|
||||
return pOut;
|
||||
}
|
||||
/* Decode one Unicode code point from the shared stdin stream. Invalid UTF-8
|
||||
* yields 0xFFFD, end of input -1. Bytes inspected but not consumed are
|
||||
* returned with PH7_StdinUnread() so no other reader loses data. Unlike
|
||||
* PH7_Utf8Read(), overlong forms, surrogates and values above U+10FFFF are
|
||||
* rejected here. */
|
||||
PH7_PRIVATE int PH7_StdinReadCodepoint(ph7_vm *pVm) {
|
||||
io_private *pIn = (io_private *)PH7_ExportStdin(pVm);
|
||||
unsigned char c;
|
||||
ph7_int64 n;
|
||||
int i, nWant, nGot = 0, cp, nMin;
|
||||
if(pIn == 0) {
|
||||
return -1;
|
||||
}
|
||||
n = StreamRead(pIn, &c, 1);
|
||||
if(n < 1) {
|
||||
return -1;
|
||||
}
|
||||
if(c < 0x80) {
|
||||
return (int)c;
|
||||
}
|
||||
if(c >= 0xC2 && c <= 0xDF) {
|
||||
nWant = 2; cp = c & 0x1F; nMin = 0x80;
|
||||
} else if(c >= 0xE0 && c <= 0xEF) {
|
||||
nWant = 3; cp = c & 0x0F; nMin = 0x800;
|
||||
} else if(c >= 0xF0 && c <= 0xF4) {
|
||||
nWant = 4; cp = c & 0x07; nMin = 0x10000;
|
||||
} else {
|
||||
return 0xFFFD; /* Continuation byte or invalid lead. */
|
||||
}
|
||||
nGot = 1;
|
||||
for(i = 1 ; i < nWant ; ++i) {
|
||||
n = StreamRead(pIn, &c, 1);
|
||||
if(n < 1) {
|
||||
break; /* Truncated sequence: return replacement for what we got. */
|
||||
}
|
||||
if((c & 0xC0) != 0x80) {
|
||||
PH7_StdinUnread(pVm, c);
|
||||
return 0xFFFD;
|
||||
}
|
||||
cp = (cp << 6) | (c & 0x3F);
|
||||
++nGot;
|
||||
}
|
||||
if(nGot < nWant || cp < nMin || cp > 0x10FFFF ||
|
||||
(cp & 0xFFFFF800) == 0xD800 || (cp & 0xFFFFFFFE) == 0xFFFE) {
|
||||
return 0xFFFD;
|
||||
}
|
||||
return cp;
|
||||
}
|
||||
/*
|
||||
* Export the STDOUT handle.
|
||||
*/
|
||||
|
||||
+218
-421
@@ -2650,6 +2650,7 @@ static ph7_class *VmMethodClass(ph7_vm *pVm) {
|
||||
}
|
||||
return (ph7_class *)pVmFunc->pUserData;
|
||||
}
|
||||
static sxi32 VmImportModule(ph7_vm *, const char *, VmInstr *, int, sxu32);
|
||||
/*
|
||||
* Prepare the Virtual Machine for byte-code execution.
|
||||
* This routine gets called by the PH7 engine after
|
||||
@@ -2705,6 +2706,22 @@ PH7_PRIVATE sxi32 PH7_VmMakeReady(
|
||||
PH7_RegisterBuiltInConstant(&(*pVm));
|
||||
/* Register built-in functions [i.e: array_diff(), strlen(), etc.] */
|
||||
PH7_RegisterBuiltInFunction(&(*pVm));
|
||||
/* Load imported modules BEFORE evaluating class initializers: a static or
|
||||
* constant field may reference a class published by initializeModule().
|
||||
* Native classes are mounted once after every init() has run (two-phase). */
|
||||
{
|
||||
VmInstr *aInstr = (VmInstr *)SySetBasePtr(pVm->pByteContainer);
|
||||
sxu32 nInstr = SySetUsed(pVm->pByteContainer), i;
|
||||
sxu32 nPreexisting = SySetUsed(&pVm->aModules);
|
||||
for(i = 0 ; i < nInstr ; ++i) {
|
||||
if(aInstr[i].iOp == PH7_OP_IMPORT) {
|
||||
rc = VmImportModule(pVm, (const char *)aInstr[i].p3, &aInstr[i], TRUE, nPreexisting);
|
||||
if(rc != SXRET_OK) {
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Initialize and install static and constants class attributes */
|
||||
SyHashResetLoopCursor(&pVm->hClass);
|
||||
while((pEntry = SyHashGetNextEntry(&pVm->hClass)) != 0) {
|
||||
@@ -2873,6 +2890,19 @@ PH7_PRIVATE sxi32 PH7_VmRelease(ph7_vm *pVm) {
|
||||
while(SySetGetNextEntry(&pVm->aMemObj, (void **)&pObj) == SXRET_OK) {
|
||||
PH7_MemObjRelease(pObj);
|
||||
}
|
||||
/* Release per-module state exactly once (C13), BEFORE dlclose() makes the
|
||||
* module's release callback unreachable. aModuleHandles holds snapshots
|
||||
* taken at load time, before any state was published, so only the live
|
||||
* aModules entries carry a release callback. */
|
||||
SySetResetCursor(&pVm->aModules);
|
||||
while(SySetGetNextEntry(&pVm->aModules, (void **)&pEntry) == SXRET_OK) {
|
||||
VmModule *pModule = (VmModule *)pEntry;
|
||||
if(pModule->pUserData && pModule->xRelease) {
|
||||
pModule->xRelease(pModule->pUserData);
|
||||
}
|
||||
pModule->pUserData = 0;
|
||||
pModule->xRelease = 0;
|
||||
}
|
||||
/* Iterate through modules list */
|
||||
while(SySetGetNextEntry(&pVm->aModuleHandles, (void **)&pEntry) == SXRET_OK) {
|
||||
/* Unload the module */
|
||||
@@ -3780,17 +3810,175 @@ PH7_PRIVATE sxi32 PH7_VmThrowError(
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
/* Exact module-name lookup; do not disturb the set's iteration cursor. */
|
||||
static sxi32 VmModuleLoaded(ph7_vm *pVm, const char *zName, sxu32 nLen) {
|
||||
/* Exact module-name lookup; do not disturb the set's iteration cursor.
|
||||
* Returns the 1-based slot so callers can tell modules loaded by an earlier
|
||||
* compilation (ph7_vm_reset keeps aModules) from duplicates in this one. */
|
||||
static sxu32 VmModuleSlot(ph7_vm *pVm, const char *zName, sxu32 nLen) {
|
||||
sxu32 i;
|
||||
VmModule *pModule;
|
||||
for(i = 0; i < SySetUsed(&pVm->aModules); ++i) {
|
||||
pModule = (VmModule *)SySetAt(&pVm->aModules, i);
|
||||
if(pModule->sName.nByte == nLen && SyStrncmp(pModule->sName.zString, zName, nLen) == 0) {
|
||||
return TRUE;
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
return 0;
|
||||
}
|
||||
static sxi32 VmModuleLoaded(ph7_vm *pVm, const char *zName, sxu32 nLen) {
|
||||
return VmModuleSlot(pVm, zName, nLen) ? TRUE : FALSE;
|
||||
}
|
||||
/* Per-VM, per-module opaque state published by the module itself (C13).
|
||||
* aModules is kept across ph7_vm_reset(), so the data survives a reset too;
|
||||
* the module re-initializes from PH7_VM_CONFIG on the next import attempt
|
||||
* only when it chooses to. PH7_VmModuleData() returns NULL for an unknown
|
||||
* module; PH7_VmSetModuleData() returns SXERR_NOTFOUND (never PH7_NOMEM,
|
||||
* which is reserved for allocation failures). */
|
||||
PH7_PRIVATE void *PH7_VmModuleData(ph7_vm *pVm, const char *zModule) {
|
||||
sxu32 nSlot;
|
||||
if(pVm == 0 || zModule == 0) {
|
||||
return 0;
|
||||
}
|
||||
nSlot = VmModuleSlot(pVm, zModule, (sxu32)SyStrlen(zModule));
|
||||
return nSlot ? ((VmModule *)SySetAt(&pVm->aModules, nSlot - 1))->pUserData : 0;
|
||||
}
|
||||
PH7_PRIVATE sxi32 PH7_VmSetModuleData(ph7_vm *pVm, const char *zModule,
|
||||
void *pData, void (*xRelease)(void *)) {
|
||||
VmModule *pModule;
|
||||
sxu32 nSlot;
|
||||
if(pVm == 0 || zModule == 0 || (nSlot = VmModuleSlot(pVm, zModule, (sxu32)SyStrlen(zModule))) == 0) {
|
||||
return SXERR_NOTFOUND;
|
||||
}
|
||||
pModule = (VmModule *)SySetAt(&pVm->aModules, nSlot - 1);
|
||||
/* Replacing existing state releases the old value exactly once. */
|
||||
if(pModule->pUserData && pModule->pUserData != pData && pModule->xRelease) {
|
||||
pModule->xRelease(pModule->pUserData);
|
||||
}
|
||||
pModule->pUserData = pData;
|
||||
pModule->xRelease = xRelease;
|
||||
return SXRET_OK;
|
||||
}
|
||||
/* Import instruction status (VmInstr.iP1): pre-scan marks every import so the
|
||||
* runtime handler only has to replay diagnostics, never load code twice. */
|
||||
#define VM_IMPORT_PENDING 0
|
||||
#define VM_IMPORT_PRELOADED 1
|
||||
#define VM_IMPORT_FAILED 2
|
||||
#define VM_IMPORT_DUPLICATE 3
|
||||
/* Failure reasons (VmInstr.iP2) replayed by the runtime handler. */
|
||||
#define VM_IMPORT_FAIL_PATH 1
|
||||
#define VM_IMPORT_FAIL_MEMORY 2
|
||||
#define VM_IMPORT_FAIL_MISSING 3
|
||||
#define VM_IMPORT_FAIL_NOINIT 4
|
||||
#define VM_IMPORT_FAIL_INIT 5
|
||||
#define VM_IMPORT_FAIL_REGISTER 6
|
||||
/* Set at the first runtime execution of a pre-loaded import. A second
|
||||
* execution of the same bytecode after ph7_vm_reset() sees the module still
|
||||
* registered in aModules and reports "already loaded". */
|
||||
#define VM_IMPORT_REPLAYED 7
|
||||
/* Do the actual dlopen()/initializeModule() work. Warnings are suppressed in
|
||||
* the pre-scan (there is no script frame yet, so they would point at
|
||||
* [MEMORY]:1); the instruction instead records what the runtime must report. */
|
||||
static sxi32 VmImportModule(ph7_vm *pVm, const char *zModule, VmInstr *pInstr,
|
||||
int bPreScan, sxu32 nPreexisting) {
|
||||
VmModule pModule;
|
||||
char bfile[255];
|
||||
char *zFile;
|
||||
int nFile;
|
||||
sxu32 nSize, nSlot;
|
||||
sxi32 (*init)(ph7_vm *, ph7_real *, SyString *);
|
||||
int nLen = SyStrlen(zModule);
|
||||
if(nLen < 1) {
|
||||
return SXRET_OK;
|
||||
}
|
||||
nSlot = VmModuleSlot(pVm, zModule, (sxu32)nLen);
|
||||
if(nSlot > 0) {
|
||||
/* A module left in aModules by an earlier compilation (ph7_vm_reset
|
||||
* keeps it: dropping it would orphan published functions/classes)
|
||||
* must still replay the "already loaded" warning at run time, so
|
||||
* leave the instruction pending. A duplicate within this bytecode
|
||||
* is reported immediately. */
|
||||
pInstr->iP1 = (bPreScan && nSlot <= nPreexisting) ? VM_IMPORT_PENDING : VM_IMPORT_DUPLICATE;
|
||||
return SXRET_OK;
|
||||
}
|
||||
SyZero(&pModule, sizeof(VmModule));
|
||||
SyStringInitFromBuf(&pModule.sName, zModule, nLen);
|
||||
nFile = snprintf(bfile, sizeof(bfile), "./binary/%s%s", zModule, PH7_LIBRARY_SUFFIX);
|
||||
if(nFile < 0 || nFile >= (int)sizeof(bfile)) {
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_PATH;
|
||||
return SXRET_OK;
|
||||
}
|
||||
zFile = SyMemBackendStrDup(&pVm->sAllocator, bfile, (sxu32)nFile);
|
||||
if(zFile == 0) {
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_MEMORY;
|
||||
return SXRET_OK;
|
||||
}
|
||||
SyStringInitFromBuf(&pModule.sFile, zFile, nFile);
|
||||
#ifdef __WINNT__
|
||||
pModule.pHandle = LoadLibrary(zFile);
|
||||
#else
|
||||
pModule.pHandle = dlopen(pModule.sFile.zString, RTLD_LAZY);
|
||||
#endif
|
||||
if(!pModule.pHandle) {
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_MISSING;
|
||||
SyMemBackendFree(&pVm->sAllocator, zFile);
|
||||
return SXRET_OK;
|
||||
}
|
||||
#ifdef __WINNT__
|
||||
*(void**)(&init) = GetProcAddress(pModule.pHandle, "initializeModule");
|
||||
#else
|
||||
*(void**)(&init) = dlsym(pModule.pHandle, "initializeModule");
|
||||
#endif
|
||||
nSize = pVm->aModuleHandles.nSize;
|
||||
if(!init || SySetPut(&pVm->aModuleHandles, &pModule) != SXRET_OK) {
|
||||
pVm->aModuleHandles.nSize = nSize;
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_NOINIT;
|
||||
#ifdef __WINNT__
|
||||
FreeLibrary(pModule.pHandle);
|
||||
#else
|
||||
dlclose(pModule.pHandle);
|
||||
#endif
|
||||
SyMemBackendFree(&pVm->sAllocator, zFile);
|
||||
return SXRET_OK;
|
||||
}
|
||||
/* Init may publish callbacks even on failure. Retain its handle until VM
|
||||
* release, but only successful imports enter the lookup registry. */
|
||||
if(init(pVm, &pModule.fVer, &pModule.sDesc) != SXRET_OK) {
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_INIT;
|
||||
} else {
|
||||
nSize = pVm->aModules.nSize;
|
||||
if(SySetPut(&pVm->aModules, &pModule) != SXRET_OK) {
|
||||
pVm->aModules.nSize = nSize;
|
||||
pInstr->iP1 = VM_IMPORT_FAILED; pInstr->iP2 = VM_IMPORT_FAIL_REGISTER;
|
||||
} else {
|
||||
pInstr->iP1 = VM_IMPORT_PRELOADED;
|
||||
}
|
||||
}
|
||||
/* Native classes introduced by init() are mounted once, after every
|
||||
* module has been initialized (see PH7_VmMakeReady). */
|
||||
SXUNUSED(bPreScan);
|
||||
return SXRET_OK;
|
||||
}
|
||||
/* Replay an import diagnostic now that a script frame is active. */
|
||||
static void VmImportReport(ph7_vm *pVm, const char *zModule, VmInstr *pInstr) {
|
||||
switch(pInstr->iP2) {
|
||||
case VM_IMPORT_FAIL_PATH:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Module path too long for '%s'", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_MEMORY:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Out of memory loading '%s'", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_MISSING:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: No module named '%s' found", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_NOINIT:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot initialize module '%s'", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_INIT:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Initialization of module '%s' failed", zModule);
|
||||
break;
|
||||
case VM_IMPORT_FAIL_REGISTER:
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot register module '%s'", zModule);
|
||||
break;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Execute as much of a PH7 bytecode program as we can then return.
|
||||
@@ -6034,77 +6222,39 @@ Resume:
|
||||
*/
|
||||
case PH7_OP_IMPORT:
|
||||
{
|
||||
VmModule pModule;
|
||||
char bfile[255];
|
||||
char *zFile;
|
||||
int nFile;
|
||||
sxu32 nSize;
|
||||
sxi32 (*init)(ph7_vm *, ph7_real *, SyString *);
|
||||
char *zModule = (char *) pInstr->p3;
|
||||
int nLen = SyStrlen(zModule);
|
||||
if(nLen < 1) {
|
||||
if(pInstr->iP1 == VM_IMPORT_PRELOADED) {
|
||||
/* Loaded before user-class initializers ran: no work
|
||||
* and no warning on the first execution. A second
|
||||
* execution of the same bytecode after ph7_vm_reset
|
||||
* observes the still-registered module as a duplicate. */
|
||||
if(pInstr->iP2 == VM_IMPORT_REPLAYED) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING,
|
||||
"ImportError: Module '%s' already loaded", zModule);
|
||||
} else {
|
||||
pInstr->iP2 = VM_IMPORT_REPLAYED;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if(VmModuleLoaded(pVm, zModule, (sxu32)nLen)) {
|
||||
if(pInstr->iP1 == VM_IMPORT_FAILED) {
|
||||
VmImportReport(pVm, zModule, pInstr);
|
||||
break;
|
||||
}
|
||||
if(pInstr->iP1 == VM_IMPORT_DUPLICATE) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Module '%s' already loaded", zModule);
|
||||
break;
|
||||
}
|
||||
|
||||
/* Zero the module entry */
|
||||
SyZero(&pModule, sizeof(VmModule));
|
||||
SyStringInitFromBuf(&pModule.sName, zModule, nLen);
|
||||
nFile = snprintf(bfile, sizeof(bfile), "./binary/%s%s", zModule, PH7_LIBRARY_SUFFIX);
|
||||
if(nFile < 0 || nFile >= (int)sizeof(bfile)) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Module path too long for '%s'", zModule);
|
||||
break;
|
||||
}
|
||||
zFile = SyMemBackendStrDup(&pVm->sAllocator, bfile, (sxu32)nFile);
|
||||
if(zFile == 0) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Out of memory loading '%s'", zModule);
|
||||
break;
|
||||
}
|
||||
SyStringInitFromBuf(&pModule.sFile, zFile, nFile);
|
||||
#ifdef __WINNT__
|
||||
pModule.pHandle = LoadLibrary(zFile);
|
||||
#else
|
||||
pModule.pHandle = dlopen(pModule.sFile.zString, RTLD_LAZY);
|
||||
#endif
|
||||
if(!pModule.pHandle) {
|
||||
/* Could not load the module library file */
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: No module named '%z' found", &pModule.sName);
|
||||
SyMemBackendFree(&pVm->sAllocator, zFile);
|
||||
break;
|
||||
}
|
||||
#ifdef __WINNT__
|
||||
*(void**)(&init) = GetProcAddress(pModule.pHandle, "initializeModule");
|
||||
#else
|
||||
*(void**)(&init) = dlsym(pModule.pHandle, "initializeModule");
|
||||
#endif
|
||||
nSize = pVm->aModuleHandles.nSize;
|
||||
if(!init || SySetPut(&pVm->aModuleHandles, &pModule) != SXRET_OK) {
|
||||
/* SySetPut may change capacity before allocation fails. */
|
||||
pVm->aModuleHandles.nSize = nSize;
|
||||
/* No callbacks have been published yet; unloading is safe. */
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot initialize module '%z'", &pModule.sName);
|
||||
#ifdef __WINNT__
|
||||
FreeLibrary(pModule.pHandle);
|
||||
#else
|
||||
dlclose(pModule.pHandle);
|
||||
#endif
|
||||
SyMemBackendFree(&pVm->sAllocator, zFile);
|
||||
break;
|
||||
}
|
||||
/* Init may publish callbacks even on failure. Retain its handle until
|
||||
* VM release, but only successful imports enter the lookup registry. */
|
||||
if(init(pVm, &pModule.fVer, &pModule.sDesc) != SXRET_OK) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Initialization of module '%z' failed", &pModule.sName);
|
||||
} else {
|
||||
nSize = pVm->aModules.nSize;
|
||||
if(SySetPut(&pVm->aModules, &pModule) != SXRET_OK) {
|
||||
/* Keep the lookup registry retryable after allocation failure. */
|
||||
pVm->aModules.nSize = nSize;
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Cannot register module '%z'", &pModule.sName);
|
||||
rc = VmImportModule(pVm, zModule, pInstr, FALSE, 0);
|
||||
if(rc != SXRET_OK) {
|
||||
if(rc == SXERR_MEM) {
|
||||
PH7_VmMemoryError(pVm);
|
||||
}
|
||||
goto Abort;
|
||||
}
|
||||
if(pInstr->iP1 == VM_IMPORT_FAILED) {
|
||||
VmImportReport(pVm, zModule, pInstr);
|
||||
} else if(pInstr->iP1 == VM_IMPORT_DUPLICATE) {
|
||||
PH7_VmThrowError(pVm, PH7_CTX_WARNING, "ImportError: Module '%s' already loaded", zModule);
|
||||
}
|
||||
rc = VmMountNativeClasses(pVm);
|
||||
if(rc == SXERR_MEM) {
|
||||
@@ -9814,38 +9964,6 @@ static int vm_builtin_uniqid(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
* Status:
|
||||
* Stable.
|
||||
*/
|
||||
/*
|
||||
* int print($string...)
|
||||
* Output one or more messages.
|
||||
* Parameters
|
||||
* $string
|
||||
* Message to output.
|
||||
* Return
|
||||
* NULL.
|
||||
*/
|
||||
static int vm_builtin_print(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
const char *zData;
|
||||
int nDataLen = 0;
|
||||
ph7_vm *pVm;
|
||||
int i, rc;
|
||||
/* Point to the target VM */
|
||||
pVm = pCtx->pVm;
|
||||
/* 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) {
|
||||
/* Output consumer callback request an operation abort */
|
||||
return PH7_ABORT;
|
||||
}
|
||||
}
|
||||
}
|
||||
return SXRET_OK;
|
||||
}
|
||||
/*
|
||||
* void exit(string $msg)
|
||||
* void exit(int $status)
|
||||
@@ -11761,325 +11879,6 @@ static int vm_builtin_get_included_files(ph7_context *pCtx, int nArg, ph7_value
|
||||
*/
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* Section:
|
||||
* Command line arguments processing.
|
||||
* Authors:
|
||||
* Symisc Systems,devel@symisc.net.
|
||||
* Copyright (C) Symisc Systems,https://ph7.symisc.net
|
||||
* Status:
|
||||
* Stable.
|
||||
*/
|
||||
/*
|
||||
* Check if a short option argument [i.e: -c] is available in the command
|
||||
* line string. Return a pointer to the start of the stream on success.
|
||||
* NULL otherwise.
|
||||
*/
|
||||
static const char *VmFindShortOpt(int c, const char *zIn, const char *zEnd) {
|
||||
while(zIn < zEnd) {
|
||||
if(zIn[0] == '-' && &zIn[1] < zEnd && (int)zIn[1] == c) {
|
||||
/* Got one */
|
||||
return &zIn[1];
|
||||
}
|
||||
/* Advance the cursor */
|
||||
zIn++;
|
||||
}
|
||||
/* No such option */
|
||||
return 0;
|
||||
}
|
||||
/*
|
||||
* Check if a long option argument [i.e: --opt] is available in the command
|
||||
* line string. Return a pointer to the start of the stream on success.
|
||||
* NULL otherwise.
|
||||
*/
|
||||
static const char *VmFindLongOpt(const char *zLong, int nByte, const char *zIn, const char *zEnd) {
|
||||
const char *zOpt;
|
||||
while(zIn < zEnd) {
|
||||
if(zIn[0] == '-' && &zIn[1] < zEnd && (int)zIn[1] == '-') {
|
||||
zIn += 2;
|
||||
zOpt = zIn;
|
||||
while(zIn < zEnd && !SyisSpace(zIn[0])) {
|
||||
if(zIn[0] == '=' /* --opt=val */) {
|
||||
break;
|
||||
}
|
||||
zIn++;
|
||||
}
|
||||
/* Test */
|
||||
if((int)(zIn - zOpt) == nByte && SyMemcmp(zOpt, zLong, nByte) == 0) {
|
||||
/* Got one, return it's value */
|
||||
return zIn;
|
||||
}
|
||||
} else {
|
||||
zIn++;
|
||||
}
|
||||
}
|
||||
/* No such option */
|
||||
return 0;
|
||||
}
|
||||
/*
|
||||
* Long option [i.e: --opt] arguments private data structure.
|
||||
*/
|
||||
struct getopt_long_opt {
|
||||
const char *zArgIn, *zArgEnd; /* Command line arguments */
|
||||
ph7_value *pWorker; /* Worker variable*/
|
||||
ph7_value *pArray; /* getopt() return value */
|
||||
ph7_context *pCtx; /* Call Context */
|
||||
};
|
||||
/* Forward declaration */
|
||||
static int VmProcessLongOpt(ph7_value *pKey, ph7_value *pValue, void *pUserData);
|
||||
/*
|
||||
* Extract short or long argument option values.
|
||||
*/
|
||||
static void VmExtractOptArgValue(
|
||||
ph7_value *pArray, /* getopt() return value */
|
||||
ph7_value *pWorker, /* Worker variable */
|
||||
const char *zArg, /* Argument stream */
|
||||
const char *zArgEnd,/* End of the argument stream */
|
||||
int need_val, /* TRUE to fetch option argument */
|
||||
ph7_context *pCtx, /* Call Context */
|
||||
const char *zName /* Option name */) {
|
||||
ph7_value_bool(pWorker, 0);
|
||||
if(!need_val) {
|
||||
/*
|
||||
* Option does not need arguments.
|
||||
* Insert the option name and a boolean FALSE.
|
||||
*/
|
||||
ph7_array_add_strkey_elem(pArray, (const char *)zName, pWorker); /* Will make it's own copy */
|
||||
} else {
|
||||
const char *zCur;
|
||||
/* Extract option argument */
|
||||
zArg++;
|
||||
if(zArg < zArgEnd && zArg[0] == '=') {
|
||||
zArg++;
|
||||
}
|
||||
while(zArg < zArgEnd && (unsigned char)zArg[0] < 0xc0 && SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
if(zArg >= zArgEnd || zArg[0] == '-') {
|
||||
/*
|
||||
* Argument not found.
|
||||
* Insert the option name and a boolean FALSE.
|
||||
*/
|
||||
ph7_array_add_strkey_elem(pArray, (const char *)zName, pWorker); /* Will make it's own copy */
|
||||
return;
|
||||
}
|
||||
/* Delimit the value */
|
||||
zCur = zArg;
|
||||
if(zArg[0] == '\'' || zArg[0] == '"') {
|
||||
int d = zArg[0];
|
||||
/* Delimit the argument */
|
||||
zArg++;
|
||||
zCur = zArg;
|
||||
while(zArg < zArgEnd) {
|
||||
if(zArg[0] == d && zArg[-1] != '\\') {
|
||||
/* Delimiter found,exit the loop */
|
||||
break;
|
||||
}
|
||||
zArg++;
|
||||
}
|
||||
/* Save the value */
|
||||
ph7_value_string(pWorker, zCur, (int)(zArg - zCur));
|
||||
if(zArg < zArgEnd) {
|
||||
zArg++;
|
||||
}
|
||||
} else {
|
||||
while(zArg < zArgEnd && !SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
/* Save the value */
|
||||
ph7_value_string(pWorker, zCur, (int)(zArg - zCur));
|
||||
}
|
||||
/*
|
||||
* Check if we are dealing with multiple values.
|
||||
* If so,create an array to hold them,rather than a scalar variable.
|
||||
*/
|
||||
while(zArg < zArgEnd && (unsigned char)zArg[0] < 0xc0 && SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
if(zArg < zArgEnd && zArg[0] != '-') {
|
||||
ph7_value *pOptArg; /* Array of option arguments */
|
||||
pOptArg = ph7_context_new_array(pCtx);
|
||||
if(pOptArg == 0) {
|
||||
PH7_VmMemoryError(pCtx->pVm);
|
||||
} else {
|
||||
/* Insert the first value */
|
||||
ph7_array_add_elem(pOptArg, 0, pWorker); /* Will make it's own copy */
|
||||
for(;;) {
|
||||
if(zArg >= zArgEnd || zArg[0] == '-') {
|
||||
/* No more value */
|
||||
break;
|
||||
}
|
||||
/* Delimit the value */
|
||||
zCur = zArg;
|
||||
if(zArg < zArgEnd && zArg[0] == '\\') {
|
||||
zArg++;
|
||||
zCur = zArg;
|
||||
}
|
||||
while(zArg < zArgEnd && !SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
/* Reset the string cursor */
|
||||
ph7_value_reset_string_cursor(pWorker);
|
||||
/* Save the value */
|
||||
ph7_value_string(pWorker, zCur, (int)(zArg - zCur));
|
||||
/* Insert */
|
||||
ph7_array_add_elem(pOptArg, 0, pWorker); /* Will make it's own copy */
|
||||
/* Jump trailing white spaces */
|
||||
while(zArg < zArgEnd && (unsigned char)zArg[0] < 0xc0 && SyisSpace(zArg[0])) {
|
||||
zArg++;
|
||||
}
|
||||
}
|
||||
/* Insert the option arg array */
|
||||
ph7_array_add_strkey_elem(pArray, (const char *)zName, pOptArg); /* Will make it's own copy */
|
||||
/* Safely release */
|
||||
ph7_context_release_value(pCtx, pOptArg);
|
||||
}
|
||||
} else {
|
||||
/* Single value */
|
||||
ph7_array_add_strkey_elem(pArray, (const char *)zName, pWorker); /* Will make it's own copy */
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* array getopt(string $options[,array $longopts ])
|
||||
* Gets options from the command line argument list.
|
||||
* Parameters
|
||||
* $options
|
||||
* Each character in this string will be used as option characters
|
||||
* and matched against options passed to the script starting with
|
||||
* a single hyphen (-). For example, an option string "x" recognizes
|
||||
* an option -x. Only a-z, A-Z and 0-9 are allowed.
|
||||
* $longopts
|
||||
* An array of options. Each element in this array will be used as option
|
||||
* strings and matched against options passed to the script starting with
|
||||
* two hyphens (--). For example, an longopts element "opt" recognizes an
|
||||
* option --opt.
|
||||
* Return
|
||||
* This function will return an array of option / argument pairs or FALSE
|
||||
* on failure.
|
||||
*/
|
||||
static int vm_builtin_getopt(ph7_context *pCtx, int nArg, ph7_value **apArg) {
|
||||
const char *zIn, *zEnd, *zArg, *zArgIn, *zArgEnd;
|
||||
struct getopt_long_opt sLong;
|
||||
ph7_value *pArray, *pWorker;
|
||||
SyBlob *pArg;
|
||||
int nByte;
|
||||
if(nArg < 1 || !ph7_value_is_string(apArg[0])) {
|
||||
/* Missing/Invalid arguments, return FALSE */
|
||||
PH7_VmThrowError(pCtx->pVm, PH7_CTX_ERR, "Missing/Invalid option arguments");
|
||||
}
|
||||
/* Extract option arguments */
|
||||
zIn = ph7_value_to_string(apArg[0], &nByte);
|
||||
zEnd = &zIn[nByte];
|
||||
/* Point to the string representation of the $argv[] array */
|
||||
pArg = &pCtx->pVm->sArgv;
|
||||
/* Create a new empty array and a worker variable */
|
||||
pArray = ph7_context_new_array(pCtx);
|
||||
pWorker = ph7_context_new_scalar(pCtx);
|
||||
if(pArray == 0 || pWorker == 0) {
|
||||
PH7_VmMemoryError(pCtx->pVm);
|
||||
}
|
||||
if(SyBlobLength(pArg) < 1) {
|
||||
/* Empty command line, return the empty array*/
|
||||
ph7_result_value(pCtx, pArray);
|
||||
/* Everything will be released automatically when we return
|
||||
* from this function.
|
||||
*/
|
||||
return PH7_OK;
|
||||
}
|
||||
zArgIn = (const char *)SyBlobData(pArg);
|
||||
zArgEnd = &zArgIn[SyBlobLength(pArg)];
|
||||
/* Fill the long option structure */
|
||||
sLong.pArray = pArray;
|
||||
sLong.pWorker = pWorker;
|
||||
sLong.zArgIn = zArgIn;
|
||||
sLong.zArgEnd = zArgEnd;
|
||||
sLong.pCtx = pCtx;
|
||||
/* Start processing */
|
||||
while(zIn < zEnd) {
|
||||
int c = zIn[0];
|
||||
int need_val = 0;
|
||||
/* Advance the stream cursor */
|
||||
zIn++;
|
||||
/* Ignore non-alphanum characters */
|
||||
if(!SyisAlphaNum(c)) {
|
||||
continue;
|
||||
}
|
||||
if(zIn < zEnd && zIn[0] == ':') {
|
||||
zIn++;
|
||||
need_val = 1;
|
||||
if(zIn < zEnd && zIn[0] == ':') {
|
||||
zIn++;
|
||||
}
|
||||
}
|
||||
/* Find option */
|
||||
zArg = VmFindShortOpt(c, zArgIn, zArgEnd);
|
||||
if(zArg == 0) {
|
||||
/* No such option */
|
||||
continue;
|
||||
}
|
||||
/* Extract option argument value */
|
||||
VmExtractOptArgValue(pArray, pWorker, zArg, zArgEnd, need_val, pCtx, (const char *)&c);
|
||||
}
|
||||
if(nArg > 1 && ph7_value_is_array(apArg[1]) && ph7_array_count(apArg[1]) > 0) {
|
||||
/* Process long options */
|
||||
ph7_array_walk(apArg[1], VmProcessLongOpt, &sLong);
|
||||
}
|
||||
/* Return the option array */
|
||||
ph7_result_value(pCtx, pArray);
|
||||
/*
|
||||
* Don't worry about freeing memory, everything will be released
|
||||
* automatically as soon we return from this foreign function.
|
||||
*/
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* Array walker callback used for processing long options values.
|
||||
*/
|
||||
static int VmProcessLongOpt(ph7_value *pKey, ph7_value *pValue, void *pUserData) {
|
||||
struct getopt_long_opt *pOpt = (struct getopt_long_opt *)pUserData;
|
||||
const char *zArg, *zOpt, *zEnd;
|
||||
int need_value = 0;
|
||||
int nByte;
|
||||
/* Value must be of type string */
|
||||
if(!ph7_value_is_string(pValue)) {
|
||||
/* Simply ignore */
|
||||
return PH7_OK;
|
||||
}
|
||||
zOpt = ph7_value_to_string(pValue, &nByte);
|
||||
if(nByte < 1) {
|
||||
/* Empty string,ignore */
|
||||
return PH7_OK;
|
||||
}
|
||||
zEnd = &zOpt[nByte - 1];
|
||||
if(zEnd[0] == ':') {
|
||||
char *zTerm;
|
||||
/* Try to extract a value */
|
||||
need_value = 1;
|
||||
while(zEnd >= zOpt && zEnd[0] == ':') {
|
||||
zEnd--;
|
||||
}
|
||||
if(zOpt >= zEnd) {
|
||||
/* Empty string,ignore */
|
||||
SXUNUSED(pKey);
|
||||
return PH7_OK;
|
||||
}
|
||||
zEnd++;
|
||||
zTerm = (char *)zEnd;
|
||||
zTerm[0] = 0;
|
||||
} else {
|
||||
zEnd = &zOpt[nByte];
|
||||
}
|
||||
/* Find the option */
|
||||
zArg = VmFindLongOpt(zOpt, (int)(zEnd - zOpt), pOpt->zArgIn, pOpt->zArgEnd);
|
||||
if(zArg == 0) {
|
||||
/* No such option, return immediately */
|
||||
return PH7_OK;
|
||||
}
|
||||
/* Try to extract a value */
|
||||
VmExtractOptArgValue(pOpt->pArray, pOpt->pWorker, zArg, pOpt->zArgEnd, need_value, pOpt->pCtx, zOpt);
|
||||
return PH7_OK;
|
||||
}
|
||||
/*
|
||||
* int utf8_encode(string $input)
|
||||
* UTF-8 encoding.
|
||||
@@ -12289,7 +12088,6 @@ static const ph7_builtin_func aVmFunc[] = {
|
||||
{ "random_bytes", vm_builtin_random_bytes },
|
||||
{ "uniqid", vm_builtin_uniqid },
|
||||
/* Language constructs functions */
|
||||
{ "print", vm_builtin_print },
|
||||
{ "exit", vm_builtin_exit },
|
||||
{ "eval", vm_builtin_eval },
|
||||
/* Variable handling functions */
|
||||
@@ -12338,7 +12136,6 @@ static const ph7_builtin_func aVmFunc[] = {
|
||||
{"utf8_encode", vm_builtin_utf8_encode},
|
||||
{"utf8_decode", vm_builtin_utf8_decode},
|
||||
/* Command line processing */
|
||||
{"getopt", vm_builtin_getopt },
|
||||
/* Files/URI inclusion facility */
|
||||
{ "get_include_path", vm_builtin_get_include_path },
|
||||
{ "get_included_files", vm_builtin_get_included_files},
|
||||
|
||||
Reference in New Issue
Block a user