Add TextWriter, IOException, per-VM module data and pre-load imports; Add console module with Console class

This commit is contained in:
2026-11-23 18:36:46 +01:00
parent 2243557bf5
commit 4d06edd045
55 changed files with 1679 additions and 675 deletions
+218 -421
View File
@@ -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},