From 1db842fe0f418e11c09ca8838702e936df2005da Mon Sep 17 00:00:00 2001 From: Rafal Kupiec Date: Tue, 24 Nov 2026 09:34:27 +0100 Subject: [PATCH] Add system module with System class, core native exception helper and remove useless builtins --- engine/classes.c | 115 +++++ engine/compiler.c | 26 +- engine/constant.c | 47 -- engine/debug.c | 3 - engine/hashmap.c | 11 +- engine/lexer.c | 1 - engine/oop.c | 6 +- engine/parser.c | 4 +- engine/vfs.c | 467 ------------------- engine/vm.c | 311 +----------- include/compiler.h | 1 - include/ph7.h | 5 + include/ph7int.h | 15 +- modules/char/char.c | 139 +----- modules/math/math.c | 171 +------ modules/system/system.c | 830 +++++++++++++++++++++++++++++++++ modules/system/system.h | 24 + tests/complex_expressions2.aer | 7 +- tests/ip_addr_enc_dec.aer | 5 +- tests/static_var.aer | 7 +- 20 files changed, 1050 insertions(+), 1145 deletions(-) create mode 100644 modules/system/system.c create mode 100644 modules/system/system.h diff --git a/engine/classes.c b/engine/classes.c index 0dbf05b..7c2f2cf 100644 --- a/engine/classes.c +++ b/engine/classes.c @@ -431,6 +431,121 @@ PH7_PRIVATE sxi32 PH7_VmThrowIoException(ph7_context *pCtx, int nCode, const cha rc = ph7_result_value(pCtx, pObj); return rc == PH7_OK ? PH7_EXCEPTION : rc; } +/* Stamp file/line with the first script frame of the active call stack for the + * generic native-exception thrower. Native frames ([NATIVE], line 0) are + * skipped so a catch(Exception $e) observes the script location that raised + * the error. IOException keeps its own stamp because its constructor already + * performs one. */ +static void NativeExceptionStampSite(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 = 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); +} +/* Core-owned throw used by native modules that publish a custom exception + * class (MathException, CharException, ...). The named class constructor is + * invoked with (message, code), the instance is stamped and published as the + * context result; every temporary is released on all paths. */ +PH7_PRIVATE sxi32 PH7_VmThrowNativeException(ph7_context *pCtx, const char *zClass, + int nCode, const char *zMessage) { + ph7_vm *pVm = pCtx->pVm; + ph7_class *pClass; + ph7_class_instance *pInst; + ph7_class_method *pCons; + ph7_value *pObj, *apArg[2], *aTmp[2]; + sxi32 rc; + sxu32 n; + if(pVm->iPendingTransfer) { + return PH7_EXCEPTION; /* a handler exception takes precedence */ + } + pClass = PH7_VmExtractClass(pVm, zClass, (sxu32)SyStrlen(zClass), FALSE); + if(pClass == 0) { + return PH7_ABORT; + } + 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], zMessage, -1); + ph7_value_int(aTmp[1], nCode); + for(n = 0 ; n < SX_ARRAYSIZE(apArg) ; ++n) { + apArg[n] = aTmp[n]; + } + pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1); + if(pCons) { + rc = PH7_VmCallClassMethod(pVm, pInst, pCons, 0, 2, apArg); + if(pInst->iRef < 1) { + pInst->iRef = 1; + } + 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]); + } + } + NativeExceptionStampSite(pVm, pInst); + if(pInst->iRef < 1) { + pInst->iRef = 1; + } + PH7_MemObjRelease(pObj); + pObj->x.pOther = pInst; + MemObjSetType(pObj, MEMOBJ_OBJ); + rc = ph7_result_value(pCtx, pObj); + ph7_context_release_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 }; diff --git a/engine/compiler.c b/engine/compiler.c index ff5fcac..33609b0 100644 --- a/engine/compiler.c +++ b/engine/compiler.c @@ -2782,29 +2782,6 @@ static sxi32 PH7_CompileReturn(ph7_gen_state *pGen) { PH7_VmEmitInstr(pGen->pVm, pGen->pIn->nLine, PH7_OP_DONE, nRet, 0, (void *)1, 0); return SXRET_OK; } -/* - * Compile the die/exit language construct. - * The role of these constructs is to terminate execution of the script. - * Shutdown functions will always be executed even if exit() is called. - */ -static sxi32 PH7_CompileHalt(ph7_gen_state *pGen) { - sxi32 nExpr = 0; - sxi32 rc; - /* Jump the exit keyword */ - pGen->pIn++; - if(pGen->pIn < pGen->pEnd && (pGen->pIn->nType & PH7_TK_SEMI) == 0) { - /* Compile the expression */ - rc = PH7_CompileExpr(&(*pGen), 0, 0); - if(rc == SXERR_ABORT) { - return SXERR_ABORT; - } else if(rc != SXERR_EMPTY) { - nExpr = 1; - } - } - /* Emit the HALT instruction */ - PH7_VmEmitInstr(pGen->pVm, pGen->pIn->nLine, PH7_OP_HALT, nExpr, 0, 0, 0); - return SXRET_OK; -} /* * Compile the var statement. */ @@ -3244,7 +3221,7 @@ static sxi32 PH7_CompileInclude(ph7_gen_state *pGen) { * 3 -) Function overloading!! * Example: * function foo($a) { - * return $a.PHP_EOL; + * return $a.PHP_INT_MAX; * } * function foo($a, $b) { * return $a + $b; @@ -5762,7 +5739,6 @@ static const LangConstruct aLangConstruct[] = { { PH7_KEYWORD_RETURN, PH7_CompileReturn }, /* return statement */ { PH7_KEYWORD_SWITCH, PH7_CompileSwitch }, /* Switch statement */ { PH7_KEYWORD_DO, PH7_CompileDoWhile }, /* do{ }while(); statement */ - { PH7_KEYWORD_EXIT, PH7_CompileHalt }, /* exit language construct */ { PH7_KEYWORD_TRY, PH7_CompileTry }, /* try statement */ { PH7_KEYWORD_THROW, PH7_CompileThrow }, /* throw statement */ { PH7_KEYWORD_GOTO, PH7_CompileGoto }, /* goto statement */ diff --git a/engine/constant.c b/engine/constant.c index 2d6e372..62d4015 100644 --- a/engine/constant.c +++ b/engine/constant.c @@ -8,50 +8,6 @@ */ #include "ph7int.h" /* This file implement built-in constants for the PH7 engine. */ -/* - * PH7_VERSION - * Expand the current version of the PH7 Engine. - */ -static void PH7_VER_Const(ph7_value *pVal, void *pUnused) { - SXUNUSED(pUnused); - ph7_value_string(pVal, ph7_lib_signature(), -1/*Compute length automatically*/); -} -#ifdef __WINNT__ - #include -#elif defined(__UNIXES__) - #include -#endif -/* - * PHP_OS - * Expand the name of the host Operating System. - */ -static void PH7_OS_Const(ph7_value *pVal, void *pUnused) { -#if defined(__WINNT__) - ph7_value_string(pVal, "WINNT", (int)sizeof("WINNT") - 1); -#elif defined(__UNIXES__) - struct utsname sInfo; - if(uname(&sInfo) != 0) { - ph7_value_string(pVal, "Unix", (int)sizeof("Unix") - 1); - } else { - ph7_value_string(pVal, sInfo.sysname, -1); - } -#else - ph7_value_string(pVal, "Host OS", (int)sizeof("Host OS") - 1); -#endif - SXUNUSED(pUnused); -} -/* - * PHP_EOL - * Expand the correct 'End Of Line' symbol for this platform. - */ -static void PH7_EOL_Const(ph7_value *pVal, void *pUnused) { - SXUNUSED(pUnused); -#ifdef __WINNT__ - ph7_value_string(pVal, "\r\n", (int)sizeof("\r\n") - 1); -#else - ph7_value_string(pVal, "\n", (int)sizeof(char)); -#endif -} /* * PHP_INT_MAX * Expand the largest integer supported. @@ -1078,9 +1034,6 @@ static void PH7_EXTR_PREFIX_IF_EXISTS_Const(ph7_value *pVal, void *pUserData) { * Table of built-in constants. */ static const ph7_builtin_constant aBuiltIn[] = { - {"PH7_VERSION", PH7_VER_Const }, - {"PHP_OS", PH7_OS_Const }, - {"PHP_EOL", PH7_EOL_Const }, {"PHP_INT_MAX", PH7_INTMAX_Const }, {"MAXINT", PH7_INTMAX_Const }, {"PHP_INT_SIZE", PH7_INTSIZE_Const }, diff --git a/engine/debug.c b/engine/debug.c index d92ba60..6da8fa7 100644 --- a/engine/debug.c +++ b/engine/debug.c @@ -82,9 +82,6 @@ static const char *VmInstrToString(sxi32 nOp) { case PH7_OP_DONE: zOp = "DONE"; break; - case PH7_OP_HALT: - zOp = "HALT"; - break; case PH7_OP_IMPORT: zOp = "IMPORT"; break; diff --git a/engine/hashmap.c b/engine/hashmap.c index e553e73..48013ed 100644 --- a/engine/hashmap.c +++ b/engine/hashmap.c @@ -1648,11 +1648,12 @@ typedef struct { * [SXERR_ABORT]. The comparator's original status decides what the builtin * hands back to the VM call machinery: an exception value stored into the * result slot plus PH7_EXCEPTION [the VM moves that copy into the throw - * transfer and unwinds to catch/finally], or plain PH7_ABORT for exit() or a - * fatal raised inside the comparator. The pending carrier is released exactly - * once here. iPendingRC == 0 means nothing was pending: internal comparators - * [flags, keys, random] never invoke user code and never fill it, and the - * FALSE return is kept as a defensive fallback for them. The same fallback + * transfer and unwinds to catch/finally], or plain PH7_ABORT for an abort + * request [System::Exit()] or a fatal raised inside the comparator. The + * pending carrier is released exactly once here. iPendingRC == 0 means nothing + * was pending: internal comparators [flags, keys, random] never invoke user + * code and never fill it, and the FALSE return is kept as a defensive fallback + * for them. The same fallback * also catches any THIRD status PH7_VmCallUserFunction could report beyond * PH7_EXCEPTION/PH7_ABORT [iPendingRC != 0 but neither known value]: every * call site pre-checks callability and reachable call failures abort, so no diff --git a/engine/lexer.c b/engine/lexer.c index 740784a..d61c19c 100644 --- a/engine/lexer.c +++ b/engine/lexer.c @@ -642,7 +642,6 @@ static sxu32 KeywordCode(const char *z, sxu32 n) { /* Reserved keywords */ {"define", PH7_KEYWORD_DEFINE}, {"eval", PH7_KEYWORD_EVAL}, - {"exit", PH7_KEYWORD_EXIT}, {"import", PH7_KEYWORD_IMPORT}, {"include", PH7_KEYWORD_INCLUDE}, {"is", PH7_KEYWORD_IS}, diff --git a/engine/oop.c b/engine/oop.c index 6cc164b..ccb1dc1 100644 --- a/engine/oop.c +++ b/engine/oop.c @@ -752,19 +752,19 @@ done: * { * public function printItem($string) * { - * echo 'Foo: ' . $string . PHP_EOL; + * echo 'Foo: ' . $string . "\n"; * } * * public function printPHP() * { - * echo 'PHP is great.' . PHP_EOL; + * echo 'PHP is great.' . "\n"; * } * } * class bar extends foo * { * public function printItem($string) * { - * echo 'Bar: ' . $string . PHP_EOL; + * echo 'Bar: ' . $string . "\n"; * } * } * $foo = new foo(); diff --git a/engine/parser.c b/engine/parser.c index 430d00d..b8a307c 100644 --- a/engine/parser.c +++ b/engine/parser.c @@ -318,7 +318,7 @@ static sxi32 ExprVerifyNodes(ph7_gen_state *pGen, ph7_expr_node **apNode, sxi32 } /* * Collect and assemble tokens holding a namespace path [i.e: namespace\to\const] - * or a simple literal [i.e: PHP_EOL]. + * or a simple literal [i.e: PHP_INT_MAX]. */ static void ExprAssembleLiteral(SyToken **ppCur, SyToken *pEnd) { SyToken *pIn = *ppCur; @@ -434,7 +434,7 @@ static sxi32 ExprAssembleClosure(ph7_gen_state *pGen, SyToken **ppCur, SyToken * * When errors,PH7 take care of generating the appropriate error message. * An expression node can be a variable [i.e: $var],an operator [i.e: ++] * an anonymous function [i.e: function(){ return "Hello"; }, a double/single - * quoted string, a literal [i.e: PHP_EOL],a namespace path + * quoted string, a literal [i.e: PHP_INT_MAX],a namespace path * [i.e: namespaces\path\to..],an array [i.e: {4,5,6}] and so on. */ static sxi32 ExprExtractNode(ph7_gen_state *pGen, ph7_expr_node **ppNode) { diff --git a/engine/vfs.c b/engine/vfs.c index 6cdd183..bbcdb6b 100644 --- a/engine/vfs.c +++ b/engine/vfs.c @@ -366,88 +366,6 @@ static int PH7_vfs_realpath(ph7_context *pCtx, int nArg, ph7_value **apArg) { } return PH7_OK; } -/* - * int sleep(int $seconds) - * Delays the program execution for the given number of seconds. - * Parameters - * $seconds - * Halt time in seconds. - * Return - * Zero on success or FALSE on failure. - */ -static int PH7_vfs_sleep(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_vfs *pVfs; - int rc, nSleep; - if(nArg < 1 || !ph7_value_is_int(apArg[0])) { - /* Missing/Invalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the underlying vfs */ - pVfs = (ph7_vfs *)ph7_context_user_data(pCtx); - if(pVfs == 0 || pVfs->xSleep == 0) { - /* IO routine not implemented, return NULL */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "IO routine(%s) not implemented in the underlying VFS", - ph7_function_name(pCtx) - ); - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Amount to sleep */ - nSleep = ph7_value_to_int(apArg[0]); - if(nSleep < 0) { - /* Invalid value, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Perform the requested operation (Microseconds) */ - rc = pVfs->xSleep((unsigned int)(nSleep * SX_USEC_PER_SEC)); - if(rc != PH7_OK) { - /* Return FALSE */ - ph7_result_bool(pCtx, 0); - } else { - /* Return zero */ - ph7_result_int(pCtx, 0); - } - return PH7_OK; -} -/* - * void usleep(int $micro_seconds) - * Delays program execution for the given number of micro seconds. - * Parameters - * $micro_seconds - * Halt time in micro seconds. A micro second is one millionth of a second. - * Return - * None. - */ -static int PH7_vfs_usleep(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_vfs *pVfs; - int nSleep; - if(nArg < 1 || !ph7_value_is_int(apArg[0])) { - /* Missing/Invalid argument, return immediately */ - return PH7_OK; - } - /* Point to the underlying vfs */ - pVfs = (ph7_vfs *)ph7_context_user_data(pCtx); - if(pVfs == 0 || pVfs->xSleep == 0) { - /* IO routine not implemented, return NULL */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "IO routine(%s) not implemented in the underlying VFS", - ph7_function_name(pCtx) - ); - return PH7_OK; - } - /* Amount to sleep */ - nSleep = ph7_value_to_int(apArg[0]); - if(nSleep < 0) { - /* Invalid value, return immediately */ - return PH7_OK; - } - /* Perform the requested operation (Microseconds) */ - pVfs->xSleep((unsigned int)nSleep); - return PH7_OK; -} /* * bool unlink (string $filename) * Delete a file. @@ -1342,115 +1260,6 @@ static int PH7_vfs_lstat(ph7_context *pCtx, int nArg, ph7_value **apArg) { * automatically as soon we return from this function. */ return PH7_OK; } -/* - * string getenv(string $varname) - * Gets the value of an environment variable. - * Parameters - * $varname - * The variable name. - * Return - * Returns the value of the environment variable varname, or FALSE if the environment - * variable varname does not exist. - */ -static int PH7_vfs_getenv(ph7_context *pCtx, int nArg, ph7_value **apArg) { - const char *zEnv; - ph7_vfs *pVfs; - int iLen; - if(nArg < 1 || !ph7_value_is_string(apArg[0])) { - /* Missing/Invalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Point to the underlying vfs */ - pVfs = (ph7_vfs *)ph7_context_user_data(pCtx); - if(pVfs == 0 || pVfs->xGetenv == 0) { - /* IO routine not implemented, return NULL */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "IO routine(%s) not implemented in the underlying VFS", - ph7_function_name(pCtx) - ); - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Extract the environment variable */ - zEnv = ph7_value_to_string(apArg[0], &iLen); - /* Set a boolean FALSE as the default return value */ - ph7_result_bool(pCtx, 0); - if(iLen < 1) { - /* Empty string */ - return PH7_OK; - } - /* Perform the requested operation */ - pVfs->xGetenv(zEnv, pCtx); - return PH7_OK; -} -/* - * bool putenv(string $settings) - * Set the value of an environment variable. - * Parameters - * $setting - * The setting, like "FOO=BAR" - * Return - * TRUE on success or FALSE on failure. - */ -static int PH7_vfs_putenv(ph7_context *pCtx, int nArg, ph7_value **apArg) { - const char *zName, *zValue; - char *zSettings, *zEnd; - ph7_vfs *pVfs; - int iLen, rc; - if(nArg < 1 || !ph7_value_is_string(apArg[0])) { - /* Missing/Invalid argument, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Extract the setting variable */ - zSettings = (char *)ph7_value_to_string(apArg[0], &iLen); - if(iLen < 1) { - /* Empty string, return FALSE */ - ph7_result_bool(pCtx, 0); - return PH7_OK; - } - /* Parse the setting */ - zEnd = &zSettings[iLen]; - zValue = 0; - zName = zSettings; - while(zSettings < zEnd) { - if(zSettings[0] == '=') { - /* Null terminate the name */ - zSettings[0] = 0; - zValue = &zSettings[1]; - break; - } - zSettings++; - } - /* Install the environment variable in the $_Env array */ - if(zValue == 0 || zName[0] == 0 || zValue >= zEnd || zName >= zValue) { - /* Invalid settings,retun FALSE */ - ph7_result_bool(pCtx, 0); - if(zSettings < zEnd) { - zSettings[0] = '='; - } - return PH7_OK; - } - ph7_vm_config(pCtx->pVm, PH7_VM_CONFIG_ENV_ATTR, zName, zValue, (int)(zEnd - zValue)); - /* Point to the underlying vfs */ - pVfs = (ph7_vfs *)ph7_context_user_data(pCtx); - if(pVfs == 0 || pVfs->xSetenv == 0) { - /* IO routine not implemented, return NULL */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "IO routine(%s) not implemented in the underlying VFS", - ph7_function_name(pCtx) - ); - ph7_result_bool(pCtx, 0); - zSettings[0] = '='; - return PH7_OK; - } - /* Perform the requested operation */ - rc = pVfs->xSetenv(zName, zValue); - ph7_result_bool(pCtx, rc == PH7_OK); - zSettings[0] = '='; - return PH7_OK; -} /* * bool touch(string $filename[,int64 $time = time()[,int64 $atime]]) * Sets access and modification time of file. @@ -2238,273 +2047,6 @@ static int PH7_vfs_sys_get_temp_dir(ph7_context *pCtx, int nArg, ph7_value **apA pVfs->xTempDir(pCtx); return PH7_OK; } -/* - * string get_current_user() - * Returns the name of the current working user. - * Parameters - * None - * Return - * Returns the name of the current working user. - */ -static int PH7_vfs_get_current_user(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_vfs *pVfs; - /* Point to the underlying vfs */ - pVfs = (ph7_vfs *)ph7_context_user_data(pCtx); - if(pVfs == 0 || pVfs->xUsername == 0) { - SXUNUSED(nArg); /* cc warning */ - SXUNUSED(apArg); - /* IO routine not implemented */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "IO routine(%s) not implemented in the underlying VFS", - ph7_function_name(pCtx) - ); - /* Set a dummy username */ - ph7_result_string(pCtx, "unknown", sizeof("unknown") - 1); - return PH7_OK; - } - /* Perform the requested operation */ - pVfs->xUsername(pCtx); - return PH7_OK; -} -/* - * int64 getmypid() - * Gets process ID. - * Parameters - * None - * Return - * Returns the process ID. - */ -static int PH7_vfs_getmypid(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_int64 nProcessId; - ph7_vfs *pVfs; - /* Point to the underlying vfs */ - pVfs = (ph7_vfs *)ph7_context_user_data(pCtx); - if(pVfs == 0 || pVfs->xProcessId == 0) { - SXUNUSED(nArg); /* cc warning */ - SXUNUSED(apArg); - /* IO routine not implemented, return -1 */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "IO routine(%s) not implemented in the underlying VFS", - ph7_function_name(pCtx) - ); - ph7_result_int(pCtx, -1); - return PH7_OK; - } - /* Perform the requested operation */ - nProcessId = (ph7_int64)pVfs->xProcessId(); - /* Set the result */ - ph7_result_int64(pCtx, nProcessId); - return PH7_OK; -} -/* - * int getmyuid() - * Get user ID. - * Parameters - * None - * Return - * Returns the user ID. - */ -static int PH7_vfs_getmyuid(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_vfs *pVfs; - int nUid; - /* Point to the underlying vfs */ - pVfs = (ph7_vfs *)ph7_context_user_data(pCtx); - if(pVfs == 0 || pVfs->xUid == 0) { - SXUNUSED(nArg); /* cc warning */ - SXUNUSED(apArg); - /* IO routine not implemented, return -1 */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "IO routine(%s) not implemented in the underlying VFS", - ph7_function_name(pCtx) - ); - ph7_result_int(pCtx, -1); - return PH7_OK; - } - /* Perform the requested operation */ - nUid = pVfs->xUid(); - /* Set the result */ - ph7_result_int(pCtx, nUid); - return PH7_OK; -} -/* - * int getmygid() - * Get group ID. - * Parameters - * None - * Return - * Returns the group ID. - */ -static int PH7_vfs_getmygid(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_vfs *pVfs; - int nGid; - /* Point to the underlying vfs */ - pVfs = (ph7_vfs *)ph7_context_user_data(pCtx); - if(pVfs == 0 || pVfs->xGid == 0) { - SXUNUSED(nArg); /* cc warning */ - SXUNUSED(apArg); - /* IO routine not implemented, return -1 */ - PH7_VmThrowError(pCtx->pVm, PH7_CTX_WARNING, - "IO routine(%s) not implemented in the underlying VFS", - ph7_function_name(pCtx) - ); - ph7_result_int(pCtx, -1); - return PH7_OK; - } - /* Perform the requested operation */ - nGid = pVfs->xGid(); - /* Set the result */ - ph7_result_int(pCtx, nGid); - return PH7_OK; -} -#ifdef __WINNT__ - #include -#elif defined(__UNIXES__) - #include -#endif -/* - * string php_uname([ string $mode = "a" ]) - * Returns information about the host operating system. - * Parameters - * $mode - * mode is a single character that defines what information is returned: - * 'a': This is the default. Contains all modes in the sequence "s n r v m". - * 's': Operating system name. eg. FreeBSD. - * 'n': Host name. eg. localhost.example.com. - * 'r': Release name. eg. 5.1.2-RELEASE. - * 'v': Version information. Varies a lot between operating systems. - * 'm': Machine type. eg. i386. - * Return - * OS description as a string. - */ -static int PH7_vfs_ph7_uname(ph7_context *pCtx, int nArg, ph7_value **apArg) { -#if defined(__WINNT__) - const char *zName = "Microsoft Windows"; - OSVERSIONINFOW sVer; -#elif defined(__UNIXES__) - struct utsname sName; -#endif - const char *zMode = "a"; - if(nArg > 0 && ph7_value_is_string(apArg[0])) { - /* Extract the desired mode */ - zMode = ph7_value_to_string(apArg[0], 0); - } -#if defined(__WINNT__) - sVer.dwOSVersionInfoSize = sizeof(sVer); - if(TRUE != GetVersionExW(&sVer)) { - ph7_result_string(pCtx, zName, -1); - return PH7_OK; - } - if(sVer.dwPlatformId == VER_PLATFORM_WIN32_NT) { - if(sVer.dwMajorVersion <= 4) { - zName = "Microsoft Windows NT"; - } else if(sVer.dwMajorVersion == 5) { - switch(sVer.dwMinorVersion) { - case 0: - zName = "Microsoft Windows 2000"; - break; - case 1: - zName = "Microsoft Windows XP"; - break; - case 2: - zName = "Microsoft Windows Server 2003"; - break; - } - } else if(sVer.dwMajorVersion == 6) { - switch(sVer.dwMinorVersion) { - case 0: - zName = "Microsoft Windows Vista"; - break; - case 1: - zName = "Microsoft Windows 7"; - break; - case 2: - zName = "Microsoft Windows Server 2008"; - break; - case 3: - zName = "Microsoft Windows 8"; - break; - default: - break; - } - } else if(sVer.dwMajorVersion == 10) { - switch(sVer.dwMinorVersion) { - case 0: - zName = "Microsoft Windows 10"; - break; - default: - break; - } - } - } - switch(zMode[0]) { - case 's': - /* Operating system name */ - ph7_result_string(pCtx, zName, -1/* Compute length automatically*/); - break; - case 'n': - /* Host name */ - ph7_result_string(pCtx, "localhost", (int)sizeof("localhost") - 1); - break; - case 'r': - case 'v': - /* Version information. */ - ph7_result_string_format(pCtx, "%u.%u build %u", - sVer.dwMajorVersion, sVer.dwMinorVersion, sVer.dwBuildNumber - ); - break; - case 'm': - /* Machine name */ - ph7_result_string(pCtx, "x86", (int)sizeof("x86") - 1); - break; - default: - ph7_result_string_format(pCtx, "%s localhost %u.%u build %u x86", - zName, - sVer.dwMajorVersion, sVer.dwMinorVersion, sVer.dwBuildNumber - ); - break; - } -#elif defined(__UNIXES__) - if(uname(&sName) != 0) { - ph7_result_string(pCtx, "Unix", (int)sizeof("Unix") - 1); - return PH7_OK; - } - switch(zMode[0]) { - case 's': - /* Operating system name */ - ph7_result_string(pCtx, sName.sysname, -1/* Compute length automatically*/); - break; - case 'n': - /* Host name */ - ph7_result_string(pCtx, sName.nodename, -1/* Compute length automatically*/); - break; - case 'r': - /* Release information */ - ph7_result_string(pCtx, sName.release, -1/* Compute length automatically*/); - break; - case 'v': - /* Version information. */ - ph7_result_string(pCtx, sName.version, -1/* Compute length automatically*/); - break; - case 'm': - /* Machine name */ - ph7_result_string(pCtx, sName.machine, -1/* Compute length automatically*/); - break; - default: - ph7_result_string_format(pCtx, - "%s %s %s %s %s", - sName.sysname, - sName.release, - sName.version, - sName.nodename, - sName.machine - ); - break; - } -#else - ph7_result_string(pCtx, "Unknown Operating System", (int)sizeof("Unknown Operating System") - 1); -#endif - return PH7_OK; -} /* * Section: * IO stream implementation. @@ -8047,8 +7589,6 @@ PH7_PRIVATE sxi32 PH7_RegisterIORoutine(ph7_vm *pVm) { {"mkdir", PH7_vfs_mkdir }, {"rename", PH7_vfs_rename }, {"realpath", PH7_vfs_realpath}, - {"sleep", PH7_vfs_sleep }, - {"usleep", PH7_vfs_usleep }, {"unlink", PH7_vfs_unlink }, {"chmod", PH7_vfs_chmod }, {"chown", PH7_vfs_chown }, @@ -8071,18 +7611,11 @@ PH7_PRIVATE sxi32 PH7_RegisterIORoutine(ph7_vm *pVm) { {"filetype", PH7_vfs_filetype }, {"stat", PH7_vfs_stat }, {"lstat", PH7_vfs_lstat }, - {"getenv", PH7_vfs_getenv }, - {"putenv", PH7_vfs_putenv }, {"touch", PH7_vfs_touch }, {"link", PH7_vfs_link }, {"symlink", PH7_vfs_symlink }, {"umask", PH7_vfs_umask }, {"sys_get_temp_dir", PH7_vfs_sys_get_temp_dir }, - {"get_current_user", PH7_vfs_get_current_user }, - {"getpid", PH7_vfs_getmypid }, - {"getuid", PH7_vfs_getmyuid }, - {"getgid", PH7_vfs_getmygid }, - {"php_uname", PH7_vfs_ph7_uname}, /* Path processing */ {"dirname", PH7_builtin_dirname }, {"basename", PH7_builtin_basename }, diff --git a/engine/vm.c b/engine/vm.c index 88c96e6..1e639c5 100644 --- a/engine/vm.c +++ b/engine/vm.c @@ -2711,7 +2711,7 @@ PH7_PRIVATE sxi32 PH7_VmMakeReady( /* Zero the reference table */ SyZero(pVm->apRefObj, sizeof(VmRefObj *) * pVm->nRefSize); } - /* Register special functions first [i.e: print, json_encode(), func_get_args(), die, etc.] */ + /* Register special functions first [i.e: print, json_encode(), func_get_args(), etc.] */ rc = VmRegisterSpecialFunction(&(*pVm)); if(rc != SXRET_OK) { /* Don't worry about freeing memory, everything will be released shortly */ @@ -2723,7 +2723,7 @@ PH7_PRIVATE sxi32 PH7_VmMakeReady( /* Don't worry about freeing memory, everything will be released shortly */ return rc; } - /* Register built-in constants [i.e: PHP_EOL, PHP_OS...] */ + /* Register built-in constants [i.e: PHP_INT_MAX, __DATE__...] */ PH7_RegisterBuiltInConstant(&(*pVm)); /* Register built-in functions [i.e: array_diff(), strlen(), etc.] */ PH7_RegisterBuiltInFunction(&(*pVm)); @@ -4202,31 +4202,6 @@ Resume: VmPopOperand(&pTos, 1); } goto Done; - /* - * HALT: P1 * * - * - * Program execution aborted: Clean up the mess left behind - * and abort immediately. - */ - case PH7_OP_HALT: - if(pInstr->iP1) { - if(pTos < pStack) { - goto Abort; - } - if(pTos->nType & MEMOBJ_STRING) { - if(SyBlobLength(&pTos->sBlob) > 0) { - /* Output the exit message */ - pVm->sVmConsumer.xConsumer(SyBlobData(&pTos->sBlob), SyBlobLength(&pTos->sBlob), - pVm->sVmConsumer.pUserData); - } - pVm->iExitStatus = 0; - } else if(pTos->nType & MEMOBJ_INT) { - /* Record exit status */ - pVm->iExitStatus = (sxi32)pTos->x.iVal; - } - VmPopOperand(&pTos, 1); - } - goto Abort; /* * JMP: P1 P2 * * @@ -4679,7 +4654,7 @@ Resume: /* * LOADC P1 P2 * * - * Load a constant [i.e: PHP_EOL,PHP_OS,__TIME__,...] indexed at P2 in the constant pool. + * Load a constant [i.e: PHP_INT_MAX,__DATE__,__TIME__,...] indexed at P2 in the constant pool. * If P1 is set,then this constant is candidate for expansion via user installable callbacks. */ case PH7_OP_LOADC: { @@ -7980,7 +7955,7 @@ PH7_PRIVATE sxi32 PH7_VmByteCodeExec(ph7_vm *pVm) { if(rc == SXERR_MEM) { PH7_VmMemoryError(pVm); } - /* Construction may stop via exit(); skip main, not shutdown. */ + /* Construction may stop via System::Exit(); skip main, not shutdown. */ goto Shutdown; } PH7_MemObjRelease(&pResult); @@ -10051,37 +10026,6 @@ static int vm_builtin_uniqid(ph7_context *pCtx, int nArg, ph7_value **apArg) { * Status: * Stable. */ -/* - * void exit(string $msg) - * void exit(int $status) - * void die(string $ms) - * void die(int $status) - * Output a message and terminate program execution. - * Parameter - * If status is a string, this function prints the status just before exiting. - * If status is an integer, that value will be used as the exit status - * and not printed - * Return - * NULL - */ -static int vm_builtin_exit(ph7_context *pCtx, int nArg, ph7_value **apArg) { - if(nArg > 0) { - if(ph7_value_is_string(apArg[0])) { - const char *zData; - int iLen = 0; - /* Print exit message */ - zData = ph7_value_to_string(apArg[0], &iLen); - ph7_context_output(pCtx, zData, iLen); - } else if(ph7_value_is_int(apArg[0])) { - sxi32 iExitStatus; - /* Record exit status code */ - iExitStatus = ph7_value_to_int(apArg[0]); - pCtx->pVm->iExitStatus = iExitStatus; - } - } - /* Abort processing immediately */ - return PH7_ABORT; -} /* * Unset a memory object [i.e: a ph7_value],remove it from the current * frame,the reference table and discard it's contents. @@ -10375,56 +10319,6 @@ static int vm_builtin_var_export(ph7_context *pCtx, int nArg, ph7_value **apArg) return SXRET_OK; } /* - * int get_memory_limit() - * Returns the amount of bytes that can be allocated from system. - * Parameters - * None - * Return - * The upper memory limit set for script processing. - */ -static int vm_builtin_get_memory_limit(ph7_context *pCtx, int nArg, ph7_value **apArg) { - SXUNUSED(apArg); - if(nArg != 0) { - ph7_result_bool(pCtx, 0); - } else { - ph7_result_int64(pCtx, pCtx->pVm->sAllocator.pHeap->nLimit); - } - return PH7_OK; -} -/* - * int get_memory_peak_usage() - * Returns the limit of memory set in Interpreter. - * Parameters - * None - * Return - * The maximum amount of memory that can be allocated from system. - */ -static int vm_builtin_get_memory_peak_usage(ph7_context *pCtx, int nArg, ph7_value **apArg) { - SXUNUSED(apArg); - if(nArg != 0) { - ph7_result_bool(pCtx, 0); - } else { - ph7_result_int64(pCtx, pCtx->pVm->sAllocator.pHeap->nPeak); - } - return PH7_OK; -} -/* - * int get_memory_usage() - * Returns the amount of memory, in bytes, that's currently being allocated. - * Parameters - * None - * Return - * Total memory allocated from system, including unused pages. - */ -static int vm_builtin_get_memory_usage(ph7_context *pCtx, int nArg, ph7_value **apArg) { - SXUNUSED(apArg); - if(nArg != 0) { - ph7_result_bool(pCtx, 0); - } else { - ph7_result_int64(pCtx, pCtx->pVm->sAllocator.pHeap->nSize); - } - return PH7_OK; -}/* * int/bool assert_options(int $what [, mixed $value ]) * Set/get the various assert flags. * Parameter @@ -10618,7 +10512,7 @@ static int vm_builtin_restore_exception_handler(ph7_context *pCtx, int nArg, ph7 * Sets a user-defined exception handler function. * Sets the default exception handler if an exception is not caught within a try/catch block. * NOTE - * Execution will NOT stop after the exception_handler calls for example die/exit unlike + * Execution will NOT stop after the exception_handler calls for example an explicit abort unlike * the standard PHP engine. * Parameters * $exception_handler @@ -10904,193 +10798,6 @@ static ph7_exception_block *VmFindCatch( } return 0; } -/* - * Section: - * Version,Credits and Copyright related functions. - * Authors: - * Symisc Systems,devel@symisc.net. - * Copyright (C) Symisc Systems,https://ph7.symisc.net - * Status: - * Stable. - */ -/* - * string ph7version(void) - * Returns the running version of the PH7 version. - * Parameters - * None - * Return - * Current PH7 version. - */ -static int vm_builtin_ph7_version(ph7_context *pCtx, int nArg, ph7_value **apArg) { - SXUNUSED(nArg); - SXUNUSED(apArg); /* cc warning */ - /* Current engine version */ - ph7_result_string(pCtx, PH7_VERSION, sizeof(PH7_VERSION) - 1); - return PH7_OK; -} -/* - * PH7 release information HTML page used by the ph7info() and ph7credits() functions. - */ -#define PH7_HTML_PAGE_HEADER ""\ - ""\ - ""\ - "PH7 engine credits"\ - ""\ - "
"\ - "

PH7 Engine Credits

"\ - "
"\ - "

"\ - "Symisc PH7 

"\ - "

"\ - "A highly efficient embeddable bytecode compiler and a Virtual Machine for the PHP(5) Programming Language.

"\ - "

Copyright (C) Symisc Systems.

"\ - "

Engine Version:

"\ - "

" - -#define PH7_HTML_PAGE_FORMAT "%s

"\ - "

Engine ID:

"\ - "

%s

"\ - "

Underlying VFS:

"\ - "

%s

"\ - "

Total Built-in Functions:

"\ - "

%d

"\ - "

Total Built-in Classes:

"\ - "

%d

"\ - "

Host Operating System:

"\ - "

%s

"\ - "

"\ - "

Licensed To: <Public Release Under The "\ - "Symisc Public License (SPL)>

" - -#define PH7_HTML_PAGE_FOOTER "

/*
"\ - " * Copyright (C) 2011, 2012 Symisc Systems. All rights reserved.
"\ - " *
"\ - " * Redistribution and use in source and binary forms, with or without
"\ - " * modification, are permitted provided that the following conditions
"\ - " * are met:
"\ - " * 1. Redistributions of source code must retain the above copyright
"\ - " *    notice, this list of conditions and the following disclaimer.
"\ - " * 2. Redistributions in binary form must reproduce the above copyright
"\ - " *    notice, this list of conditions and the following disclaimer in the
"\ - " *    documentation and/or other materials provided with the distribution.
"\ - " * 3. Redistributions in any form must be accompanied by information on
"\ - " *    how to obtain complete source code for the PH7 engine and any
"\ - " *    accompanying software that uses the PH7 engine software.
"\ - " *    The source code must either be included in the distribution
"\ - " *    or be available for no more than the cost of distribution plus
"\ - " *    a nominal fee, and must be freely redistributable under reasonable
"\ - " *    conditions. For an executable file, complete source code means
"\ - " *    the source code for all modules it contains.It does not include
"\ - " *    source code for modules or files that typically accompany the major
"\ - " *    components of the operating system on which the executable file runs.
"\ - " *
"\ - " * THIS SOFTWARE IS PROVIDED BY SYMISC SYSTEMS ``AS IS'' AND ANY EXPRESS
"\ - " * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
"\ - " * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
"\ - " * NON-INFRINGEMENT, ARE DISCLAIMED.  IN NO EVENT SHALL SYMISC SYSTEMS
"\ - " * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
"\ - " * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
"\ - " * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
"\ - " * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
"\ - " * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
"\ - " * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
"\ - " * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"\ - " */
"\ - "

"\ - "

Copyright (C) Symisc Systems"\ - "

" -/* - * bool ph7credits(void) - * bool ph7info(void) - * bool ph7copyright(void) - * Prints out the credits for PH7 engine - * Parameters - * None - * Return - * Always TRUE - */ -static int vm_builtin_ph7_credits(ph7_context *pCtx, int nArg, ph7_value **apArg) { - ph7_vm *pVm = pCtx->pVm; /* Point to the underlying VM */ - /* Expand the HTML page above*/ - ph7_context_output(pCtx, PH7_HTML_PAGE_HEADER, (int)sizeof(PH7_HTML_PAGE_HEADER) - 1); - ph7_context_output_format( - pCtx, - PH7_HTML_PAGE_FORMAT, - ph7_lib_version(), /* Engine version */ - ph7_lib_signature(), /* Engine signature */ - pVm->pEngine->pVfs ? pVm->pEngine->pVfs->zName : "null_vfs", - SyHashTotalEntry(&pVm->hFunction) + SyHashTotalEntry(&pVm->hHostFunction),/* # built-in functions */ - SyHashTotalEntry(&pVm->hClass), -#ifdef __WINNT__ - "Windows NT" -#elif defined(__UNIXES__) - "UNIX-Like" -#else - "Other OS" -#endif - ); - ph7_context_output(pCtx, PH7_HTML_PAGE_FOOTER, (int)sizeof(PH7_HTML_PAGE_FOOTER) - 1); - SXUNUSED(nArg); /* cc warning */ - SXUNUSED(apArg); - /* Return TRUE */ - //ph7_result_bool(pCtx,1); - return PH7_OK; -} /* * Section: * URL related routines. @@ -12175,7 +11882,6 @@ static const ph7_builtin_func aVmFunc[] = { { "random_bytes", vm_builtin_random_bytes }, { "uniqid", vm_builtin_uniqid }, /* Language constructs functions */ - { "exit", vm_builtin_exit }, { "eval", vm_builtin_eval }, /* Variable handling functions */ { "get_defined_vars", vm_builtin_get_defined_vars}, @@ -12199,10 +11905,6 @@ static const ph7_builtin_func aVmFunc[] = { { "ob_get_level", vm_builtin_ob_get_level }, { "ob_list_handlers", vm_builtin_ob_list_handlers }, { "ob_start", vm_builtin_ob_start }, - /* Memory usage reporting */ - { "get_memory_limit", vm_builtin_get_memory_limit }, - { "get_memory_peak_usage", vm_builtin_get_memory_peak_usage }, - { "get_memory_usage", vm_builtin_get_memory_usage }, /* Assertion functions */ { "assert_options", vm_builtin_assert_options }, { "assert", vm_builtin_assert }, @@ -12210,9 +11912,6 @@ static const ph7_builtin_func aVmFunc[] = { { "restore_exception_handler", vm_builtin_restore_exception_handler }, { "set_exception_handler", vm_builtin_set_exception_handler }, { "debug_backtrace", vm_builtin_debug_backtrace}, - /* Release info */ - {"ph7version", vm_builtin_ph7_version }, - {"phpinfo", vm_builtin_ph7_credits }, /* hashmap */ {"compact", vm_builtin_compact }, {"extract", vm_builtin_extract }, diff --git a/include/compiler.h b/include/compiler.h index d2621a1..893c55c 100644 --- a/include/compiler.h +++ b/include/compiler.h @@ -134,7 +134,6 @@ static sxi32 GenStateForEachNodeValidator(ph7_gen_state *pGen, ph7_expr_node *pR static sxi32 PH7_CompileForeach(ph7_gen_state *pGen); static sxi32 PH7_CompileIf(ph7_gen_state *pGen); static sxi32 PH7_CompileReturn(ph7_gen_state *pGen); -static sxi32 PH7_CompileHalt(ph7_gen_state *pGen); static sxi32 PH7_CompileVar(ph7_gen_state *pGen); static sxi32 PH7_CompileNamespace(ph7_gen_state *pGen); static sxi32 PH7_CompileUsing(ph7_gen_state *pGen); diff --git a/include/ph7.h b/include/ph7.h index f86809d..ede8dad 100644 --- a/include/ph7.h +++ b/include/ph7.h @@ -257,6 +257,11 @@ struct SyMutexMethods { #define PH7_LOOKED SXERR_LOCKED /* Forbidden Operation */ #define PH7_COMPILE_ERR (-70) /* Compilation error */ #define PH7_VM_ERR (-71) /* Virtual machine error */ +/* + * initializeModule() must return this code BEFORE publishing anything + * (classes, functions or constants) and before allocating any per-VM data: + * the engine releases the module library immediately after the return. + */ #define PH7_MODULE_SAPI_DENIED 1 /* Returned by initializeModule: module not available for the current SAPI */ /* end-of-error-codes */ /* diff --git a/include/ph7int.h b/include/ph7int.h index c45ed39..a467c47 100644 --- a/include/ph7int.h +++ b/include/ph7int.h @@ -705,7 +705,7 @@ struct ph7_constant_info { SySet *pConsCode; }; /* - * Each registered constant [i.e: __TIME__, __DATE__, PHP_OS, INT_MAX, etc.] is stored + * Each registered constant [i.e: __TIME__, __DATE__, PATH_SEPARATOR, INT_MAX, etc.] is stored * in an instance of the following structure. * Please refer to the official documentation for more information * on how to create/install foreign constants. @@ -1449,8 +1449,8 @@ enum iErrCode { */ enum ph7_vm_op { PH7_OP_DONE = 1, /* Done */ - PH7_OP_HALT, /* Halt */ - PH7_OP_IMPORT, /* Import AerScript module */ + /* 2 was PH7_OP_HALT (retired exit construct); gap kept so opcode values do not shift. */ + PH7_OP_IMPORT = 3, /* Import AerScript module */ PH7_OP_INCLUDE, /* Include another source file */ PH7_OP_DECLARE, /* Declare a variable */ PH7_OP_LOADV, /* Load variable */ @@ -1651,7 +1651,7 @@ enum ph7_expr_id { #define PH7_KEYWORD_CLASS 32 /* class */ #define PH7_KEYWORD_IN 33 /* in */ #define PH7_KEYWORD_CONTINUE 34 /* continue */ -#define PH7_KEYWORD_EXIT 35 /* exit */ +/* 35 was PH7_KEYWORD_EXIT (retired exit construct); gap kept so keyword IDs do not shift. */ #define PH7_KEYWORD_FINALLY 36 /* finally */ #define PH7_KEYWORD_IMPLEMENTS 39 /* implements */ #define PH7_KEYWORD_INCLUDE 41 /* include */ @@ -1798,6 +1798,13 @@ PH7_PRIVATE sxi32 PH7_VmThrowError(ph7_vm *pVm, sxi32 iErr, const char *zMessage /* classes.c: publish a core IOException instance as a pending exception. * Returns PH7_EXCEPTION on success, PH7_ABORT on allocation failure. */ PH7_PRIVATE sxi32 PH7_VmThrowIoException(ph7_context *pCtx, int nCode, const char *zMsg); +/* classes.c: publish an instance of the named exception class as a pending + * exception. The constructor receives (message, code); file/line are stamped + * from the first non-[NATIVE] script frame. Returns PH7_EXCEPTION on success, + * PH7_ABORT when the class is missing or allocation fails, and the constructor + * result on constructor failure. */ +PH7_PRIVATE sxi32 PH7_VmThrowNativeException(ph7_context *pCtx, const char *zClass, + int nCode, const char *zMessage); /* vm.c: per-VM, per-module opaque state (C13). Lookups are by module name. */ PH7_PRIVATE void *PH7_VmModuleData(ph7_vm *pVm, const char *zModule); PH7_PRIVATE sxi32 PH7_VmSetModuleData(ph7_vm *pVm, const char *zModule, diff --git a/modules/char/char.c b/modules/char/char.c index c747fc6..ae53358 100644 --- a/modules/char/char.c +++ b/modules/char/char.c @@ -35,121 +35,6 @@ static const char *CharErrorDescription(int nErr) { /* ------------------------------------------------------------------ */ /* CharException */ /* ------------------------------------------------------------------ */ -static ph7_value *CharInstField(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. */ -static void CharStampSite(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 = CharInstField(pInst, "file"); - if(pField) { - PH7_MemObjRelease(pField); - PH7_MemObjInit(pVm, pField); - (void)ph7_value_string(pField, pTrace->pFile->zString, (int)pTrace->pFile->nByte); - } - pField = CharInstField(pInst, "line"); - if(pField) { - (void)ph7_value_int64(pField, (ph7_int64)pTrace->nLine); - } - break; - } - SySetRelease(&sTrace); -} -/* Throw a real CharException instance; every temporary is released on all - * paths and the pending transfer is left for the VM unwinder. */ -static int CharThrow(ph7_context *pCtx, int nErr, const char *zMsg) { - ph7_vm *pVm = pCtx->pVm; - ph7_class *pClass; - ph7_class_instance *pInst; - ph7_class_method *pCons; - ph7_value *pObj, *apArg[2], *aTmp[2]; - sxi32 rc; - sxu32 n; - if(pVm->iPendingTransfer) { - return PH7_EXCEPTION; - } - pClass = PH7_VmExtractClass(pVm, CCLS_EXC, sizeof(CCLS_EXC) - 1, FALSE); - if(pClass == 0) { - return PH7_ABORT; - } - 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_int(aTmp[1], nErr); - apArg[0] = aTmp[0]; - apArg[1] = aTmp[1]; - pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1); - if(pCons) { - rc = PH7_VmCallClassMethod(pVm, pInst, pCons, 0, 2, apArg); - if(pInst->iRef < 1) { - pInst->iRef = 1; - } - 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]); - } - } - CharStampSite(pVm, pInst); - if(pInst->iRef < 1) { - pInst->iRef = 1; - } - PH7_MemObjRelease(pObj); - pObj->x.pOther = pInst; - MemObjSetType(pObj, MEMOBJ_OBJ); - rc = ph7_result_value(pCtx, pObj); - ph7_context_release_value(pCtx, pObj); - return rc == PH7_OK ? PH7_EXCEPTION : rc; -} static int CharExceptionConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_value *pResult = ph7_context_new_scalar(pCtx); sxi32 rc; @@ -177,12 +62,12 @@ static int CharOperand(ph7_context *pCtx, ph7_value *pArg, ph7_int64 *pOut) { sxu32 nByte; ph7_int64 iVal; if(pArg == 0) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Expected a char (0..255) or a single-byte string argument"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Expected a char (0..255) or a single-byte string argument"); } if(ph7_value_is_char(pArg)) { iVal = ph7_value_to_int64(pArg); if(iVal < 0 || iVal > 255) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Char argument is outside the 0..255 range"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Char argument is outside the 0..255 range"); } *pOut = iVal; return PH7_OK; @@ -190,13 +75,13 @@ static int CharOperand(ph7_context *pCtx, ph7_value *pArg, ph7_int64 *pOut) { if(ph7_value_is_string(pArg)) { nByte = SyBlobLength(&pArg->sBlob); if(nByte != 1) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Expected a string of exactly one byte"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Expected a string of exactly one byte"); } zData = (const char *)SyBlobData(&pArg->sBlob); *pOut = (ph7_int64)(unsigned char)zData[0]; return PH7_OK; } - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Expected a char (0..255) or a single-byte string argument"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Expected a char (0..255) or a single-byte string argument"); } /* Set a full-range char result; ph7_value_char() clamps to 0..255. */ static int CharResultChar(ph7_context *pCtx, ph7_int64 iVal) { @@ -242,7 +127,7 @@ static int PredHexDigit(ph7_int64 c) { return PredDigit(c) || PredHexLower(c) || static int CharClassify(ph7_context *pCtx, int nArg, ph7_value **apArg, CharPred xPred) { ph7_int64 c; if(nArg != 1) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Method expects exactly one argument"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Method expects exactly one argument"); } if(CharOperand(pCtx, apArg[0], &c) != PH7_OK) { return PH7_EXCEPTION; @@ -279,7 +164,7 @@ CLS_FN(CharIsAsciiHexDigitUpper, PredHexUpper) static int CharIsBetween(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_int64 c, zMin, zMax; if(nArg != 3) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "IsBetween expects exactly three arguments"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "IsBetween expects exactly three arguments"); } if(CharOperand(pCtx, apArg[0], &c) != PH7_OK || CharOperand(pCtx, apArg[1], &zMin) != PH7_OK || @@ -296,7 +181,7 @@ static int CharIsBetween(ph7_context *pCtx, int nArg, ph7_value **apArg) { static int CharCaseConvert(ph7_context *pCtx, int nArg, ph7_value **apArg, int bUpper) { ph7_int64 c; if(nArg != 1) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Method expects exactly one argument"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Method expects exactly one argument"); } if(CharOperand(pCtx, apArg[0], &c) != PH7_OK) { return PH7_EXCEPTION; @@ -317,7 +202,7 @@ static int CharToLower(ph7_context *pCtx, int nArg, ph7_value **apArg) { static int CharGetNumericValue(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_int64 c; if(nArg != 1) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "GetNumericValue expects exactly one argument"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "GetNumericValue expects exactly one argument"); } if(CharOperand(pCtx, apArg[0], &c) != PH7_OK) { return PH7_EXCEPTION; @@ -328,7 +213,7 @@ static int CharToString(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_int64 c; char zByte[2]; if(nArg != 1) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "ToString expects exactly one argument"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "ToString expects exactly one argument"); } if(CharOperand(pCtx, apArg[0], &c) != PH7_OK) { return PH7_EXCEPTION; @@ -341,14 +226,14 @@ static int CharParse(ph7_context *pCtx, int nArg, ph7_value **apArg) { const char *zData; sxu32 nByte; if(nArg != 1) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Parse expects exactly one argument"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Parse expects exactly one argument"); } if(apArg[0] == 0 || !ph7_value_is_string(apArg[0])) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Parse expects a single-byte string"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Parse expects a single-byte string"); } nByte = SyBlobLength(&apArg[0]->sBlob); if(nByte != 1) { - return CharThrow(pCtx, CHAR_ERROR_ARGUMENT, "Parse expects a single-byte string"); + return PH7_VmThrowNativeException(pCtx, CCLS_EXC, CHAR_ERROR_ARGUMENT, "Parse expects a single-byte string"); } zData = (const char *)SyBlobData(&apArg[0]->sBlob); return CharResultChar(pCtx, (int)(unsigned char)zData[0]); diff --git a/modules/math/math.c b/modules/math/math.c index e71f678..22ff807 100644 --- a/modules/math/math.c +++ b/modules/math/math.c @@ -53,127 +53,6 @@ static const char *MathErrorDescription(int nErr) { default: return "Unknown error code"; } } -/* Fetch an inherited (protected) attribute slot straight off the instance. - * PH7_ClassInstanceFetchAttr walks the attribute table without a scope check, - * so the base Exception fields are reachable from this module. */ -static ph7_value *MathInstField(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 fields with the first script frame - * of the active call stack. Native frames ([NATIVE], line 0) are skipped so - * catch(Exception $e) observes the place in the script that raised the error. */ -static void MathStampSite(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 = MathInstField(pInst, "file"); - if(pField) { - PH7_MemObjRelease(pField); - PH7_MemObjInit(pVm, pField); - (void)ph7_value_string(pField, pTrace->pFile->zString, (int)pTrace->pFile->nByte); - } - pField = MathInstField(pInst, "line"); - if(pField) { - (void)ph7_value_int64(pField, (ph7_int64)pTrace->nLine); - } - break; - } - SySetRelease(&sTrace); -} -/* Throw a real MathException object; temporary scalars are always released - * and the instance reference dropped on every error path. */ -static int MathThrow(ph7_context *pCtx, int nErr, const char *zMsg) { - ph7_vm *pVm = pCtx->pVm; - ph7_class *pClass; - ph7_class_instance *pInst; - ph7_class_method *pCons; - ph7_value *pObj, *apArg[2], *aTmp[2]; - sxi32 rc; - sxu32 n; - if(pVm->iPendingTransfer) { - return PH7_EXCEPTION; /* a handler exception takes precedence */ - } - pClass = PH7_VmExtractClass(pVm, MCLS_EXC, sizeof(MCLS_EXC) - 1, FALSE); - if(pClass == 0) { - return PH7_ABORT; - } - 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_int(aTmp[1], nErr); - for(n = 0 ; n < SX_ARRAYSIZE(apArg) ; ++n) { - apArg[n] = aTmp[n]; - } - pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1); - if(pCons) { - rc = PH7_VmCallClassMethod(pVm, pInst, pCons, 0, 2, apArg); - if(pInst->iRef < 1) { - pInst->iRef = 1; - } - 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]); - } - } - MathStampSite(pVm, pInst); - if(pInst->iRef < 1) { - pInst->iRef = 1; - } - PH7_MemObjRelease(pObj); - pObj->x.pOther = pInst; - MemObjSetType(pObj, MEMOBJ_OBJ); - rc = ph7_result_value(pCtx, pObj); - ph7_context_release_value(pCtx, pObj); - return rc == PH7_OK ? PH7_EXCEPTION : rc; -} /* ------------------------------------------------------------------ */ /* Method callbacks: MathException */ /* ------------------------------------------------------------------ */ @@ -206,7 +85,7 @@ static int MathOperand(ph7_context *pCtx, ph7_value *pArg, int *pIsInt, ph7_int64 *pInt, double *pReal) { if(pArg == 0 || (pArg->nType & MEMOBJ_NULL) || (!ph7_value_is_int(pArg) && !ph7_value_is_float(pArg))) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Expected an int or float argument"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Expected an int or float argument"); } *pIsInt = ph7_value_is_int(pArg) ? 1 : 0; if(*pIsInt) { @@ -225,7 +104,7 @@ static int MathNumber(ph7_context *pCtx, ph7_value *pArg, double *pOut) { } static int MathInteger(ph7_context *pCtx, ph7_value *pArg, ph7_int64 *pOut) { if(pArg == 0 || (pArg->nType & MEMOBJ_NULL) || !ph7_value_is_int(pArg)) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Expected an integer argument"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Expected an integer argument"); } *pOut = ph7_value_to_int64(pArg); return PH7_OK; @@ -238,7 +117,7 @@ static int MathUnaryFloat(ph7_context *pCtx, int nArg, ph7_value **apArg, double x; int rc; if(nArg < 1) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Expected one numeric argument"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Expected one numeric argument"); } rc = MathNumber(pCtx, apArg[0], &x); if(rc != PH7_OK) { @@ -251,7 +130,7 @@ static int MathBinaryFloat(ph7_context *pCtx, int nArg, ph7_value **apArg, double x, y; int rc; if(nArg < 2) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Expected two numeric arguments"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Expected two numeric arguments"); } rc = MathNumber(pCtx, apArg[0], &x); if(rc != PH7_OK) { @@ -305,7 +184,7 @@ static int MathAbs(ph7_context *pCtx, int nArg, ph7_value **apArg) { double x; int bIsInt, rc; if(nArg < 1) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Abs() expects a value"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Abs() expects a value"); } rc = MathOperand(pCtx, apArg[0], &bIsInt, &iVal, &x); if(rc != PH7_OK) { @@ -314,7 +193,7 @@ static int MathAbs(ph7_context *pCtx, int nArg, ph7_value **apArg) { if(bIsInt) { /* -SMALLEST_INT64 is undefined; check before negating. */ if(iVal == SMALLEST_INT64) { - return MathThrow(pCtx, MATH_ERROR_OVERFLOW, "Abs() overflows for the smallest integer"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_OVERFLOW, "Abs() overflows for the smallest integer"); } return ph7_result_int64(pCtx, iVal < 0 ? -iVal : iVal); } @@ -325,7 +204,7 @@ static int MathSign(ph7_context *pCtx, int nArg, ph7_value **apArg) { double x; int bIsInt, rc; if(nArg < 1) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Sign() expects a value"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Sign() expects a value"); } rc = MathOperand(pCtx, apArg[0], &bIsInt, &iVal, &x); if(rc != PH7_OK) { @@ -335,7 +214,7 @@ static int MathSign(ph7_context *pCtx, int nArg, ph7_value **apArg) { return ph7_result_int(pCtx, iVal > 0 ? 1 : (iVal < 0 ? -1 : 0)); } if(isnan(x)) { - return MathThrow(pCtx, MATH_ERROR_ARITHMETIC, "Sign() is undefined for NaN"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARITHMETIC, "Sign() is undefined for NaN"); } return ph7_result_int(pCtx, x > 0.0 ? 1 : (x < 0.0 ? -1 : 0)); } @@ -344,7 +223,7 @@ static int MathLog(ph7_context *pCtx, int nArg, ph7_value **apArg) { double a, b; int bIsInt, bHasBase, rc; if(nArg < 1) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Log() expects a value"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Log() expects a value"); } rc = MathOperand(pCtx, apArg[0], &bIsInt, &iVal, &a); if(rc != PH7_OK) { @@ -380,7 +259,7 @@ static int MathExtreme(ph7_context *pCtx, int nArg, ph7_value **apArg, int bWant double a, b; int ba, bb, rc; if(nArg != 2) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, bWantMax ? "Max() expects exactly two arguments" : "Min() expects exactly two arguments"); } rc = MathOperand(pCtx, apArg[0], &ba, &ia, &a); @@ -420,7 +299,7 @@ static int MathClamp(ph7_context *pCtx, int nArg, ph7_value **apArg) { double v, dMin, dMax; int bAllInt = 1, bIsInt, rc; if(nArg != 3) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Clamp() expects exactly three arguments"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Clamp() expects exactly three arguments"); } rc = MathOperand(pCtx, apArg[0], &bIsInt, &iv, &v); if(rc != PH7_OK) return rc; @@ -436,7 +315,7 @@ static int MathClamp(ph7_context *pCtx, int nArg, ph7_value **apArg) { * bounds a NaN makes '>' false, which is the .NET Math.Clamp(double) * behavior: the comparisons below then simply fall through to value. */ if(bAllInt ? (iMin > iMax) : (dMin > dMax)) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Clamp() requires min <= max"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Clamp() requires min <= max"); } if(bAllInt) { if(iv < iMin) return ph7_result_int64(pCtx, iMin); @@ -477,7 +356,7 @@ static int MathMagnitude(ph7_context *pCtx, int nArg, ph7_value **apArg, int bWa double x, y, ax, ay; int rc; if(nArg != 2) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, bWantMax ? "MaxMagnitude() expects exactly two arguments" : "MinMagnitude() expects exactly two arguments"); } @@ -503,7 +382,7 @@ static int MathILogB(ph7_context *pCtx, int nArg, ph7_value **apArg) { double x; int rc; if(nArg < 1) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "ILogB() expects a value"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "ILogB() expects a value"); } rc = MathNumber(pCtx, apArg[0], &x); if(rc != PH7_OK) { @@ -518,14 +397,14 @@ static int MathScaleB(ph7_context *pCtx, int nArg, ph7_value **apArg) { double x; int rc; if(nArg < 2) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "ScaleB() expects a value and an exponent"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "ScaleB() expects a value and an exponent"); } rc = MathNumber(pCtx, apArg[0], &x); if(rc != PH7_OK) return rc; rc = MathInteger(pCtx, apArg[1], &n); if(rc != PH7_OK) return rc; if(n < (-2147483647 - 1) || n > 2147483647) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT_OUT_OF_RANGE, + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT_OUT_OF_RANGE, "ScaleB() exponent is outside the int32 range"); } return ph7_result_double(pCtx, scalbn(x, (int)n)); @@ -534,7 +413,7 @@ static int MathFusedMultiplyAdd(ph7_context *pCtx, int nArg, ph7_value **apArg) double x, y, z; int rc; if(nArg < 3) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "FusedMultiplyAdd() expects three values"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "FusedMultiplyAdd() expects three values"); } rc = MathNumber(pCtx, apArg[0], &x); if(rc != PH7_OK) return rc; @@ -551,18 +430,18 @@ static int MathFloorDiv(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_int64 a, b, q, r; int rc; if(nArg < 2) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "FloorDiv() expects two integers"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "FloorDiv() expects two integers"); } rc = MathInteger(pCtx, apArg[0], &a); if(rc != PH7_OK) return rc; rc = MathInteger(pCtx, apArg[1], &b); if(rc != PH7_OK) return rc; if(b == 0) { - return MathThrow(pCtx, MATH_ERROR_DIVIDE_BY_ZERO, "Division by zero"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_DIVIDE_BY_ZERO, "Division by zero"); } if(b == -1) { if(a == SMALLEST_INT64) { - return MathThrow(pCtx, MATH_ERROR_OVERFLOW, "FloorDiv() overflows for the smallest integer"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_OVERFLOW, "FloorDiv() overflows for the smallest integer"); } return ph7_result_int64(pCtx, -a); } @@ -577,14 +456,14 @@ static int MathFloorMod(ph7_context *pCtx, int nArg, ph7_value **apArg) { ph7_int64 a, b, r; int rc; if(nArg < 2) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "FloorMod() expects two integers"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "FloorMod() expects two integers"); } rc = MathInteger(pCtx, apArg[0], &a); if(rc != PH7_OK) return rc; rc = MathInteger(pCtx, apArg[1], &b); if(rc != PH7_OK) return rc; if(b == 0) { - return MathThrow(pCtx, MATH_ERROR_DIVIDE_BY_ZERO, "Division by zero"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_DIVIDE_BY_ZERO, "Division by zero"); } if(b == -1) { return ph7_result_int64(pCtx, 0); @@ -635,7 +514,7 @@ static int MathRound(ph7_context *pCtx, int nArg, ph7_value **apArg) { double value, scaled, result, scale, intPart; int bIsInt, bNegative, rc; if(nArg < 1) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Round() expects a value"); + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Round() expects a value"); } rc = MathOperand(pCtx, apArg[0], &bIsInt, &iDummy, &value); if(rc != PH7_OK) return rc; @@ -644,11 +523,11 @@ static int MathRound(ph7_context *pCtx, int nArg, ph7_value **apArg) { rc = MathInteger(pCtx, nArg > 2 ? apArg[2] : 0, &iMode); if(rc != PH7_OK) return rc; if(iDigits < 0 || iDigits > 15) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT_OUT_OF_RANGE, + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT_OUT_OF_RANGE, "Round() digits must be between 0 and 15"); } if(iMode < 0 || iMode > 4) { - return MathThrow(pCtx, MATH_ERROR_ARGUMENT, + return PH7_VmThrowNativeException(pCtx, MCLS_EXC, MATH_ERROR_ARGUMENT, "Round() mode is not a known MidpointRounding value"); } if(isnan(value) || isinf(value) || fabs(value) >= MATH_TWO_POW_52) { diff --git a/modules/system/system.c b/modules/system/system.c new file mode 100644 index 0000000..16532b9 --- /dev/null +++ b/modules/system/system.c @@ -0,0 +1,830 @@ +/** + * @PROJECT AerScript Interpreter + * @COPYRIGHT See COPYING in the top level directory + * @FILE modules/system/system.c + * @DESCRIPTION Static System class module for AerScript Interpreter + * @DEVELOPERS Rafal Kupiec + */ +#include +#include +#include +#ifdef __WINNT__ +#include +#include +#include +#include +#include +#else +#include +#include +#include +#include +#include +extern char **environ; +#endif +#include "system.h" + +#define SCLS_SYSTEM "System" +#define SCLS_EXC "SystemException" + +#ifdef __WINNT__ +#define SYS_NEW_LINE "\r\n" +#else +#define SYS_NEW_LINE "\n" +#endif + +/* ------------------------------------------------------------------ */ +/* Platform helpers */ +/* ------------------------------------------------------------------ */ +/* Throw the two SystemException flavours used all over this module. Both + * helpers return the exact status of the core-owned throw routine. */ +static int SystemArgError(ph7_context *pCtx, const char *zMsg) { + return PH7_VmThrowNativeException(pCtx, SCLS_EXC, SYS_ERROR_ARGUMENT, zMsg); +} +static int SystemIoError(ph7_context *pCtx, const char *zMsg) { + return PH7_VmThrowNativeException(pCtx, SCLS_EXC, SYS_ERROR_IO, zMsg); +} + +/* Validate a variable name shared by GetEnvironmentVariable() and + * SetEnvironmentVariable(): non-empty, no '=' and no embedded NUL. */ +static int SystemEnvName(ph7_context *pCtx, ph7_value *pArg, const char **pzName) { + const char *zData; + int nByte = 0; + if(pArg == 0 || (pArg->nType & MEMOBJ_NULL) || !ph7_value_is_string(pArg)) { + return SystemArgError(pCtx, "Environment variable name must be a string"); + } + zData = ph7_value_to_string(pArg, &nByte); + if(zData == 0 || nByte < 1 || memchr(zData, '=', (size_t)nByte) != 0 || + memchr(zData, '\0', (size_t)nByte) != 0) { + return SystemArgError(pCtx, "Invalid environment variable name"); + } + *pzName = zData; + return PH7_OK; +} + +/* Compilation-target architecture of the running process: 64-bit spellings + * are checked before their 32-bit counterparts, as required by the contract. */ +static const char *SystemProcessArch(void) { +#if defined(__x86_64__) || defined(__amd64__) || defined(_M_X64) + return "x64"; +#elif defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64) + return "arm64"; +#elif defined(__i386__) || defined(_M_IX86) + return "x86"; +#elif defined(__arm__) || defined(_M_ARM) + return "arm"; +#else + return "Unknown"; +#endif +} +#ifndef __WINNT__ +/* Map uname(2)'s machine field onto the four contract spellings. */ +static const char *SystemArchFromMachine(const char *zMachine) { + if(zMachine == 0) { + return "Unknown"; + } + if(strcmp(zMachine, "x86_64") == 0 || strcmp(zMachine, "amd64") == 0 || + strcmp(zMachine, "AMD64") == 0) { + return "x64"; + } + if(strcmp(zMachine, "aarch64") == 0 || strcmp(zMachine, "arm64") == 0) { + return "arm64"; + } + if(strcmp(zMachine, "i386") == 0 || strcmp(zMachine, "i486") == 0 || + strcmp(zMachine, "i586") == 0 || strcmp(zMachine, "i686") == 0 || + strcmp(zMachine, "x86") == 0) { + return "x86"; + } + if(strncmp(zMachine, "arm", 3) == 0) { + return "arm"; + } + return "Unknown"; +} +#endif +/* Architecture of the host, not of the compiled interpreter. */ +static const char *SystemOSArch(void) { +#ifdef __WINNT__ + SYSTEM_INFO sInfo; + GetNativeSystemInfo(&sInfo); + switch(sInfo.wProcessorArchitecture) { + case PROCESSOR_ARCHITECTURE_AMD64: return "x64"; +#ifdef PROCESSOR_ARCHITECTURE_ARM64 + case PROCESSOR_ARCHITECTURE_ARM64: return "arm64"; +#endif + case PROCESSOR_ARCHITECTURE_INTEL: return "x86"; + case PROCESSOR_ARCHITECTURE_ARM: return "arm"; + default: return "Unknown"; + } +#else + struct utsname sInfo; + if(uname(&sInfo) != 0) { + return "Unknown"; + } + return SystemArchFromMachine(sInfo.machine); +#endif +} +static int SystemProcessorCount(void) { + sxu64 nCount = 0; +#ifdef __WINNT__ +#ifdef ALL_PROCESSOR_GROUPS + nCount = (sxu64)GetActiveProcessorCount(ALL_PROCESSOR_GROUPS); +#else + { + SYSTEM_INFO sInfo; + GetSystemInfo(&sInfo); + nCount = (sxu64)sInfo.dwNumberOfProcessors; + } +#endif +#else + { + /* sysconf() signals failure with -1; casting that to sxu64 would make + * the final > 0 test succeed and yield a negative processor count. */ + long nRaw = sysconf(_SC_NPROCESSORS_ONLN); + nCount = nRaw > 0 ? (sxu64)nRaw : 0; + } +#endif + return nCount > 0 ? (int)nCount : 1; +} +static ph7_int64 SystemTickCount(void) { +#ifdef __WINNT__ + return (ph7_int64)GetTickCount64(); +#else + struct timespec sNow; + if(clock_gettime(CLOCK_MONOTONIC, &sNow) != 0) { + return 0; + } + return (ph7_int64)sNow.tv_sec * 1000 + (ph7_int64)(sNow.tv_nsec / 1000000L); +#endif +} +/* Sleep in milliseconds with EINTR resumption; iMs is always >= 0 here. */ +static void SystemSleepMs(ph7_int64 iMs) { +#ifdef __WINNT__ + Sleep((DWORD)iMs); +#else + struct timespec sReq, sRem; + sReq.tv_sec = (time_t)(iMs / 1000); + sReq.tv_nsec = (long)((iMs % 1000) * 1000000); + while(nanosleep(&sReq, &sRem) != 0) { + if(errno == EINTR) { + sReq = sRem; + continue; + } + break; + } +#endif +} +#ifdef __WINNT__ +/* UTF-16 <-> UTF-8 conversion. Buffers are heap allocated and owned by the + * caller; the VFS does not expose wide-string environment helpers. */ +static char *SystemUtf8FromWide(const WCHAR *zWide, int nWide) { + char *zOut; + int nByte; + if(nWide < 0) { + nWide = (int)wcslen(zWide); + } + if(nWide == 0) { + /* An empty environment value is a valid value, not a failure. */ + char *zEmpty = (char *)malloc(1); + if(zEmpty) { + zEmpty[0] = '\0'; + } + return zEmpty; + } + nByte = WideCharToMultiByte(CP_UTF8, 0, zWide, nWide, 0, 0, 0, 0); + if(nByte < 1) { + return 0; + } + zOut = (char *)malloc((size_t)nByte + 1); + if(zOut == 0) { + return 0; + } + if(WideCharToMultiByte(CP_UTF8, 0, zWide, nWide, zOut, nByte, 0, 0) < 1) { + free(zOut); + return 0; + } + zOut[nByte] = '\0'; + return zOut; +} +static WCHAR *SystemWideFromUtf8(const char *zUtf8) { + WCHAR *zOut; + int nByte, nWide; + if(zUtf8 == 0) { + return 0; + } + nByte = (int)strlen(zUtf8); + if(nByte == 0) { + /* Keep an empty value distinct from an absent variable: the caller + * passes this NUL-only buffer to SetEnvironmentVariableW(). */ + zOut = (WCHAR *)malloc(sizeof(WCHAR)); + if(zOut) { + zOut[0] = L'\0'; + } + return zOut; + } + nWide = MultiByteToWideChar(CP_UTF8, 0, zUtf8, nByte, 0, 0); + if(nWide < 1) { + return 0; + } + zOut = (WCHAR *)malloc(((size_t)nWide + 1) * sizeof(WCHAR)); + if(zOut == 0) { + return 0; + } + if(MultiByteToWideChar(CP_UTF8, 0, zUtf8, nByte, zOut, nWide) < 1) { + free(zOut); + return 0; + } + zOut[nWide] = L'\0'; + return zOut; +} +static int SystemIsElevated(void) { + HANDLE hToken = 0; + TOKEN_ELEVATION sElevation; + DWORD nSize = sizeof(sElevation); + if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { + return 0; + } + if(!GetTokenInformation(hToken, TokenElevation, &sElevation, sizeof(sElevation), &nSize)) { + CloseHandle(hToken); + return 0; + } + CloseHandle(hToken); + return sElevation.TokenIsElevated ? 1 : 0; +} +#endif + +/* ------------------------------------------------------------------ */ +/* Methods available under every SAPI */ +/* ------------------------------------------------------------------ */ +static int System_GetEnvironmentVariable(ph7_context *pCtx, int nArg, ph7_value **apArg) { +#ifndef __WINNT__ + const ph7_vfs *pVfs; +#endif + const char *zName; + int rc; + rc = SystemEnvName(pCtx, nArg > 0 ? apArg[0] : 0, &zName); + if(rc != PH7_OK) { + return rc; + } + /* Absent variables (and a missing VFS) keep the NULL fallback result. */ + (void)ph7_result_null(pCtx); +#ifdef __WINNT__ + { + /* WinVfs_Getenv() maps GetEnvironmentVariableA() == 0 to "not found", + * which is also returned for a variable set to "". Query the wide API + * directly: only ERROR_ENVVAR_NOT_FOUND yields NULL, "" stays "". */ + WCHAR *zWideName = SystemWideFromUtf8(zName); + DWORD nSize, nErr; + if(zWideName == 0) { + return SystemIoError(pCtx, "Unable to convert the variable name"); + } + nSize = GetEnvironmentVariableW(zWideName, 0, 0); + nErr = GetLastError(); + if(nSize == 0) { + free(zWideName); + if(nErr == ERROR_ENVVAR_NOT_FOUND) { + return PH7_OK; + } + return SystemIoError(pCtx, "Unable to read the environment variable"); + } + { + WCHAR *zBuf = (WCHAR *)malloc(((size_t)nSize + 1) * sizeof(WCHAR)); + if(zBuf == 0) { + free(zWideName); + return PH7_ABORT; + } + (void)GetEnvironmentVariableW(zWideName, zBuf, nSize); + free(zWideName); + { + char *zUtf = SystemUtf8FromWide(zBuf, -1); + free(zBuf); + if(zUtf == 0) { + return SystemIoError(pCtx, "Unable to convert the environment variable value"); + } + rc = ph7_result_string(pCtx, zUtf, -1); + free(zUtf); + return rc; + } + } + } +#else + pVfs = pCtx->pVm->pEngine->pVfs; + if(pVfs == 0 || pVfs->xGetenv == 0) { + return PH7_OK; + } + (void)pVfs->xGetenv(zName, pCtx); + return PH7_OK; +#endif +} +static int System_GetOSPlatform(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); +#if defined(__WINNT__) + return ph7_result_string(pCtx, "Windows", sizeof("Windows") - 1); +#elif defined(__APPLE__) + return ph7_result_string(pCtx, "macOS", sizeof("macOS") - 1); +#elif defined(__FreeBSD__) + return ph7_result_string(pCtx, "FreeBSD", sizeof("FreeBSD") - 1); +#elif defined(__OpenBSD__) + return ph7_result_string(pCtx, "OpenBSD", sizeof("OpenBSD") - 1); +#elif defined(__NetBSD__) + return ph7_result_string(pCtx, "NetBSD", sizeof("NetBSD") - 1); +#elif defined(__linux__) + return ph7_result_string(pCtx, "Linux", sizeof("Linux") - 1); +#else + return ph7_result_string(pCtx, "Unknown", sizeof("Unknown") - 1); +#endif +} +static int System_GetOSArchitecture(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return ph7_result_string(pCtx, SystemOSArch(), -1); +} +static int System_GetProcessArchitecture(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return ph7_result_string(pCtx, SystemProcessArch(), -1); +} +static int System_GetProcessorCount(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return ph7_result_int(pCtx, SystemProcessorCount()); +} +static int System_GetTickCount(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return ph7_result_int64(pCtx, SystemTickCount()); +} +/* nWhich: 0 = current, 1 = peak, 2 = configured limit. */ +static int SystemMemory(ph7_context *pCtx, int nWhich) { + const SyMemHeap *pHeap = pCtx->pVm->sAllocator.pHeap; + ph7_int64 iValue = 0; + if(pHeap != 0) { + if(nWhich == 0) { + iValue = (ph7_int64)pHeap->nSize; + } else if(nWhich == 1) { + iValue = (ph7_int64)pHeap->nPeak; + } else { + iValue = (ph7_int64)pHeap->nLimit; + } + } + return ph7_result_int64(pCtx, iValue); +} +static int System_GetMemoryUsage(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return SystemMemory(pCtx, 0); +} +static int System_GetPeakMemoryUsage(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return SystemMemory(pCtx, 1); +} +static int System_GetMemoryLimit(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); + return SystemMemory(pCtx, 2); +} +static int System_Sleep(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_int64 iMs; + if(nArg < 1 || apArg[0] == 0 || (apArg[0]->nType & MEMOBJ_NULL) || + !ph7_value_is_int(apArg[0])) { + return SystemArgError(pCtx, "Sleep() expects an integer number of milliseconds"); + } + iMs = ph7_value_to_int64(apArg[0]); + if(iMs < 0) { + return SystemArgError(pCtx, "Sleep() rejects a negative delay"); + } + if(iMs > 0) { + SystemSleepMs(iMs); + } + return PH7_OK; +} +static int System_Exit(ph7_context *pCtx, int nArg, ph7_value **apArg) { + sxi32 iStatus = 0; + if(nArg > 0) { + if(apArg[0] == 0 || (apArg[0]->nType & MEMOBJ_NULL) || + !ph7_value_is_int(apArg[0])) { + return SystemArgError(pCtx, "Exit() expects an integer status code"); + } + iStatus = ph7_value_to_int(apArg[0]); + } + /* Under a future FastCGI SAPI this must end the current request, not the + * process; the VM's existing PH7_ABORT path owns shutdown handlers and + * destructors in both cases. */ + pCtx->pVm->iExitStatus = iStatus; + return PH7_ABORT; +} + +/* ------------------------------------------------------------------ */ +/* Methods registered only under the "cli" SAPI */ +/* ------------------------------------------------------------------ */ +static int System_GetEnvironmentVariables(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pArray; + SXUNUSED(nArg); + SXUNUSED(apArg); + pArray = ph7_context_new_array(pCtx); + if(pArray == 0) { + return PH7_ABORT; + } +#ifdef __WINNT__ + { + LPWCH pEnv = GetEnvironmentStringsW(); + LPWCH pCur; + if(pEnv == 0) { + return SystemIoError(pCtx, "Unable to read the environment block"); + } + for(pCur = pEnv ; *pCur != 0 ; ) { + WCHAR *zEq = wcschr(pCur, L'='); + if(zEq != 0 && zEq != pCur) { + ph7_value *pKey = ph7_context_new_scalar(pCtx); + ph7_value *pVal = ph7_context_new_scalar(pCtx); + char *zName = SystemUtf8FromWide(pCur, (int)(zEq - pCur)); + char *zValue = SystemUtf8FromWide(zEq + 1, -1); + if(pKey == 0 || pVal == 0 || zName == 0 || zValue == 0) { + free(zName); + free(zValue); + FreeEnvironmentStringsW(pEnv); + return PH7_ABORT; + } + (void)ph7_value_string(pKey, zName, -1); + (void)ph7_value_string(pVal, zValue, -1); + if(ph7_array_add_elem(pArray, pKey, pVal) != PH7_OK) { + free(zName); + free(zValue); + FreeEnvironmentStringsW(pEnv); + return PH7_ABORT; + } + free(zName); + free(zValue); + } + pCur += wcslen(pCur) + 1; + } + FreeEnvironmentStringsW(pEnv); + } +#else + { + char **pEnv; + for(pEnv = environ ; pEnv != 0 && *pEnv != 0 ; ++pEnv) { + const char *zEntry = *pEnv; + const char *zEq = strchr(zEntry, '='); + ph7_value *pKey, *pVal; + if(zEq == 0 || zEq == zEntry) { + continue; + } + pKey = ph7_context_new_scalar(pCtx); + pVal = ph7_context_new_scalar(pCtx); + if(pKey == 0 || pVal == 0) { + return PH7_ABORT; + } + (void)ph7_value_string(pKey, zEntry, (int)(zEq - zEntry)); + (void)ph7_value_string(pVal, zEq + 1, -1); + if(ph7_array_add_elem(pArray, pKey, pVal) != PH7_OK) { + return PH7_ABORT; + } + } + } +#endif + /* Stamp the primitive element type: the declared string[] result must + * match exactly, else VmCheckReturn() rejects the array on return. */ + pArray->nType = MEMOBJ_STRING | MEMOBJ_HASHMAP; + return ph7_result_value(pCtx, pArray); +} +static int System_SetEnvironmentVariable(ph7_context *pCtx, int nArg, ph7_value **apArg) { +#ifndef __WINNT__ + const ph7_vfs *pVfs; +#endif + const char *zName; + /* A NULL (or missing) value removes the variable. A NULL literal passed + * through a MIXED formal arrives as MEMOBJ_MIXED | MEMOBJ_VOID. */ + int bRemove = (nArg < 2 || apArg[1] == 0 || + (apArg[1]->nType & (MEMOBJ_NULL | MEMOBJ_VOID))) ? 1 : 0; + int rc; + rc = SystemEnvName(pCtx, nArg > 0 ? apArg[0] : 0, &zName); + if(rc != PH7_OK) { + return rc; + } + if(!bRemove && !ph7_value_is_string(apArg[1])) { + return SystemArgError(pCtx, "Environment variable value must be a string or NULL"); + } +#ifdef __WINNT__ + { + /* Keep both Windows paths wide: the VFS xSetenv() uses the ANSI API + * and would store raw UTF-8 bytes that the W-based enumeration then + * decodes as UTF-16, breaking non-ASCII round trips. */ + WCHAR *zWideName = SystemWideFromUtf8(zName); + WCHAR *zWideValue = 0; + BOOL bOk; + if(zWideName == 0) { + return SystemIoError(pCtx, "Unable to convert the variable name"); + } + if(!bRemove) { + zWideValue = SystemWideFromUtf8(ph7_value_to_string(apArg[1], 0)); + if(zWideValue == 0) { + free(zWideName); + return SystemIoError(pCtx, "Unable to convert the environment variable value"); + } + } + /* A NULL value pointer removes the variable. */ + bOk = SetEnvironmentVariableW(zWideName, zWideValue); + free(zWideValue); + free(zWideName); + if(!bOk) { + return SystemIoError(pCtx, bRemove ? + "Unable to remove the environment variable" : + "Unable to set the environment variable"); + } + return PH7_OK; + } +#else + if(bRemove) { + if(unsetenv(zName) != 0) { + return SystemIoError(pCtx, "Unable to remove the environment variable"); + } + return PH7_OK; + } + pVfs = pCtx->pVm->pEngine->pVfs; + if(pVfs == 0 || pVfs->xSetenv == 0) { + return SystemIoError(pCtx, "Environment writes are not available in the underlying VFS"); + } + if(pVfs->xSetenv(zName, ph7_value_to_string(apArg[1], 0)) != PH7_OK) { + return SystemIoError(pCtx, "Unable to set the environment variable"); + } + return PH7_OK; +#endif +} +static int System_GetProcessId(ph7_context *pCtx, int nArg, ph7_value **apArg) { + const ph7_vfs *pVfs; + SXUNUSED(nArg); + SXUNUSED(apArg); + pVfs = pCtx->pVm->pEngine->pVfs; + return ph7_result_int64(pCtx, pVfs != 0 && pVfs->xProcessId != 0 ? + (ph7_int64)pVfs->xProcessId() : 0); +} +static int System_GetUserName(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); +#ifdef __WINNT__ + { + WCHAR zBuf[256]; + DWORD nSize = (DWORD)SX_ARRAYSIZE(zBuf); + char *zUtf; + int rc; + if(!GetUserNameW(zBuf, &nSize)) { + return SystemIoError(pCtx, "Unable to determine the current user name"); + } + zUtf = SystemUtf8FromWide(zBuf, (int)nSize - 1); + if(zUtf == 0) { + return SystemIoError(pCtx, "Unable to convert the current user name"); + } + rc = ph7_result_string(pCtx, zUtf, -1); + free(zUtf); + return rc; + } +#else + { + /* The VFS xUsername() helper uses the real UID; the contract asks for + * the effective user, so query getpwuid(geteuid()) directly. */ + struct passwd *pPwd = getpwuid(geteuid()); + if(pPwd == 0 || pPwd->pw_name == 0) { + return SystemIoError(pCtx, "Unable to determine the current user name"); + } + return ph7_result_string(pCtx, pPwd->pw_name, -1); + } +#endif +} +static int System_IsPrivilegedProcess(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); +#ifdef __WINNT__ + return ph7_result_bool(pCtx, SystemIsElevated()); +#else + return ph7_result_bool(pCtx, geteuid() == 0 ? 1 : 0); +#endif +} +static int System_GetMachineName(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); +#ifdef __WINNT__ + { + WCHAR zBuf[256]; + DWORD nSize = (DWORD)SX_ARRAYSIZE(zBuf); + char *zUtf; + int rc; + if(!GetComputerNameExW(ComputerNameDnsHostname, zBuf, &nSize)) { + return SystemIoError(pCtx, "Unable to determine the machine name"); + } + zUtf = SystemUtf8FromWide(zBuf, (int)nSize); + if(zUtf == 0) { + return SystemIoError(pCtx, "Unable to convert the machine name"); + } + rc = ph7_result_string(pCtx, zUtf, -1); + free(zUtf); + return rc; + } +#else + { + char zBuf[256]; + if(gethostname(zBuf, sizeof(zBuf) - 1) != 0) { + return SystemIoError(pCtx, "Unable to determine the machine name"); + } + zBuf[sizeof(zBuf) - 1] = '\0'; + return ph7_result_string(pCtx, zBuf, -1); + } +#endif +} +static int System_GetOSVersion(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(nArg); + SXUNUSED(apArg); +#ifdef __WINNT__ + { + typedef LONG (WINAPI *RtlGetVersionFunc)(PRTL_OSVERSIONINFOW); + HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll"); + RtlGetVersionFunc xGetVersion; + RTL_OSVERSIONINFOW sInfo; + char zBuf[64]; + if(hNtdll == 0) { + return SystemIoError(pCtx, "Unable to query the operating system version"); + } + /* RtlGetVersion() bypasses the compatibility layer's fake version. */ + xGetVersion = (RtlGetVersionFunc)GetProcAddress(hNtdll, "RtlGetVersion"); + if(xGetVersion == 0) { + return SystemIoError(pCtx, "Unable to query the operating system version"); + } + SyZero(&sInfo, sizeof(sInfo)); + sInfo.dwOSVersionInfoSize = sizeof(sInfo); + if(xGetVersion(&sInfo) != 0) { + return SystemIoError(pCtx, "Unable to query the operating system version"); + } + (void)snprintf(zBuf, sizeof(zBuf), "%lu.%lu.%lu", + (unsigned long)sInfo.dwMajorVersion, (unsigned long)sInfo.dwMinorVersion, + (unsigned long)sInfo.dwBuildNumber); + return ph7_result_string(pCtx, zBuf, -1); + } +#else + { + struct utsname sInfo; + if(uname(&sInfo) != 0) { + return SystemIoError(pCtx, "Unable to query the operating system version"); + } + return ph7_result_string(pCtx, sInfo.release, -1); + } +#endif +} + +/* ------------------------------------------------------------------ */ +/* Class registration */ +/* ------------------------------------------------------------------ */ +static int SystemConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + SXUNUSED(pCtx); + SXUNUSED(nArg); + SXUNUSED(apArg); + return PH7_ABORT; /* final class: no public construction */ +} +static int SystemExceptionConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) { + ph7_value *pResult = ph7_context_new_scalar(pCtx); + sxi32 rc; + SXUNUSED(nArg); + if(pResult == 0) { + return PH7_ABORT; + } + /* apArg[1] is filled by the VM from the registered default snapshot. */ + rc = ph7_context_parent(pCtx, "__construct", 2, apArg, pResult); + return rc; +} +static sxi32 SystemRegisterClasses(ph7_vm *pVm) { +#define STY(T) { PH7_TYPE_##T, 0, 0 } +#define SYSC(N) { N, 0, PH7_MEMBER_PUBLIC, 0, 0 } +#define SYSM(NAME,RET,PARAMS,NPARAM,FUNC) \ + { NAME, STY(RET), PARAMS, NPARAM, FUNC, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC } + static ph7_constant_def aConst[] = { + SYSC("ERROR_NONE"), SYSC("ERROR_ARGUMENT"), SYSC("ERROR_IO"), SYSC("NEW_LINE") + }; + static const int aConstValue[] = { SYS_ERROR_NONE, SYS_ERROR_ARGUMENT, SYS_ERROR_IO }; + static ph7_param_def aExcCtor[] = { + { "message", STY(STRING), 0, 0, 0, 0 }, + { "code", STY(INT), 0, 0, 0, 0 } + }; + static const ph7_param_def aNameParam[] = { { "name", STY(STRING), 0, 0, 0, 0 } }; + /* MIXED, not STRING: a STRING formal casts NULL to "" before the callback, + * but NULL is the "remove variable" sentinel here. */ + static const ph7_param_def aSetParam[] = { + { "name", STY(STRING), 0, 0, 0, 0 }, + { "value", STY(MIXED), 0, 0, 0, 0 } + }; + static const ph7_param_def aIntParam[] = { { "milliseconds", STY(INT), 0, 0, 0, 0 } }; + /* MIXED so a wrong-typed status reaches System_Exit() and raises + * SystemException(ERROR_ARGUMENT) instead of a VM overload error. */ + static ph7_param_def aExitParam[] = { { "code", STY(MIXED), 0, 0, 0, 0 } }; + static const ph7_method_def aExcMethod[] = { + { "__construct", STY(VOID), aExcCtor, 2, SystemExceptionConstruct, 0, 0 } + }; + static const ph7_method_def aMethodCommon[] = { + { "__construct", STY(VOID), 0, 0, SystemConstruct, 0, PH7_MEMBER_PRIVATE }, + /* MIXED, not STRING: a STRING return would cast the NULL sentinel for + * an absent variable into an empty string (VmCheckReturn() cast). */ + SYSM("GetEnvironmentVariable", MIXED, aNameParam, 1, System_GetEnvironmentVariable), + SYSM("GetOSPlatform", STRING, 0, 0, System_GetOSPlatform), + SYSM("GetOSArchitecture", STRING, 0, 0, System_GetOSArchitecture), + SYSM("GetProcessArchitecture", STRING, 0, 0, System_GetProcessArchitecture), + SYSM("GetProcessorCount", INT, 0, 0, System_GetProcessorCount), + SYSM("GetTickCount", INT, 0, 0, System_GetTickCount), + SYSM("GetMemoryUsage", INT, 0, 0, System_GetMemoryUsage), + SYSM("GetPeakMemoryUsage", INT, 0, 0, System_GetPeakMemoryUsage), + SYSM("GetMemoryLimit", INT, 0, 0, System_GetMemoryLimit), + SYSM("Sleep", VOID, aIntParam, 1, System_Sleep), + SYSM("Exit", VOID, aExitParam, 1, System_Exit) + }; + static const ph7_method_def aMethodCli[] = { + { "GetEnvironmentVariables", { PH7_TYPE_STRING, 0, 1 }, 0, 0, + System_GetEnvironmentVariables, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC }, + SYSM("SetEnvironmentVariable", VOID, aSetParam, 2, System_SetEnvironmentVariable), + SYSM("GetProcessId", INT, 0, 0, System_GetProcessId), + SYSM("GetUserName", STRING, 0, 0, System_GetUserName), + SYSM("IsPrivilegedProcess", BOOL, 0, 0, System_IsPrivilegedProcess), + SYSM("GetMachineName", STRING, 0, 0, System_GetMachineName), + SYSM("GetOSVersion", STRING, 0, 0, System_GetOSVersion) + }; + static const char *const aExcBase[] = { "Exception" }; + ph7_method_def aMethod[SX_ARRAYSIZE(aMethodCommon) + SX_ARRAYSIZE(aMethodCli)]; + ph7_class_def sExc = { + sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, SCLS_EXC, + 0, 0, 0, 0, aExcMethod, SX_ARRAYSIZE(aExcMethod), 0, + aExcBase, 1, 0, 0, 0, 0 + }; + ph7_class_def sSystem = { + sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, SCLS_SYSTEM, + 0, 0, aConst, SX_ARRAYSIZE(aConst), aMethod, 0, + PH7_DECL_FINAL | PH7_DECL_VIRTUAL, 0, 0, 0, 0, 0, 0 + }; + ph7_value *apConst[SX_ARRAYSIZE(aConst)]; + ph7_value *apDefault[2]; + sxu32 n; + sxi32 rc = PH7_OK; + SyZero(apConst, sizeof(apConst)); + SyZero(apDefault, sizeof(apDefault)); + /* Constant and default snapshots; ph7_create_class() deep-copies them. */ + for(n = 0 ; n < SX_ARRAYSIZE(apConst) ; ++n) { + apConst[n] = ph7_new_scalar(pVm); + if(apConst[n] == 0) { + rc = PH7_NOMEM; + goto Cleanup; + } + if(n < SX_ARRAYSIZE(aConstValue)) { + ph7_value_int(apConst[n], aConstValue[n]); + } else { + (void)ph7_value_string(apConst[n], SYS_NEW_LINE, -1); + } + aConst[n].pValue = apConst[n]; + } + /* SystemException("message") gets ERROR_NONE from this snapshot. */ + apDefault[0] = ph7_new_scalar(pVm); + if(apDefault[0] == 0) { + rc = PH7_NOMEM; + goto Cleanup; + } + ph7_value_int(apDefault[0], SYS_ERROR_NONE); + aExcCtor[1].pDefault = apDefault[0]; + /* Exit()'s optional status code defaults to zero. */ + apDefault[1] = ph7_new_scalar(pVm); + if(apDefault[1] == 0) { + rc = PH7_NOMEM; + goto Cleanup; + } + ph7_value_int(apDefault[1], 0); + aExitParam[0].pDefault = apDefault[1]; + /* Per-SAPI method table: only the CLI SAPI sees the process/environment + * helpers; every other SAPI gets the common, portable surface. */ + memcpy(aMethod, aMethodCommon, sizeof(aMethodCommon)); + sSystem.nMethod = SX_ARRAYSIZE(aMethodCommon); + if(PH7_VmSapiIs(pVm, "cli")) { + memcpy(aMethod + SX_ARRAYSIZE(aMethodCommon), aMethodCli, sizeof(aMethodCli)); + sSystem.nMethod += SX_ARRAYSIZE(aMethodCli); + } + rc = ph7_create_class(pVm, &sExc); + if(rc == PH7_OK) { + rc = ph7_create_class(pVm, &sSystem); + } +Cleanup: + aExcCtor[1].pDefault = 0; + aExitParam[0].pDefault = 0; + for(n = 0 ; n < SX_ARRAYSIZE(apDefault) ; ++n) { + if(apDefault[n]) { + ph7_release_value(pVm, apDefault[n]); + } + } + for(n = 0 ; n < SX_ARRAYSIZE(apConst) ; ++n) { + if(apConst[n]) { + ph7_release_value(pVm, apConst[n]); + aConst[n].pValue = 0; + } + } + return rc; +#undef SYSM +#undef SYSC +#undef STY +} +PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc) { + desc->zString = MODULE_DESC; + *ver = MODULE_VER; + return SystemRegisterClasses(pVm); +} diff --git a/modules/system/system.h b/modules/system/system.h new file mode 100644 index 0000000..67bc96d --- /dev/null +++ b/modules/system/system.h @@ -0,0 +1,24 @@ +/** + * @PROJECT AerScript Interpreter + * @COPYRIGHT See COPYING in the top level directory + * @FILE modules/system/system.h + * @DESCRIPTION System class module for AerScript Interpreter + * @DEVELOPERS Rafal Kupiec + */ +#ifndef __SYSTEM_H__ +#define __SYSTEM_H__ + +#include "ph7.h" +#include "ph7int.h" + +#define MODULE_DESC "System Module" +#define MODULE_VER 1.0 + +/* SystemException error codes, also published as System class constants. */ +#define SYS_ERROR_NONE 0 +#define SYS_ERROR_ARGUMENT 1 +#define SYS_ERROR_IO 2 + +PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc); + +#endif diff --git a/tests/complex_expressions2.aer b/tests/complex_expressions2.aer index 129e17a..f9988b7 100644 --- a/tests/complex_expressions2.aer +++ b/tests/complex_expressions2.aer @@ -1,10 +1,11 @@ +import 'system'; import 'console'; class Program { private void test(int $a = (int(int $a, int $b, int $c){return $a+$b+$c;})(14, 10+2, 15), int $b = 0, int $c = 98) { - Console::Print($a + PHP_EOL); - Console::Print($b + PHP_EOL); - Console::Print($c + PHP_EOL); + Console::Print($a + System::NEW_LINE); + Console::Print($b + System::NEW_LINE); + Console::Print($c + System::NEW_LINE); } public void main() { diff --git a/tests/ip_addr_enc_dec.aer b/tests/ip_addr_enc_dec.aer index a0a36d1..8fc9c93 100644 --- a/tests/ip_addr_enc_dec.aer +++ b/tests/ip_addr_enc_dec.aer @@ -1,3 +1,4 @@ +import 'system'; import 'console'; class Program { @@ -16,8 +17,8 @@ class Program { Console::Print("127.0.0.1 ==> $localhost\n"); string $router = $this->encode_ip('192.168.2.1'); Console::Print("192.168.2.1 ==> $router\n"); - Console::Print("$localhost ==> " + ($this->decode_ip($localhost) + PHP_EOL)); - Console::Print("$router ==> " + ($this->decode_ip($router) + PHP_EOL)); + Console::Print("$localhost ==> " + ($this->decode_ip($localhost) + System::NEW_LINE)); + Console::Print("$router ==> " + ($this->decode_ip($router) + System::NEW_LINE)); } } diff --git a/tests/static_var.aer b/tests/static_var.aer index 5c834df..7730b87 100644 --- a/tests/static_var.aer +++ b/tests/static_var.aer @@ -1,3 +1,4 @@ +import 'system'; import 'console'; class Program { @@ -12,11 +13,11 @@ class Program { public void main() { for(int $i = 1; $i < 3; $i++) { - Console::Print($i + $this->cycle('a', 'b') + PHP_EOL); + Console::Print($i + $this->cycle('a', 'b') + System::NEW_LINE); for(int $j = 1; $j < 5; $j++) { - Console::Print(' ' + $j + $this->cycle('a', 'b', 1) + PHP_EOL); + Console::Print(' ' + $j + $this->cycle('a', 'b', 1) + System::NEW_LINE); for(int $k = 1; $k < 3; $k++) { - Console::Print(' ' + $k + $this->cycle('c', 'd', 2) + PHP_EOL); + Console::Print(' ' + $k + $this->cycle('c', 'd', 2) + System::NEW_LINE); } } }