diff options
Diffstat (limited to 'generic/tclCmdAH.c')
| -rw-r--r-- | generic/tclCmdAH.c | 3656 | 
1 files changed, 2251 insertions, 1405 deletions
| diff --git a/generic/tclCmdAH.c b/generic/tclCmdAH.c index ce50da4..807a1ac 100644 --- a/generic/tclCmdAH.c +++ b/generic/tclCmdAH.c @@ -9,14 +9,36 @@   *   * See the file "license.terms" for information on usage and redistribution of   * this file, and for a DISCLAIMER OF ALL WARRANTIES. - * - * RCS: @(#) $Id: tclCmdAH.c,v 1.72 2006/02/08 21:41:27 dgp Exp $   */  #include "tclInt.h" +#ifdef _WIN32 +#   include "tclWinInt.h" +#endif  #include <locale.h> -#define NEW_FORMAT 1 +/* + * The state structure used by [foreach]. Note that the actual structure has + * all its working arrays appended afterwards so they can be allocated and + * freed in a single step. + */ + +struct ForeachState { +    Tcl_Obj *bodyPtr;		/* The script body of the command. */ +    int bodyIdx;		/* The argument index of the body. */ +    int j, maxj;		/* Number of loop iterations. */ +    int numLists;		/* Count of value lists. */ +    int *index;			/* Array of value list indices. */ +    int *varcList;		/* # loop variables per list. */ +    Tcl_Obj ***varvList;	/* Array of var name lists. */ +    Tcl_Obj **vCopyList;	/* Copies of var name list arguments. */ +    int *argcList;		/* Array of value list sizes. */ +    Tcl_Obj ***argvList;	/* Array of value lists. */ +    Tcl_Obj **aCopyList;	/* Copies of value list arguments. */ +    Tcl_Obj *resultList;	/* List of result values from the loop body, +				 * or NULL if we're not collecting them +				 * ([lmap] vs [foreach]). */ +};  /*   * Prototypes for local procedures defined in this file: @@ -24,14 +46,70 @@  static int		CheckAccess(Tcl_Interp *interp, Tcl_Obj *pathPtr,  			    int mode); +static int		BadEncodingSubcommand(ClientData dummy, +			    Tcl_Interp *interp, int objc, +			    Tcl_Obj *const objv[]); +static int		EncodingConvertfromObjCmd(ClientData dummy, +			    Tcl_Interp *interp, int objc, +			    Tcl_Obj *const objv[]); +static int		EncodingConverttoObjCmd(ClientData dummy, +			    Tcl_Interp *interp, int objc, +			    Tcl_Obj *const objv[]);  static int		EncodingDirsObjCmd(ClientData dummy, -				Tcl_Interp *interp, int objc, -				Tcl_Obj *CONST objv[]); +			    Tcl_Interp *interp, int objc, +			    Tcl_Obj *const objv[]); +static int		EncodingNamesObjCmd(ClientData dummy, +			    Tcl_Interp *interp, int objc, +			    Tcl_Obj *const objv[]); +static int		EncodingSystemObjCmd(ClientData dummy, +			    Tcl_Interp *interp, int objc, +			    Tcl_Obj *const objv[]); +static inline int	ForeachAssignments(Tcl_Interp *interp, +			    struct ForeachState *statePtr); +static inline void	ForeachCleanup(Tcl_Interp *interp, +			    struct ForeachState *statePtr);  static int		GetStatBuf(Tcl_Interp *interp, Tcl_Obj *pathPtr,  			    Tcl_FSStatProc *statProc, Tcl_StatBuf *statPtr); -static char *		GetTypeFromMode(int mode); +static const char *	GetTypeFromMode(int mode);  static int		StoreStatData(Tcl_Interp *interp, Tcl_Obj *varName,  			    Tcl_StatBuf *statPtr); +static inline int	EachloopCmd(Tcl_Interp *interp, int collect, +			    int objc, Tcl_Obj *const objv[]); +static Tcl_NRPostProc	CatchObjCmdCallback; +static Tcl_NRPostProc	ExprCallback; +static Tcl_NRPostProc	ForSetupCallback; +static Tcl_NRPostProc	ForCondCallback; +static Tcl_NRPostProc	ForNextCallback; +static Tcl_NRPostProc	ForPostNextCallback; +static Tcl_NRPostProc	ForeachLoopStep; +static Tcl_NRPostProc	EvalCmdErrMsg; + +static Tcl_ObjCmdProc	BadFileSubcommand; +static Tcl_ObjCmdProc FileAttrAccessTimeCmd; +static Tcl_ObjCmdProc FileAttrIsDirectoryCmd; +static Tcl_ObjCmdProc FileAttrIsExecutableCmd; +static Tcl_ObjCmdProc FileAttrIsExistingCmd; +static Tcl_ObjCmdProc FileAttrIsFileCmd; +static Tcl_ObjCmdProc FileAttrIsOwnedCmd; +static Tcl_ObjCmdProc FileAttrIsReadableCmd; +static Tcl_ObjCmdProc FileAttrIsWritableCmd; +static Tcl_ObjCmdProc FileAttrLinkStatCmd; +static Tcl_ObjCmdProc FileAttrModifyTimeCmd; +static Tcl_ObjCmdProc FileAttrSizeCmd; +static Tcl_ObjCmdProc FileAttrStatCmd; +static Tcl_ObjCmdProc FileAttrTypeCmd; +static Tcl_ObjCmdProc FilesystemSeparatorCmd; +static Tcl_ObjCmdProc FilesystemVolumesCmd; +static Tcl_ObjCmdProc PathDirNameCmd; +static Tcl_ObjCmdProc PathExtensionCmd; +static Tcl_ObjCmdProc PathFilesystemCmd; +static Tcl_ObjCmdProc PathJoinCmd; +static Tcl_ObjCmdProc PathNativeNameCmd; +static Tcl_ObjCmdProc PathNormalizeCmd; +static Tcl_ObjCmdProc PathRootNameCmd; +static Tcl_ObjCmdProc PathSplitCmd; +static Tcl_ObjCmdProc PathTailCmd; +static Tcl_ObjCmdProc PathTypeCmd;  /*   *---------------------------------------------------------------------- @@ -56,11 +134,11 @@ static int		StoreStatData(Tcl_Interp *interp, Tcl_Obj *varName,  	/* ARGSUSED */  int -Tcl_BreakObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_BreakObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  {      if (objc != 1) {  	Tcl_WrongNumArgs(interp, 1, objv, NULL); @@ -75,7 +153,8 @@ Tcl_BreakObjCmd(dummy, interp, objc, objv)   * Tcl_CaseObjCmd --   *   *	This procedure is invoked to process the "case" Tcl command. See the - *	user documentation for details on what it does. + *	user documentation for details on what it does. THIS COMMAND IS + *	OBSOLETE AND DEPRECATED. SLATED FOR REMOVAL IN TCL 9.0.   *   * Results:   *	A standard Tcl object result. @@ -85,24 +164,24 @@ Tcl_BreakObjCmd(dummy, interp, objc, objv)   *   *----------------------------------------------------------------------   */ - +#ifndef TCL_NO_DEPRECATED  	/* ARGSUSED */  int -Tcl_CaseObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_CaseObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  {      register int i;      int body, result, caseObjc; -    char *stringPtr, *arg; -    Tcl_Obj *CONST *caseObjv; +    const char *stringPtr, *arg; +    Tcl_Obj *const *caseObjv;      Tcl_Obj *armPtr;      if (objc < 3) {  	Tcl_WrongNumArgs(interp, 1, objv, -		"string ?in? patList body ... ?default body?"); +		"string ?in? ?pattern body ...? ?default body?");  	return TCL_ERROR;      } @@ -126,19 +205,19 @@ Tcl_CaseObjCmd(dummy, interp, objc, objv)      if (caseObjc == 1) {  	Tcl_Obj **newObjv; -	Tcl_ListObjGetElements(interp, caseObjv[0], &caseObjc, &newObjv); +	TclListObjGetElements(interp, caseObjv[0], &caseObjc, &newObjv);  	caseObjv = newObjv;      }      for (i = 0;  i < caseObjc;  i += 2) {  	int patObjc, j; -	CONST char **patObjv; -	char *pat; -	unsigned char *p; +	const char **patObjv; +	const char *pat, *p; -	if (i == (caseObjc - 1)) { +	if (i == caseObjc-1) {  	    Tcl_ResetResult(interp); -	    Tcl_AppendResult(interp, "extra case pattern with no body", NULL); +	    Tcl_SetObjResult(interp, Tcl_NewStringObj( +		    "extra case pattern with no body", -1));  	    return TCL_ERROR;  	} @@ -148,8 +227,8 @@ Tcl_CaseObjCmd(dummy, interp, objc, objv)  	 */  	pat = TclGetString(caseObjv[i]); -	for (p = (unsigned char *) pat; *p != '\0'; p++) { -	    if (isspace(*p) || (*p == '\\')) {	/* INTL: ISO space, UCHAR */ +	for (p = pat; *p != '\0'; p++) { +	    if (TclIsSpaceProc(*p) || (*p == '\\')) {  		break;  	    }  	} @@ -179,7 +258,7 @@ Tcl_CaseObjCmd(dummy, interp, objc, objv)  		break;  	    }  	} -	ckfree((char *) patObjv); +	ckfree(patObjv);  	if (j < patObjc) {  	    break;  	} @@ -190,8 +269,9 @@ Tcl_CaseObjCmd(dummy, interp, objc, objv)  	armPtr = caseObjv[body - 1];  	result = Tcl_EvalObjEx(interp, caseObjv[body], 0);  	if (result == TCL_ERROR) { -	    TclFormatToErrorInfo(interp, "\n    (\"%.50s\" arm line %d)", -		    TclGetString(armPtr), interp->errorLine); +	    Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf( +		    "\n    (\"%.50s\" arm line %d)", +		    TclGetString(armPtr), Tcl_GetErrorLine(interp)));  	}  	return result;      } @@ -202,6 +282,7 @@ Tcl_CaseObjCmd(dummy, interp, objc, objv)      return TCL_OK;  } +#endif /* !TCL_NO_DEPRECATED */  /*   *---------------------------------------------------------------------- @@ -222,15 +303,25 @@ Tcl_CaseObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_CatchObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_CatchObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{ +    return Tcl_NRCallObjProc(interp, TclNRCatchObjCmd, dummy, objc, objv); +} + +int +TclNRCatchObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  {      Tcl_Obj *varNamePtr = NULL;      Tcl_Obj *optionVarNamePtr = NULL; -    int result; +    Interp *iPtr = (Interp *) interp;      if ((objc < 2) || (objc > 4)) {  	Tcl_WrongNumArgs(interp, 1, objv, @@ -245,34 +336,51 @@ Tcl_CatchObjCmd(dummy, interp, objc, objv)  	optionVarNamePtr = objv[3];      } -    result = Tcl_EvalObjEx(interp, objv[1], 0); +    TclNRAddCallback(interp, CatchObjCmdCallback, INT2PTR(objc), +	    varNamePtr, optionVarNamePtr, NULL); + +    /* +     * TIP #280. Make invoking context available to caught script. +     */ + +    return TclNREvalObjEx(interp, objv[1], 0, iPtr->cmdFramePtr, 1); +} + +static int +CatchObjCmdCallback( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    Interp *iPtr = (Interp *) interp; +    int objc = PTR2INT(data[0]); +    Tcl_Obj *varNamePtr = data[1]; +    Tcl_Obj *optionVarNamePtr = data[2]; +    int rewind = iPtr->execEnvPtr->rewind;      /*       * We disable catch in interpreters where the limit has been exceeded.       */ -    if (Tcl_LimitExceeded(interp)) { -	TclFormatToErrorInfo(interp, "\n    (\"catch\" body line %d)", -		interp->errorLine); +    if (rewind || Tcl_LimitExceeded(interp)) { +	Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf( +		"\n    (\"catch\" body line %d)", Tcl_GetErrorLine(interp)));  	return TCL_ERROR;      }      if (objc >= 3) {  	if (NULL == Tcl_ObjSetVar2(interp, varNamePtr, NULL, -		Tcl_GetObjResult(interp), 0)) { -	    Tcl_ResetResult(interp); -	    Tcl_AppendResult(interp, -		    "couldn't save command result in variable", NULL); +		Tcl_GetObjResult(interp), TCL_LEAVE_ERR_MSG)) {  	    return TCL_ERROR;  	}      }      if (objc == 4) {  	Tcl_Obj *options = Tcl_GetReturnOptions(interp, result); +  	if (NULL == Tcl_ObjSetVar2(interp, optionVarNamePtr, NULL, -		options, 0)) { -	    Tcl_ResetResult(interp); -	    Tcl_AppendResult(interp, -		    "couldn't save return options in variable", NULL); +		options, TCL_LEAVE_ERR_MSG)) { +	    /* Do not decrRefCount 'options', it was already done by +	     * Tcl_ObjSetVar2 */  	    return TCL_ERROR;  	}      } @@ -301,11 +409,11 @@ Tcl_CatchObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_CdObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_CdObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  {      Tcl_Obj *dir;      int result; @@ -318,7 +426,7 @@ Tcl_CdObjCmd(dummy, interp, objc, objv)      if (objc == 2) {  	dir = objv[1];      } else { -	dir = Tcl_NewStringObj("~",1); +	TclNewLiteralStringObj(dir, "~");  	Tcl_IncrRefCount(dir);      }      if (Tcl_FSConvertToPathType(interp, dir) != TCL_OK) { @@ -326,8 +434,9 @@ Tcl_CdObjCmd(dummy, interp, objc, objv)      } else {  	result = Tcl_FSChdir(dir);  	if (result != TCL_OK) { -	    Tcl_AppendResult(interp, "couldn't change working directory to \"", -		    TclGetString(dir), "\": ", Tcl_PosixError(interp), NULL); +	    Tcl_SetObjResult(interp, Tcl_ObjPrintf( +		    "couldn't change working directory to \"%s\": %s", +		    TclGetString(dir), Tcl_PosixError(interp)));  	    result = TCL_ERROR;  	}      } @@ -356,11 +465,11 @@ Tcl_CdObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_ConcatObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_ConcatObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  {      if (objc >= 2) {  	Tcl_SetObjResult(interp, Tcl_ConcatObj(objc-1, objv+1)); @@ -391,11 +500,11 @@ Tcl_ConcatObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_ContinueObjCmd(dummy, interp, objc, objv) -    ClientData dummy;			/* Not used. */ -    Tcl_Interp *interp;			/* Current interpreter. */ -    int objc;				/* Number of arguments. */ -    Tcl_Obj *CONST objv[];		/* Argument objects. */ +Tcl_ContinueObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  {      if (objc != 1) {  	Tcl_WrongNumArgs(interp, 1, objv, NULL); @@ -421,15 +530,15 @@ Tcl_ContinueObjCmd(dummy, interp, objc, objv)   */  int -Tcl_EncodingObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_EncodingObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  {      int index; -    static CONST char *optionStrings[] = { +    static const char *const optionStrings[] = {  	"convertfrom", "convertto", "dirs", "names", "system",  	NULL      }; @@ -448,81 +557,280 @@ Tcl_EncodingObjCmd(dummy, interp, objc, objv)      switch ((enum options) index) {      case ENC_CONVERTTO: -    case ENC_CONVERTFROM: { -	Tcl_Obj *data; -	Tcl_DString ds; -	Tcl_Encoding encoding; -	int length; -	char *stringPtr; - -	if (objc == 3) { -	    encoding = Tcl_GetEncoding(interp, NULL); -	    data = objv[2]; -	} else if (objc == 4) { -	    if (Tcl_GetEncodingFromObj(interp, objv[2], &encoding) != TCL_OK) { -		return TCL_ERROR; -	    } -	    data = objv[3]; -	} else { -	    Tcl_WrongNumArgs(interp, 2, objv, "?encoding? data"); -	    return TCL_ERROR; -	} +	return EncodingConverttoObjCmd(dummy, interp, objc, objv); +    case ENC_CONVERTFROM: +	return EncodingConvertfromObjCmd(dummy, interp, objc, objv); +    case ENC_DIRS: +	return EncodingDirsObjCmd(dummy, interp, objc, objv); +    case ENC_NAMES: +	return EncodingNamesObjCmd(dummy, interp, objc, objv); +    case ENC_SYSTEM: +	return EncodingSystemObjCmd(dummy, interp, objc, objv); +    } +    return TCL_OK; +} + +/* + *----------------------------------------------------------------------------- + * + * TclInitEncodingCmd -- + * + *	This function creates the 'encoding' ensemble. + * + * Results: + *	Returns the Tcl_Command so created. + * + * Side effects: + *	The ensemble is initialized. + * + * This command is hidden in a safe interpreter. + */ -	if ((enum options) index == ENC_CONVERTFROM) { -	    /* -	     * Treat the string as binary data. -	     */ +Tcl_Command +TclInitEncodingCmd( +    Tcl_Interp* interp)		/* Tcl interpreter */ +{ +    static const EnsembleImplMap encodingImplMap[] = { +	{"convertfrom", EncodingConvertfromObjCmd, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0}, +	{"convertto",   EncodingConverttoObjCmd,   TclCompileBasic1Or2ArgCmd, NULL, NULL, 0}, +	{"dirs",        EncodingDirsObjCmd,        TclCompileBasic0Or1ArgCmd, NULL, NULL, 0}, +	{"names",       EncodingNamesObjCmd,       TclCompileBasic0ArgCmd,    NULL, NULL, 0}, +	{"system",      EncodingSystemObjCmd,      TclCompileBasic0Or1ArgCmd, NULL, NULL, 0}, +	{NULL,          NULL,                      NULL,                      NULL, NULL, 0} +    }; -	    stringPtr = (char *) Tcl_GetByteArrayFromObj(data, &length); -	    Tcl_ExternalToUtfDString(encoding, stringPtr, length, &ds); +    return TclMakeEnsemble(interp, "encoding", encodingImplMap); +} + +/* + *----------------------------------------------------------------------------- + * + * TclMakeEncodingCommandSafe -- + * + *	This function hides the unsafe 'dirs' and 'system' subcommands of + *	the "encoding" Tcl command ensemble. It must be called only from + *	TclHideUnsafeCommands. + * + * Results: + *	A standard Tcl result + * + * Side effects: + *	Adds commands to the table of hidden commands. + * + *----------------------------------------------------------------------------- + */ -	    /* -	     * Note that we cannot use Tcl_DStringResult here because it will -	     * truncate the string at the first null byte. -	     */ +int +TclMakeEncodingCommandSafe( +    Tcl_Interp* interp)		/* Tcl interpreter */ +{ +    static const struct { +	const char *cmdName; +	int unsafe; +    } unsafeInfo[] = { +	{"convertfrom", 0}, +	{"convertto",   0}, +	{"dirs",        1}, +	{"names",       0}, +	{"system",      0}, +	{NULL,          0} +    }; -	    Tcl_SetObjResult(interp, Tcl_NewStringObj( -		    Tcl_DStringValue(&ds), Tcl_DStringLength(&ds))); -	    Tcl_DStringFree(&ds); -	} else { -	    /* -	     * Store the result as binary data. -	     */ - -	    stringPtr = Tcl_GetStringFromObj(data, &length); -	    Tcl_UtfToExternalDString(encoding, stringPtr, length, &ds); -	    Tcl_SetObjResult(interp, Tcl_NewByteArrayObj( -		    (unsigned char *) Tcl_DStringValue(&ds), -		    Tcl_DStringLength(&ds))); -	    Tcl_DStringFree(&ds); +    int i; +    Tcl_DString oldBuf, newBuf; + +    Tcl_DStringInit(&oldBuf); +    TclDStringAppendLiteral(&oldBuf, "::tcl::encoding::"); +    Tcl_DStringInit(&newBuf); +    TclDStringAppendLiteral(&newBuf, "tcl:encoding:"); +    for (i=0 ; unsafeInfo[i].cmdName != NULL ; i++) { +	if (unsafeInfo[i].unsafe) { +	    const char *oldName, *newName; + +	    Tcl_DStringSetLength(&oldBuf, 17); +	    oldName = Tcl_DStringAppend(&oldBuf, unsafeInfo[i].cmdName, -1); +	    Tcl_DStringSetLength(&newBuf, 13); +	    newName = Tcl_DStringAppend(&newBuf, unsafeInfo[i].cmdName, -1); +	    if (TclRenameCommand(interp, oldName, "___tmp") != TCL_OK +		    || Tcl_HideCommand(interp, "___tmp", newName) != TCL_OK) { +		Tcl_Panic("problem making 'encoding %s' safe: %s", +			unsafeInfo[i].cmdName, +			Tcl_GetString(Tcl_GetObjResult(interp))); +	    } +	    Tcl_CreateObjCommand(interp, oldName, BadEncodingSubcommand, +		    (ClientData) unsafeInfo[i].cmdName, NULL);  	} +    } +    Tcl_DStringFree(&oldBuf); +    Tcl_DStringFree(&newBuf); -	Tcl_FreeEncoding(encoding); -	break; +    /* +     * Ugh. The [encoding] command is now actually safe, but it is assumed by +     * scripts that it is not, which messes up security policies. +     */ + +    if (Tcl_HideCommand(interp, "encoding", "encoding") != TCL_OK) { +	Tcl_Panic("problem making 'encoding' safe: %s", +		Tcl_GetString(Tcl_GetObjResult(interp)));      } -    case ENC_DIRS: -	return EncodingDirsObjCmd(dummy, interp, objc-1, objv+1); -    case ENC_NAMES: -	if (objc > 2) { -	    Tcl_WrongNumArgs(interp, 2, objv, NULL); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * BadEncodingSubcommand -- + * + *	Command used to act as a backstop implementation when subcommands of + *	"encoding" are unsafe (the real implementations of the subcommands are + *	hidden). The clientData is always the full official subcommand name. + * + * Results: + *	A standard Tcl result (always a TCL_ERROR). + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +BadEncodingSubcommand( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    const char *subcommandName = (const char *) clientData; + +    Tcl_SetObjResult(interp, Tcl_ObjPrintf( +	    "not allowed to invoke subcommand %s of encoding", subcommandName)); +    Tcl_SetErrorCode(interp, "TCL", "SAFE", "SUBCOMMAND", NULL); +    return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * EncodingConvertfromObjCmd -- + * + *	This command converts a byte array in an external encoding into a + *	Tcl string + * + * Results: + *	A standard Tcl result. + * + *---------------------------------------------------------------------- + */ + +int +EncodingConvertfromObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{ +    Tcl_Obj *data;		/* Byte array to convert */ +    Tcl_DString ds;		/* Buffer to hold the string */ +    Tcl_Encoding encoding;	/* Encoding to use */ +    int length;			/* Length of the byte array being converted */ +    const char *bytesPtr;	/* Pointer to the first byte of the array */ + +    if (objc == 2) { +	encoding = Tcl_GetEncoding(interp, NULL); +	data = objv[1]; +    } else if (objc == 3) { +	if (Tcl_GetEncodingFromObj(interp, objv[1], &encoding) != TCL_OK) {  	    return TCL_ERROR;  	} -	Tcl_GetEncodingNames(interp); -	break; -    case ENC_SYSTEM: -	if (objc > 3) { -	    Tcl_WrongNumArgs(interp, 2, objv, "?encoding?"); +	data = objv[2]; +    } else { +	Tcl_WrongNumArgs(interp, 1, objv, "?encoding? data"); +	return TCL_ERROR; +    } + +    /* +     * Convert the string into a byte array in 'ds' +     */ +    bytesPtr = (char *) Tcl_GetByteArrayFromObj(data, &length); +    Tcl_ExternalToUtfDString(encoding, bytesPtr, length, &ds); + +    /* +     * Note that we cannot use Tcl_DStringResult here because it will +     * truncate the string at the first null byte. +     */ + +    Tcl_SetObjResult(interp, TclDStringToObj(&ds)); + +    /* +     * We're done with the encoding +     */ + +    Tcl_FreeEncoding(encoding); +    return TCL_OK; + +} + +/* + *---------------------------------------------------------------------- + * + * EncodingConverttoObjCmd -- + * + *	This command converts a Tcl string into a byte array that + *	encodes the string according to some encoding. + * + * Results: + *	A standard Tcl result. + * + *---------------------------------------------------------------------- + */ + +int +EncodingConverttoObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{ +    Tcl_Obj *data;		/* String to convert */ +    Tcl_DString ds;		/* Buffer to hold the byte array */ +    Tcl_Encoding encoding;	/* Encoding to use */ +    int length;			/* Length of the string being converted */ +    const char *stringPtr;	/* Pointer to the first byte of the string */ + +    /* TODO - ADJUST OBJ INDICES WHEN ENSEMBLIFYING THIS */ + +    if (objc == 2) { +	encoding = Tcl_GetEncoding(interp, NULL); +	data = objv[1]; +    } else if (objc == 3) { +	if (Tcl_GetEncodingFromObj(interp, objv[1], &encoding) != TCL_OK) {  	    return TCL_ERROR;  	} -	if (objc == 2) { -	    Tcl_SetObjResult(interp, Tcl_NewStringObj( -		    Tcl_GetEncodingName(NULL), -1)); -	} else { -	    return Tcl_SetSystemEncoding(interp, TclGetString(objv[2])); -	} -	break; +	data = objv[2]; +    } else { +	Tcl_WrongNumArgs(interp, 1, objv, "?encoding? data"); +	return TCL_ERROR;      } + +    /* +     * Convert the string to a byte array in 'ds' +     */ + +    stringPtr = TclGetStringFromObj(data, &length); +    Tcl_UtfToExternalDString(encoding, stringPtr, length, &ds); +    Tcl_SetObjResult(interp, +		     Tcl_NewByteArrayObj((unsigned char*) Tcl_DStringValue(&ds), +					 Tcl_DStringLength(&ds))); +    Tcl_DStringFree(&ds); + +    /* +     * We're done with the encoding +     */ + +    Tcl_FreeEncoding(encoding);      return TCL_OK; +  }  /* @@ -542,12 +850,14 @@ Tcl_EncodingObjCmd(dummy, interp, objc, objv)   */  int -EncodingDirsObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +EncodingDirsObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  { +    Tcl_Obj *dirListObj; +      if (objc > 2) {  	Tcl_WrongNumArgs(interp, 1, objv, "?dirList?");  	return TCL_ERROR; @@ -556,12 +866,79 @@ EncodingDirsObjCmd(dummy, interp, objc, objv)  	Tcl_SetObjResult(interp, Tcl_GetEncodingSearchPath());  	return TCL_OK;      } -    if (Tcl_SetEncodingSearchPath(objv[1]) == TCL_ERROR) { -	Tcl_AppendResult(interp, "expected directory list but got \"", -		Tcl_GetString(objv[1]), "\"", NULL); + +    dirListObj = objv[1]; +    if (Tcl_SetEncodingSearchPath(dirListObj) == TCL_ERROR) { +	Tcl_SetObjResult(interp, Tcl_ObjPrintf( +		"expected directory list but got \"%s\"", +		TclGetString(dirListObj))); +	Tcl_SetErrorCode(interp, "TCL", "OPERATION", "ENCODING", "BADPATH", +		NULL);  	return TCL_ERROR;      } -    Tcl_SetObjResult(interp, objv[1]); +    Tcl_SetObjResult(interp, dirListObj); +    return TCL_OK; +} + +/* + *----------------------------------------------------------------------------- + * + * EncodingNamesObjCmd -- + * + *	This command returns a list of the available encoding names + * + * Results: + *	Returns a standard Tcl result + * + *----------------------------------------------------------------------------- + */ + +int +EncodingNamesObjCmd(ClientData dummy,       /* Unused */ +		    Tcl_Interp* interp,	    /* Tcl interpreter */ +		    int objc,		    /* Number of command line args */ +		    Tcl_Obj* const objv[])  /* Vector of command line args */ +{ +    if (objc > 1) { +	Tcl_WrongNumArgs(interp, 1, objv, NULL); +	return TCL_ERROR; +    } +    Tcl_GetEncodingNames(interp); +    return TCL_OK; +} + +/* + *----------------------------------------------------------------------------- + * + * EncodingSystemObjCmd -- + * + *	This command retrieves or changes the system encoding + * + * Results: + *	Returns a standard Tcl result + * + * Side effects: + *	May change the system encoding. + * + *----------------------------------------------------------------------------- + */ + +int +EncodingSystemObjCmd(ClientData dummy,      /* Unused */ +		     Tcl_Interp* interp,    /* Tcl interpreter */ +		     int objc,		    /* Number of command line args */ +		     Tcl_Obj* const objv[]) /* Vector of command line args */ +{ +    if (objc > 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "?encoding?"); +	return TCL_ERROR; +    } +    if (objc == 1) { +	Tcl_SetObjResult(interp, +			 Tcl_NewStringObj(Tcl_GetEncodingName(NULL), -1)); +    } else { +	return Tcl_SetSystemEncoding(interp, TclGetString(objv[1])); +    }      return TCL_OK;  } @@ -584,30 +961,30 @@ EncodingDirsObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_ErrorObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_ErrorObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  { -    Tcl_Obj *options; +    Tcl_Obj *options, *optName;      if ((objc < 2) || (objc > 4)) {  	Tcl_WrongNumArgs(interp, 1, objv, "message ?errorInfo? ?errorCode?");  	return TCL_ERROR;      } -    options = Tcl_NewStringObj("-code error -level 0", -1); +    TclNewLiteralStringObj(options, "-code error -level 0"); -    if (objc >= 3) {		/* process the optional info argument */ -	Tcl_ListObjAppendElement(NULL, options, -		Tcl_NewStringObj("-errorinfo", -1)); +    if (objc >= 3) {		/* Process the optional info argument */ +	TclNewLiteralStringObj(optName, "-errorinfo"); +	Tcl_ListObjAppendElement(NULL, options, optName);  	Tcl_ListObjAppendElement(NULL, options, objv[2]);      } -    if (objc == 4) {		/* process the optional code argument */ -	Tcl_ListObjAppendElement(NULL, options, -		Tcl_NewStringObj("-errorcode", -1)); +    if (objc >= 4) {		/* Process the optional code argument */ +	TclNewLiteralStringObj(optName, "-errorcode"); +	Tcl_ListObjAppendElement(NULL, options, optName);  	Tcl_ListObjAppendElement(NULL, options, objv[3]);      } @@ -633,15 +1010,40 @@ Tcl_ErrorObjCmd(dummy, interp, objc, objv)   */  	/* ARGSUSED */ +static int +EvalCmdErrMsg( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    if (result == TCL_ERROR) { +	Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf( +		"\n    (\"eval\" body line %d)", Tcl_GetErrorLine(interp))); +    } +    return result; +} +  int -Tcl_EvalObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_EvalObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{ +    return Tcl_NRCallObjProc(interp, TclNREvalObjCmd, dummy, objc, objv); +} + +int +TclNREvalObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  { -    int result;      register Tcl_Obj *objPtr; +    Interp *iPtr = (Interp *) interp; +    CmdFrame *invoker = NULL; +    int word = 0;      if (objc < 2) {  	Tcl_WrongNumArgs(interp, 1, objv, "arg ?arg ...?"); @@ -649,22 +1051,28 @@ Tcl_EvalObjCmd(dummy, interp, objc, objv)      }      if (objc == 2) { -	result = Tcl_EvalObjEx(interp, objv[1], TCL_EVAL_DIRECT); +	/* +	 * TIP #280. Make argument location available to eval'd script. +	 */ + +	invoker = iPtr->cmdFramePtr; +	word = 1; +	objPtr = objv[1]; +	TclArgumentGet(interp, objPtr, &invoker, &word);      } else {  	/*  	 * More than one argument: concatenate them together with spaces  	 * between, then evaluate the result. Tcl_EvalObjEx will delete the  	 * object when it decrements its refcount after eval'ing it. +	 * +	 * TIP #280. Make invoking context available to eval'd script, done +	 * with the default values.  	 */  	objPtr = Tcl_ConcatObj(objc-1, objv+1); -	result = Tcl_EvalObjEx(interp, objPtr, TCL_EVAL_DIRECT);      } -    if (result == TCL_ERROR) { -	TclFormatToErrorInfo(interp,"\n    (\"eval\" body line %d)", -		interp->errorLine); -    } -    return result; +    TclNRAddCallback(interp, EvalCmdErrMsg, NULL, NULL, NULL, NULL); +    return TclNREvalObjEx(interp, objPtr, 0, invoker, word);  }  /* @@ -686,11 +1094,11 @@ Tcl_EvalObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_ExitObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_ExitObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  {      int value; @@ -706,7 +1114,7 @@ Tcl_ExitObjCmd(dummy, interp, objc, objv)      }      Tcl_Exit(value);      /*NOTREACHED*/ -    return TCL_OK;			/* Better not ever reach this! */ +    return TCL_OK;		/* Better not ever reach this! */  }  /* @@ -735,44 +1143,73 @@ Tcl_ExitObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_ExprObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_ExprObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  { -    register Tcl_Obj *objPtr; -    Tcl_Obj *resultPtr; -    int result; +    return Tcl_NRCallObjProc(interp, TclNRExprObjCmd, dummy, objc, objv); +} + +int +TclNRExprObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{ +    Tcl_Obj *resultPtr, *objPtr;      if (objc < 2) {  	Tcl_WrongNumArgs(interp, 1, objv, "arg ?arg ...?");  	return TCL_ERROR;      } -    objPtr = Tcl_ConcatObj(objc-1, objv+1); -    Tcl_IncrRefCount(objPtr); -    result = Tcl_ExprObj(interp, objPtr, &resultPtr); -    Tcl_DecrRefCount(objPtr); +    TclNewObj(resultPtr); +    Tcl_IncrRefCount(resultPtr); +    if (objc == 2) { +	objPtr = objv[1]; +	TclNRAddCallback(interp, ExprCallback, resultPtr, NULL, NULL, NULL); +    } else { +	objPtr = Tcl_ConcatObj(objc-1, objv+1); +	TclNRAddCallback(interp, ExprCallback, resultPtr, objPtr, NULL, NULL); +    } + +    return Tcl_NRExprObj(interp, objPtr, resultPtr); +} + +static int +ExprCallback( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    Tcl_Obj *resultPtr = data[0]; +    Tcl_Obj *objPtr = data[1]; + +    if (objPtr != NULL) { +	Tcl_DecrRefCount(objPtr); +    }      if (result == TCL_OK) {  	Tcl_SetObjResult(interp, resultPtr); -	Tcl_DecrRefCount(resultPtr);	/* done with the result object */      } - +    Tcl_DecrRefCount(resultPtr);      return result;  }  /*   *----------------------------------------------------------------------   * - * Tcl_FileObjCmd -- + * TclInitFileCmd -- + * + *	This function builds the "file" Tcl command ensemble. See the user + *	documentation for details on what that ensemble does.   * - *	This procedure is invoked to process the "file" Tcl command. See the - *	user documentation for details on what it does. PLEASE NOTE THAT THIS - *	FAILS WITH FILENAMES AND PATHS WITH EMBEDDED NULLS. With the - *	object-based Tcl_FS APIs, the above NOTE may no longer be true. In any - *	case this assertion should be tested. + *	PLEASE NOTE THAT THIS FAILS WITH FILENAMES AND PATHS WITH EMBEDDED + *	NULLS. With the object-based Tcl_FS APIs, the above NOTE may no longer + *	be true. In any case this assertion should be tested.   *   * Results:   *	A standard Tcl result. @@ -783,570 +1220,1226 @@ Tcl_ExprObjCmd(dummy, interp, objc, objv)   *----------------------------------------------------------------------   */ -	/* ARGSUSED */ -int -Tcl_FileObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_Command +TclInitFileCmd( +    Tcl_Interp *interp)  { -    int index, value; -    Tcl_StatBuf buf; -    struct utimbuf tval; -      /* -     * This list of constants should match the fileOption string array below. +     * Note that most subcommands are unsafe because either they manipulate +     * the native filesystem or because they reveal information about the +     * native filesystem.       */ -    static CONST char *fileOptions[] = { -	"atime",	"attributes",	"channels",	"copy", -	"delete", -	"dirname",	"executable",	"exists",	"extension", -	"isdirectory",	"isfile",	"join",		"link", -	"lstat",	"mtime",	"mkdir",	"nativename", -	"normalize",    "owned", -	"pathtype",	"readable",	"readlink",	"rename", -	"rootname",	"separator",    "size",		"split", -	"stat",		"system", -	"tail",		"type",		"volumes",	"writable", -	(char *) NULL +    static const EnsembleImplMap initMap[] = { +	{"atime",	FileAttrAccessTimeCmd,	TclCompileBasic1Or2ArgCmd, NULL, NULL, 0}, +	{"attributes",	TclFileAttrsCmd,	NULL, NULL, NULL, 0}, +	{"channels",	TclChannelNamesCmd,	TclCompileBasic0Or1ArgCmd, NULL, NULL, 0}, +	{"copy",	TclFileCopyCmd,		NULL, NULL, NULL, 0}, +	{"delete",	TclFileDeleteCmd,	TclCompileBasicMin0ArgCmd, NULL, NULL, 0}, +	{"dirname",	PathDirNameCmd,		TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"executable",	FileAttrIsExecutableCmd, TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"exists",	FileAttrIsExistingCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"extension",	PathExtensionCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"isdirectory",	FileAttrIsDirectoryCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"isfile",	FileAttrIsFileCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"join",	PathJoinCmd,		TclCompileBasicMin1ArgCmd, NULL, NULL, 0}, +	{"link",	TclFileLinkCmd,		TclCompileBasic1To3ArgCmd, NULL, NULL, 0}, +	{"lstat",	FileAttrLinkStatCmd,	TclCompileBasic2ArgCmd, NULL, NULL, 0}, +	{"mtime",	FileAttrModifyTimeCmd,	TclCompileBasic1Or2ArgCmd, NULL, NULL, 0}, +	{"mkdir",	TclFileMakeDirsCmd,	TclCompileBasicMin0ArgCmd, NULL, NULL, 0}, +	{"nativename",	PathNativeNameCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"normalize",	PathNormalizeCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"owned",	FileAttrIsOwnedCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"pathtype",	PathTypeCmd,		TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"readable",	FileAttrIsReadableCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"readlink",	TclFileReadLinkCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"rename",	TclFileRenameCmd,	NULL, NULL, NULL, 0}, +	{"rootname",	PathRootNameCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"separator",	FilesystemSeparatorCmd,	TclCompileBasic0Or1ArgCmd, NULL, NULL, 0}, +	{"size",	FileAttrSizeCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"split",	PathSplitCmd,		TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"stat",	FileAttrStatCmd,	TclCompileBasic2ArgCmd, NULL, NULL, 0}, +	{"system",	PathFilesystemCmd,	TclCompileBasic0Or1ArgCmd, NULL, NULL, 0}, +	{"tail",	PathTailCmd,		TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"tempfile",	TclFileTemporaryCmd,	TclCompileBasic0To2ArgCmd, NULL, NULL, 0}, +	{"type",	FileAttrTypeCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{"volumes",	FilesystemVolumesCmd,	TclCompileBasic0ArgCmd, NULL, NULL, 0}, +	{"writable",	FileAttrIsWritableCmd,	TclCompileBasic1ArgCmd, NULL, NULL, 0}, +	{NULL, NULL, NULL, NULL, NULL, 0}      }; -    enum options { -	FCMD_ATIME,	FCMD_ATTRIBUTES, FCMD_CHANNELS,	FCMD_COPY, -	FCMD_DELETE, -	FCMD_DIRNAME,	FCMD_EXECUTABLE, FCMD_EXISTS,	FCMD_EXTENSION, -	FCMD_ISDIRECTORY, FCMD_ISFILE,	FCMD_JOIN,	FCMD_LINK, -	FCMD_LSTAT,	FCMD_MTIME,	FCMD_MKDIR,	FCMD_NATIVENAME, -	FCMD_NORMALIZE,	FCMD_OWNED, -	FCMD_PATHTYPE,	FCMD_READABLE,	FCMD_READLINK,	FCMD_RENAME, -	FCMD_ROOTNAME,	FCMD_SEPARATOR,	FCMD_SIZE,	FCMD_SPLIT, -	FCMD_STAT,	FCMD_SYSTEM, -	FCMD_TAIL,	FCMD_TYPE,	FCMD_VOLUMES,	FCMD_WRITABLE +    return TclMakeEnsemble(interp, "file", initMap); +} + +/* + *---------------------------------------------------------------------- + * + * TclMakeFileCommandSafe -- + * + *	This function hides the unsafe subcommands of the "file" Tcl command + *	ensemble. It must only be called from TclHideUnsafeCommands. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	Adds commands to the table of hidden commands. + * + *---------------------------------------------------------------------- + */ + +int +TclMakeFileCommandSafe( +    Tcl_Interp *interp) +{ +    static const struct { +	const char *cmdName; +	int unsafe; +    } unsafeInfo[] = { +	{"atime",	 1}, +	{"attributes",	 1}, +	{"channels",	 0}, +	{"copy",	 1}, +	{"delete",	 1}, +	{"dirname",	 1}, +	{"executable",	 1}, +	{"exists",	 1}, +	{"extension",	 1}, +	{"isdirectory",	 1}, +	{"isfile",	 1}, +	{"join",	 0}, +	{"link",	 1}, +	{"lstat",	 1}, +	{"mtime",	 1}, +	{"mkdir",	 1}, +	{"nativename",	 1}, +	{"normalize",	 1}, +	{"owned",	 1}, +	{"pathtype",	 0}, +	{"readable",	 1}, +	{"readlink",	 1}, +	{"rename",	 1}, +	{"rootname",	 1}, +	{"separator",	 0}, +	{"size",	 1}, +	{"split",	 0}, +	{"stat",	 1}, +	{"system",	 0}, +	{"tail",	 1}, +	{"tempfile",	 1}, +	{"type",	 1}, +	{"volumes",	 1}, +	{"writable",	 1}, +	{NULL, 0}      }; +    int i; +    Tcl_DString oldBuf, newBuf; + +    Tcl_DStringInit(&oldBuf); +    TclDStringAppendLiteral(&oldBuf, "::tcl::file::"); +    Tcl_DStringInit(&newBuf); +    TclDStringAppendLiteral(&newBuf, "tcl:file:"); +    for (i=0 ; unsafeInfo[i].cmdName != NULL ; i++) { +	if (unsafeInfo[i].unsafe) { +	    const char *oldName, *newName; + +	    Tcl_DStringSetLength(&oldBuf, 13); +	    oldName = Tcl_DStringAppend(&oldBuf, unsafeInfo[i].cmdName, -1); +	    Tcl_DStringSetLength(&newBuf, 9); +	    newName = Tcl_DStringAppend(&newBuf, unsafeInfo[i].cmdName, -1); +	    if (TclRenameCommand(interp, oldName, "___tmp") != TCL_OK +		    || Tcl_HideCommand(interp, "___tmp", newName) != TCL_OK) { +		Tcl_Panic("problem making 'file %s' safe: %s", +			unsafeInfo[i].cmdName, +			Tcl_GetString(Tcl_GetObjResult(interp))); +	    } +	    Tcl_CreateObjCommand(interp, oldName, BadFileSubcommand, +		    (ClientData) unsafeInfo[i].cmdName, NULL); +	} +    } +    Tcl_DStringFree(&oldBuf); +    Tcl_DStringFree(&newBuf); -    if (objc < 2) { -	Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?"); +    /* +     * Ugh. The [file] command is now actually safe, but it is assumed by +     * scripts that it is not, which messes up security policies. [Bug +     * 3211758] +     */ + +    if (Tcl_HideCommand(interp, "file", "file") != TCL_OK) { +	Tcl_Panic("problem making 'file' safe: %s", +		Tcl_GetString(Tcl_GetObjResult(interp))); +    } +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * BadFileSubcommand -- + * + *	Command used to act as a backstop implementation when subcommands of + *	"file" are unsafe (the real implementations of the subcommands are + *	hidden). The clientData is always the full official subcommand name. + * + * Results: + *	A standard Tcl result (always a TCL_ERROR). + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +BadFileSubcommand( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    const char *subcommandName = (const char *) clientData; + +    Tcl_SetObjResult(interp, Tcl_ObjPrintf( +	    "not allowed to invoke subcommand %s of file", subcommandName)); +    Tcl_SetErrorCode(interp, "TCL", "SAFE", "SUBCOMMAND", NULL); +    return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrAccessTimeCmd -- + * + *	This function is invoked to process the "file atime" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	May update the access time on the file, if requested by the user. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrAccessTimeCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_StatBuf buf; +    struct utimbuf tval; + +    if (objc < 2 || objc > 3) { +	Tcl_WrongNumArgs(interp, 1, objv, "name ?time?");  	return TCL_ERROR;      } -    if (Tcl_GetIndexFromObj(interp, objv[1], fileOptions, "option", 0, -	    &index) != TCL_OK) { +    if (GetStatBuf(interp, objv[1], Tcl_FSStat, &buf) != TCL_OK) {  	return TCL_ERROR;      } +#if defined(_WIN32) +    /* We use a value of 0 to indicate the access time not available */ +    if (buf.st_atime == 0) { +        Tcl_SetObjResult(interp, Tcl_ObjPrintf( +                             "could not get access time for file \"%s\"", +                             TclGetString(objv[1]))); +        return TCL_ERROR; +    } +#endif -    switch ((enum options) index) { +    if (objc == 3) { +	/* +	 * Need separate variable for reading longs from an object on 64-bit +	 * platforms. [Bug 698146] +	 */ + +	long newTime; -    case FCMD_ATIME: -    case FCMD_MTIME: -	if ((objc < 3) || (objc > 4)) { -	    Tcl_WrongNumArgs(interp, 2, objv, "name ?time?"); +	if (TclGetLongFromObj(interp, objv[2], &newTime) != TCL_OK) {  	    return TCL_ERROR;  	} -	if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) { + +	tval.actime = newTime; +	tval.modtime = buf.st_mtime; + +	if (Tcl_FSUtime(objv[1], &tval) != 0) { +	    Tcl_SetObjResult(interp, Tcl_ObjPrintf( +		    "could not set access time for file \"%s\": %s", +		    TclGetString(objv[1]), Tcl_PosixError(interp)));  	    return TCL_ERROR;  	} -	if (objc == 4) { -	    /* -	     * Need separate variable for reading longs from an object on -	     * 64-bit platforms. [Bug #698146] -	     */ -	    long newTime; +	/* +	 * Do another stat to ensure that the we return the new recognized +	 * atime - hopefully the same as the one we sent in. However, fs's +	 * like FAT don't even know what atime is. +	 */ -	    if (Tcl_GetLongFromObj(interp, objv[3], &newTime) != TCL_OK) { -		return TCL_ERROR; -	    } +	if (GetStatBuf(interp, objv[1], Tcl_FSStat, &buf) != TCL_OK) { +	    return TCL_ERROR; +	} +    } -	    if (index == FCMD_ATIME) { -		tval.actime = newTime; -		tval.modtime = buf.st_mtime; -	    } else {	/* index == FCMD_MTIME */ -		tval.actime = buf.st_atime; -		tval.modtime = newTime; -	    } +    Tcl_SetObjResult(interp, Tcl_NewLongObj((long) buf.st_atime)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrModifyTimeCmd -- + * + *	This function is invoked to process the "file mtime" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	May update the modification time on the file, if requested by the + *	user. + * + *---------------------------------------------------------------------- + */ -	    if (Tcl_FSUtime(objv[2], &tval) != 0) { -		Tcl_AppendResult(interp, "could not set ", -			(index == FCMD_ATIME ? "access" : "modification"), -			" time for file \"", TclGetString(objv[2]), "\": ", -			Tcl_PosixError(interp), (char *) NULL); -		return TCL_ERROR; -	    } +static int +FileAttrModifyTimeCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_StatBuf buf; +    struct utimbuf tval; -	    /* -	     * Do another stat to ensure that the we return the new recognized -	     * atime - hopefully the same as the one we sent in. However, fs's -	     * like FAT don't even know what atime is. -	     */ +    if (objc < 2 || objc > 3) { +	Tcl_WrongNumArgs(interp, 1, objv, "name ?time?"); +	return TCL_ERROR; +    } +    if (GetStatBuf(interp, objv[1], Tcl_FSStat, &buf) != TCL_OK) { +	return TCL_ERROR; +    } +#if defined(_WIN32) +    /* We use a value of 0 to indicate the modification time not available */ +    if (buf.st_mtime == 0) { +        Tcl_SetObjResult(interp, Tcl_ObjPrintf( +                             "could not get modification time for file \"%s\"", +                             TclGetString(objv[1]))); +        return TCL_ERROR; +    } +#endif +    if (objc == 3) { +	/* +	 * Need separate variable for reading longs from an object on 64-bit +	 * platforms. [Bug 698146] +	 */ -	    if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) { -		return TCL_ERROR; -	    } -	} +	long newTime; -	Tcl_SetObjResult(interp, Tcl_NewLongObj((long) -		(index == FCMD_ATIME ? buf.st_atime : buf.st_mtime))); -	return TCL_OK; -    case FCMD_ATTRIBUTES: -	return TclFileAttrsCmd(interp, objc, objv); -    case FCMD_CHANNELS: -	if ((objc < 2) || (objc > 3)) { -	    Tcl_WrongNumArgs(interp, 2, objv, "?pattern?"); +	if (TclGetLongFromObj(interp, objv[2], &newTime) != TCL_OK) {  	    return TCL_ERROR;  	} -	return Tcl_GetChannelNamesEx(interp, -		((objc == 2) ? NULL : TclGetString(objv[2]))); -    case FCMD_COPY: -	return TclFileCopyCmd(interp, objc, objv); -    case FCMD_DELETE: -	return TclFileDeleteCmd(interp, objc, objv); -    case FCMD_DIRNAME: { -	Tcl_Obj *dirPtr; - -	if (objc != 3) { -	    goto only3Args; -	} -	dirPtr = TclPathPart(interp, objv[2], TCL_PATH_DIRNAME); -	if (dirPtr == NULL) { + +	tval.actime = buf.st_atime; +	tval.modtime = newTime; + +	if (Tcl_FSUtime(objv[1], &tval) != 0) { +	    Tcl_SetObjResult(interp, Tcl_ObjPrintf( +		    "could not set modification time for file \"%s\": %s", +		    TclGetString(objv[1]), Tcl_PosixError(interp)));  	    return TCL_ERROR; -	} else { -	    Tcl_SetObjResult(interp, dirPtr); -	    Tcl_DecrRefCount(dirPtr); -	    return TCL_OK; -	} -    } -    case FCMD_EXECUTABLE: -	if (objc != 3) { -	    goto only3Args; -	} -	return CheckAccess(interp, objv[2], X_OK); -    case FCMD_EXISTS: -	if (objc != 3) { -	    goto only3Args;  	} -	return CheckAccess(interp, objv[2], F_OK); -    case FCMD_EXTENSION: { -	Tcl_Obj *ext; -	if (objc != 3) { -	    goto only3Args; -	} -	ext = TclPathPart(interp, objv[2], TCL_PATH_EXTENSION); -	if (ext != NULL) { -	    Tcl_SetObjResult(interp, ext); -	    Tcl_DecrRefCount(ext); -	    return TCL_OK; -	} else { +	/* +	 * Do another stat to ensure that the we return the new recognized +	 * mtime - hopefully the same as the one we sent in. +	 */ + +	if (GetStatBuf(interp, objv[1], Tcl_FSStat, &buf) != TCL_OK) {  	    return TCL_ERROR;  	}      } -    case FCMD_ISDIRECTORY: -	if (objc != 3) { -	    goto only3Args; -	} -	value = 0; -	if (GetStatBuf(NULL, objv[2], Tcl_FSStat, &buf) == TCL_OK) { -	    value = S_ISDIR(buf.st_mode); -	} -	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(value)); -	return TCL_OK; -    case FCMD_ISFILE: -	if (objc != 3) { -	    goto only3Args; -	} -	value = 0; -	if (GetStatBuf(NULL, objv[2], Tcl_FSStat, &buf) == TCL_OK) { -	    value = S_ISREG(buf.st_mode); -	} -	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(value)); -	return TCL_OK; -    case FCMD_OWNED: -	if (objc != 3) { -	    goto only3Args; -	} -	value = 0; -	if (GetStatBuf(NULL, objv[2], Tcl_FSStat, &buf) == TCL_OK) { -	    /* -	     * For Windows, there are no user ids associated with a file, so -	     * we always return 1. -	     */ - -#if defined(__WIN32__) -	    value = 1; + +    Tcl_SetObjResult(interp, Tcl_NewLongObj((long) buf.st_mtime)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrLinkStatCmd -- + * + *	This function is invoked to process the "file lstat" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	Writes to an array named by the user. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrLinkStatCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_StatBuf buf; + +    if (objc != 3) { +	Tcl_WrongNumArgs(interp, 1, objv, "name varName"); +	return TCL_ERROR; +    } +    if (GetStatBuf(interp, objv[1], Tcl_FSLstat, &buf) != TCL_OK) { +	return TCL_ERROR; +    } +    return StoreStatData(interp, objv[2], &buf); +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrStatCmd -- + * + *	This function is invoked to process the "file stat" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	Writes to an array named by the user. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrStatCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_StatBuf buf; + +    if (objc != 3) { +	Tcl_WrongNumArgs(interp, 1, objv, "name varName"); +	return TCL_ERROR; +    } +    if (GetStatBuf(interp, objv[1], Tcl_FSStat, &buf) != TCL_OK) { +	return TCL_ERROR; +    } +    return StoreStatData(interp, objv[2], &buf); +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrTypeCmd -- + * + *	This function is invoked to process the "file type" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrTypeCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_StatBuf buf; + +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    if (GetStatBuf(interp, objv[1], Tcl_FSLstat, &buf) != TCL_OK) { +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, Tcl_NewStringObj( +	    GetTypeFromMode((unsigned short) buf.st_mode), -1)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrSizeCmd -- + * + *	This function is invoked to process the "file size" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrSizeCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_StatBuf buf; + +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    if (GetStatBuf(interp, objv[1], Tcl_FSStat, &buf) != TCL_OK) { +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, Tcl_NewWideIntObj((Tcl_WideInt) buf.st_size)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrIsDirectoryCmd -- + * + *	This function is invoked to process the "file isdirectory" Tcl + *	command. See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrIsDirectoryCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_StatBuf buf; +    int value = 0; + +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    if (GetStatBuf(NULL, objv[1], Tcl_FSStat, &buf) == TCL_OK) { +	value = S_ISDIR(buf.st_mode); +    } +    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(value)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrIsExecutableCmd -- + * + *	This function is invoked to process the "file executable" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrIsExecutableCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    return CheckAccess(interp, objv[1], X_OK); +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrIsExistingCmd -- + * + *	This function is invoked to process the "file exists" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrIsExistingCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    return CheckAccess(interp, objv[1], F_OK); +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrIsFileCmd -- + * + *	This function is invoked to process the "file isfile" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrIsFileCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_StatBuf buf; +    int value = 0; + +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    if (GetStatBuf(NULL, objv[1], Tcl_FSStat, &buf) == TCL_OK) { +	value = S_ISREG(buf.st_mode); +    } +    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(value)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrIsOwnedCmd -- + * + *	This function is invoked to process the "file owned" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ + +static int +FileAttrIsOwnedCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +#ifdef __CYGWIN__ +#define geteuid() (short)(geteuid)() +#endif +#if !defined(_WIN32) +    Tcl_StatBuf buf; +#endif +    int value = 0; + +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +#if defined(_WIN32) +    value = TclWinFileOwned(objv[1]);  #else -	    value = (geteuid() == buf.st_uid); +    if (GetStatBuf(NULL, objv[1], Tcl_FSStat, &buf) == TCL_OK) { +	value = (geteuid() == buf.st_uid); +    }  #endif -	} -	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(value)); -	return TCL_OK; -    case FCMD_JOIN: { -	Tcl_Obj *resObj; +    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(value)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrIsReadableCmd -- + * + *	This function is invoked to process the "file readable" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (objc < 3) { -	    Tcl_WrongNumArgs(interp, 2, objv, "name ?name ...?"); -	    return TCL_ERROR; -	} -	resObj = Tcl_FSJoinToPath(NULL, objc - 2, objv + 2); -	Tcl_SetObjResult(interp, resObj); -	return TCL_OK; +static int +FileAttrIsReadableCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR;      } -    case FCMD_LINK: { -	Tcl_Obj *contents; -	int index; +    return CheckAccess(interp, objv[1], R_OK); +} + +/* + *---------------------------------------------------------------------- + * + * FileAttrIsWritableCmd -- + * + *	This function is invoked to process the "file writable" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (objc < 3 || objc > 5) { -	    Tcl_WrongNumArgs(interp, 2, objv, "?-linktype? linkname ?target?"); -	    return TCL_ERROR; -	} +static int +FileAttrIsWritableCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    return CheckAccess(interp, objv[1], W_OK); +} + +/* + *---------------------------------------------------------------------- + * + * PathDirNameCmd -- + * + *	This function is invoked to process the "file dirname" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	/* -	 * Index of the 'source' argument. -	 */ +static int +PathDirNameCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_Obj *dirPtr; -	if (objc == 5) { -	    index = 3; -	} else { -	    index = 2; -	} +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    dirPtr = TclPathPart(interp, objv[1], TCL_PATH_DIRNAME); +    if (dirPtr == NULL) { +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, dirPtr); +    Tcl_DecrRefCount(dirPtr); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathExtensionCmd -- + * + *	This function is invoked to process the "file extension" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (objc > 3) { -	    int linkAction; -	    if (objc == 5) { -		/* -		 * We have a '-linktype' argument. -		 */ - -		static CONST char *linkTypes[] = { -		    "-symbolic", "-hard", NULL -		}; -		if (Tcl_GetIndexFromObj(interp, objv[2], linkTypes, "switch", -			0, &linkAction) != TCL_OK) { -		    return TCL_ERROR; -		} -		if (linkAction == 0) { -		    linkAction = TCL_CREATE_SYMBOLIC_LINK; -		} else { -		    linkAction = TCL_CREATE_HARD_LINK; -		} -	    } else { -		linkAction = TCL_CREATE_SYMBOLIC_LINK|TCL_CREATE_HARD_LINK; -	    } -	    if (Tcl_FSConvertToPathType(interp, objv[index]) != TCL_OK) { -		return TCL_ERROR; -	    } +static int +PathExtensionCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_Obj *dirPtr; -	    /* -	     * Create link from source to target. -	     */ - -	    contents = Tcl_FSLink(objv[index], objv[index+1], linkAction); -	    if (contents == NULL) { -		/* -		 * We handle three common error cases specially, and for all -		 * other errors, we use the standard posix error message. -		 */ - -		if (errno == EEXIST) { -		    Tcl_AppendResult(interp, "could not create new link \"", -			    TclGetString(objv[index]), -			    "\": that path already exists", (char *) NULL); -		} else if (errno == ENOENT) { -		    /* -		     * There are two cases here: either the target doesn't -		     * exist, or the directory of the src doesn't exist. -		     */ - -		    int access; -		    Tcl_Obj *dirPtr = TclPathPart(interp, objv[index], -			    TCL_PATH_DIRNAME); - -		    if (dirPtr == NULL) { -			return TCL_ERROR; -		    } -		    access = Tcl_FSAccess(dirPtr, F_OK); -		    Tcl_DecrRefCount(dirPtr); -		    if (access != 0) { -			Tcl_AppendResult(interp, -				"could not create new link \"", -				TclGetString(objv[index]), -				"\": no such file or directory", -				(char *) NULL); -		    } else { -			Tcl_AppendResult(interp, -				"could not create new link \"", -				TclGetString(objv[index]), "\": target \"", -				TclGetString(objv[index+1]), -				"\" doesn't exist", (char *) NULL); -		    } -		} else { -		    Tcl_AppendResult(interp, -			    "could not create new link \"", -			    TclGetString(objv[index]), "\" pointing to \"", -			    TclGetString(objv[index+1]), "\": ", -			    Tcl_PosixError(interp), (char *) NULL); -		} -		return TCL_ERROR; -	    } -	} else { -	    if (Tcl_FSConvertToPathType(interp, objv[index]) != TCL_OK) { -		return TCL_ERROR; -	    } +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    dirPtr = TclPathPart(interp, objv[1], TCL_PATH_EXTENSION); +    if (dirPtr == NULL) { +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, dirPtr); +    Tcl_DecrRefCount(dirPtr); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathRootNameCmd -- + * + *	This function is invoked to process the "file root" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	    /* -	     * Read link -	     */ +static int +PathRootNameCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_Obj *dirPtr; -	    contents = Tcl_FSLink(objv[index], NULL, 0); -	    if (contents == NULL) { -		Tcl_AppendResult(interp, "could not read link \"", -			TclGetString(objv[index]), "\": ", -			Tcl_PosixError(interp), (char *) NULL); -		return TCL_ERROR; -	    } -	} -	Tcl_SetObjResult(interp, contents); -	if (objc == 3) { -	    /* -	     * If we are reading a link, we need to free this result refCount. -	     * If we are creating a link, this will just be objv[index+1], and -	     * so we don't own it. -	     */ - -	    Tcl_DecrRefCount(contents); -	} -	return TCL_OK; +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR;      } -    case FCMD_LSTAT: -	if (objc != 4) { -	    Tcl_WrongNumArgs(interp, 2, objv, "name varName"); -	    return TCL_ERROR; -	} -	if (GetStatBuf(interp, objv[2], Tcl_FSLstat, &buf) != TCL_OK) { -	    return TCL_ERROR; -	} -	return StoreStatData(interp, objv[3], &buf); -    case FCMD_STAT: -	if (objc != 4) { -	    Tcl_WrongNumArgs(interp, 2, objv, "name varName"); -	    return TCL_ERROR; -	} -	if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) { -	    return TCL_ERROR; -	} -	return StoreStatData(interp, objv[3], &buf); -    case FCMD_SIZE: -	if (objc != 3) { -	    goto only3Args; -	} -	if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) { -	    return TCL_ERROR; -	} -	Tcl_SetObjResult(interp, -		Tcl_NewWideIntObj((Tcl_WideInt) buf.st_size)); -	return TCL_OK; -    case FCMD_TYPE: -	if (objc != 3) { -	    goto only3Args; -	} -	if (GetStatBuf(interp, objv[2], Tcl_FSLstat, &buf) != TCL_OK) { -	    return TCL_ERROR; -	} -	Tcl_SetObjResult(interp, Tcl_NewStringObj( -		GetTypeFromMode((unsigned short) buf.st_mode), -1)); -	return TCL_OK; -    case FCMD_MKDIR: -	if (objc < 3) { -	    Tcl_WrongNumArgs(interp, 2, objv, "name ?name ...?"); -	    return TCL_ERROR; -	} -	return TclFileMakeDirsCmd(interp, objc, objv); -    case FCMD_NATIVENAME: { -	CONST char *fileName; -	Tcl_DString ds; +    dirPtr = TclPathPart(interp, objv[1], TCL_PATH_ROOT); +    if (dirPtr == NULL) { +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, dirPtr); +    Tcl_DecrRefCount(dirPtr); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathTailCmd -- + * + *	This function is invoked to process the "file tail" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (objc != 3) { -	    goto only3Args; -	} -	fileName = TclGetString(objv[2]); -	fileName = Tcl_TranslateFileName(interp, fileName, &ds); -	if (fileName == NULL) { -	    return TCL_ERROR; -	} -	Tcl_SetObjResult(interp, Tcl_NewStringObj(fileName, -		Tcl_DStringLength(&ds))); -	Tcl_DStringFree(&ds); -	return TCL_OK; +static int +PathTailCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_Obj *dirPtr; + +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR;      } -    case FCMD_NORMALIZE: { -	Tcl_Obj *fileName; +    dirPtr = TclPathPart(interp, objv[1], TCL_PATH_TAIL); +    if (dirPtr == NULL) { +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, dirPtr); +    Tcl_DecrRefCount(dirPtr); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathFilesystemCmd -- + * + *	This function is invoked to process the "file system" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (objc != 3) { -	    Tcl_WrongNumArgs(interp, 2, objv, "filename"); -	    return TCL_ERROR; -	} +static int +PathFilesystemCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_Obj *fsInfo; -	fileName = Tcl_FSGetNormalizedPath(interp, objv[2]); -	if (fileName == NULL) { -	    return TCL_ERROR; -	} -	Tcl_SetObjResult(interp, fileName); -	return TCL_OK; +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR;      } -    case FCMD_PATHTYPE: -	if (objc != 3) { -	    goto only3Args; -	} -	switch (Tcl_FSGetPathType(objv[2])) { -	case TCL_PATH_ABSOLUTE: -	    Tcl_SetObjResult(interp, Tcl_NewStringObj("absolute", -1)); -	    break; -	case TCL_PATH_RELATIVE: -	    Tcl_SetObjResult(interp, Tcl_NewStringObj("relative", -1)); -	    break; -	case TCL_PATH_VOLUME_RELATIVE: -	    Tcl_SetObjResult(interp, Tcl_NewStringObj("volumerelative", -1)); -	    break; -	} -	return TCL_OK; -    case FCMD_READABLE: -	if (objc != 3) { -	    goto only3Args; -	} -	return CheckAccess(interp, objv[2], R_OK); -    case FCMD_READLINK: { -	Tcl_Obj *contents; +    fsInfo = Tcl_FSFileSystemInfo(objv[1]); +    if (fsInfo == NULL) { +	Tcl_SetObjResult(interp, Tcl_NewStringObj("unrecognised path", -1)); +	Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "FILESYSTEM", +		Tcl_GetString(objv[1]), NULL); +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, fsInfo); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathJoinCmd -- + * + *	This function is invoked to process the "file join" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (objc != 3) { -	    goto only3Args; -	} +static int +PathJoinCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    if (objc < 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name ?name ...?"); +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, TclJoinPath(objc - 1, objv + 1)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathNativeNameCmd -- + * + *	This function is invoked to process the "file nativename" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (Tcl_FSConvertToPathType(interp, objv[2]) != TCL_OK) { -	    return TCL_ERROR; -	} +static int +PathNativeNameCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_DString ds; -	contents = Tcl_FSLink(objv[2], NULL, 0); +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    if (Tcl_TranslateFileName(interp, TclGetString(objv[1]), &ds) == NULL) { +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, TclDStringToObj(&ds)); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathNormalizeCmd -- + * + *	This function is invoked to process the "file normalize" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (contents == NULL) { -	    Tcl_AppendResult(interp, "could not readlink \"", -		    TclGetString(objv[2]), "\": ", Tcl_PosixError(interp), -		    (char *) NULL); -	    return TCL_ERROR; -	} -	Tcl_SetObjResult(interp, contents); -	Tcl_DecrRefCount(contents); -	return TCL_OK; +static int +PathNormalizeCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_Obj *fileName; + +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    fileName = Tcl_FSGetNormalizedPath(interp, objv[1]); +    if (fileName == NULL) { +	return TCL_ERROR;      } -    case FCMD_RENAME: -	return TclFileRenameCmd(interp, objc, objv); -    case FCMD_ROOTNAME: { -	Tcl_Obj *root; +    Tcl_SetObjResult(interp, fileName); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathSplitCmd -- + * + *	This function is invoked to process the "file split" Tcl command. See + *	the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (objc != 3) { -	    goto only3Args; -	} -	root = TclPathPart(interp, objv[2], TCL_PATH_ROOT); -	if (root != NULL) { -	    Tcl_SetObjResult(interp, root); -	    Tcl_DecrRefCount(root); -	    return TCL_OK; -	} else { -	    return TCL_ERROR; -	} +static int +PathSplitCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_Obj *res; + +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR;      } -    case FCMD_SEPARATOR: -	if ((objc < 2) || (objc > 3)) { -	    Tcl_WrongNumArgs(interp, 2, objv, "?name?"); -	    return TCL_ERROR; -	} -	if (objc == 2) { -	    char *separator = NULL; /* lint */ +    res = Tcl_FSSplitPath(objv[1], NULL); +    if (res == NULL) { +	Tcl_SetObjResult(interp, Tcl_ObjPrintf( +		"could not read \"%s\": no such file or directory", +		TclGetString(objv[1]))); +	Tcl_SetErrorCode(interp, "TCL", "OPERATION", "PATHSPLIT", "NONESUCH", +		NULL); +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, res); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * PathTypeCmd -- + * + *	This function is invoked to process the "file pathtype" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	    switch (tclPlatform) { -	    case TCL_PLATFORM_UNIX: -		separator = "/"; -		break; -	    case TCL_PLATFORM_WINDOWS: -		separator = "\\"; -		break; -	    } -	    Tcl_SetObjResult(interp, Tcl_NewStringObj(separator,1)); -	} else { -	    Tcl_Obj *separatorObj = Tcl_FSPathSeparator(objv[2]); -	    if (separatorObj != NULL) { -		Tcl_SetObjResult(interp, separatorObj); -	    } else { -		Tcl_SetObjResult(interp, -			Tcl_NewStringObj("Unrecognised path",-1)); -		return TCL_ERROR; -	    } -	} -	return TCL_OK; -    case FCMD_SPLIT: { -	Tcl_Obj *res; +static int +PathTypeCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    Tcl_Obj *typeName; -	if (objc != 3) { -	    goto only3Args; -	} -	res = Tcl_FSSplitPath(objv[2], NULL); -	if (res == NULL) { -	    if (interp != NULL) { -		Tcl_AppendResult(interp, "could not read \"", -			TclGetString(objv[2]), -			"\": no such file or directory", (char *) NULL); -	    } -	    return TCL_ERROR; -	} else { -	    Tcl_SetObjResult(interp, res); -	    return TCL_OK; -	} +    if (objc != 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "name"); +	return TCL_ERROR; +    } +    switch (Tcl_FSGetPathType(objv[1])) { +    case TCL_PATH_ABSOLUTE: +	TclNewLiteralStringObj(typeName, "absolute"); +	break; +    case TCL_PATH_RELATIVE: +	TclNewLiteralStringObj(typeName, "relative"); +	break; +    case TCL_PATH_VOLUME_RELATIVE: +	TclNewLiteralStringObj(typeName, "volumerelative"); +	break; +    default: +	/* Should be unreachable */ +	return TCL_OK;      } -    case FCMD_SYSTEM: { -	Tcl_Obj* fsInfo; +    Tcl_SetObjResult(interp, typeName); +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FilesystemSeparatorCmd -- + * + *	This function is invoked to process the "file separator" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -	if (objc != 3) { -	    goto only3Args; -	} -	fsInfo = Tcl_FSFileSystemInfo(objv[2]); -	if (fsInfo != NULL) { -	    Tcl_SetObjResult(interp, fsInfo); -	    return TCL_OK; -	} else { -	    Tcl_SetObjResult(interp, Tcl_NewStringObj("Unrecognised path",-1)); -	    return TCL_ERROR; -	} +static int +FilesystemSeparatorCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    if (objc < 1 || objc > 2) { +	Tcl_WrongNumArgs(interp, 1, objv, "?name?"); +	return TCL_ERROR;      } -    case FCMD_TAIL: { -	Tcl_Obj *dirPtr; +    if (objc == 1) { +	const char *separator = NULL; /* lint */ -	if (objc != 3) { -	    goto only3Args; -	} -	dirPtr = TclPathPart(interp, objv[2], TCL_PATH_TAIL); -	if (dirPtr == NULL) { -	    return TCL_ERROR; -	} else { -	    Tcl_SetObjResult(interp, dirPtr); -	    Tcl_DecrRefCount(dirPtr); -	    return TCL_OK; +	switch (tclPlatform) { +	case TCL_PLATFORM_UNIX: +	    separator = "/"; +	    break; +	case TCL_PLATFORM_WINDOWS: +	    separator = "\\"; +	    break;  	} -    } -    case FCMD_VOLUMES: -	if (objc != 2) { -	    Tcl_WrongNumArgs(interp, 2, objv, NULL); +	Tcl_SetObjResult(interp, Tcl_NewStringObj(separator, 1)); +    } else { +	Tcl_Obj *separatorObj = Tcl_FSPathSeparator(objv[1]); + +	if (separatorObj == NULL) { +	    Tcl_SetObjResult(interp, Tcl_NewStringObj( +		    "unrecognised path", -1)); +	    Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "FILESYSTEM", +		    Tcl_GetString(objv[1]), NULL);  	    return TCL_ERROR;  	} -	Tcl_SetObjResult(interp, Tcl_FSListVolumes()); -	return TCL_OK; -    case FCMD_WRITABLE: -	if (objc != 3) { -	    goto only3Args; -	} -	return CheckAccess(interp, objv[2], W_OK); +	Tcl_SetObjResult(interp, separatorObj);      } +    return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * FilesystemVolumesCmd -- + * + *	This function is invoked to process the "file volumes" Tcl command. + *	See the user documentation for details on what it does. + * + * Results: + *	A standard Tcl result. + * + * Side effects: + *	None. + * + *---------------------------------------------------------------------- + */ -  only3Args: -    Tcl_WrongNumArgs(interp, 2, objv, "name"); -    return TCL_ERROR; +static int +FilesystemVolumesCmd( +    ClientData clientData, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    if (objc != 1) { +	Tcl_WrongNumArgs(interp, 1, objv, NULL); +	return TCL_ERROR; +    } +    Tcl_SetObjResult(interp, Tcl_FSListVolumes()); +    return TCL_OK;  }  /* @@ -1368,11 +2461,11 @@ Tcl_FileObjCmd(dummy, interp, objc, objv)   */  static int -CheckAccess(interp, pathPtr, mode) -    Tcl_Interp *interp;		/* Interp for status return. Must not be +CheckAccess( +    Tcl_Interp *interp,		/* Interp for status return. Must not be  				 * NULL. */ -    Tcl_Obj *pathPtr;		/* Name of file to check. */ -    int mode;			/* Attribute to check; passed as argument to +    Tcl_Obj *pathPtr,		/* Name of file to check. */ +    int mode)			/* Attribute to check; passed as argument to  				 * access(). */  {      int value; @@ -1408,12 +2501,12 @@ CheckAccess(interp, pathPtr, mode)   */  static int -GetStatBuf(interp, pathPtr, statProc, statPtr) -    Tcl_Interp *interp;		/* Interp for error return. May be NULL. */ -    Tcl_Obj *pathPtr;		/* Path name to examine. */ -    Tcl_FSStatProc *statProc;	/* Either stat() or lstat() depending on +GetStatBuf( +    Tcl_Interp *interp,		/* Interp for error return. May be NULL. */ +    Tcl_Obj *pathPtr,		/* Path name to examine. */ +    Tcl_FSStatProc *statProc,	/* Either stat() or lstat() depending on  				 * desired behavior. */ -    Tcl_StatBuf *statPtr;	/* Filled with info about file obtained by +    Tcl_StatBuf *statPtr)	/* Filled with info about file obtained by  				 * calling (*statProc)(). */  {      int status; @@ -1422,13 +2515,13 @@ GetStatBuf(interp, pathPtr, statProc, statPtr)  	return TCL_ERROR;      } -    status = (*statProc)(pathPtr, statPtr); +    status = statProc(pathPtr, statPtr);      if (status < 0) {  	if (interp != NULL) { -	    Tcl_AppendResult(interp, "could not read \"", -		    TclGetString(pathPtr), "\": ", -		    Tcl_PosixError(interp), (char *) NULL); +	    Tcl_SetObjResult(interp, Tcl_ObjPrintf( +		    "could not read \"%s\": %s", +		    TclGetString(pathPtr), Tcl_PosixError(interp)));  	}  	return TCL_ERROR;      } @@ -1455,37 +2548,37 @@ GetStatBuf(interp, pathPtr, statProc, statPtr)   */  static int -StoreStatData(interp, varName, statPtr) -    Tcl_Interp *interp;		/* Interpreter for error reports. */ -    Tcl_Obj *varName;		/* Name of associative array variable in which +StoreStatData( +    Tcl_Interp *interp,		/* Interpreter for error reports. */ +    Tcl_Obj *varName,		/* Name of associative array variable in which  				 * to store stat results. */ -    Tcl_StatBuf *statPtr;	/* Pointer to buffer containing stat data to +    Tcl_StatBuf *statPtr)	/* Pointer to buffer containing stat data to  				 * store in varName. */  { -    Tcl_Obj *field = Tcl_NewObj(); -    Tcl_Obj *value; +    Tcl_Obj *field, *value;      register unsigned short mode;      /*       * Assume Tcl_ObjSetVar2() does not keep a copy of the field name!       * -     * Might be a better idea to call Tcl_SetVar2Ex() instead so we don't have -     * to make assumptions that might go wrong later. +     * Might be a better idea to call Tcl_SetVar2Ex() instead, except we want +     * to have an object (i.e. possibly cached) array variable name but a +     * string element name, so no API exists. Messy.       */  #define STORE_ARY(fieldName, object) \ -    Tcl_SetStringObj(field, (fieldName), -1); \ -    value = (object); \ +    TclNewLiteralStringObj(field, fieldName);				\ +    Tcl_IncrRefCount(field);						\ +    value = (object);							\      if (Tcl_ObjSetVar2(interp,varName,field,value,TCL_LEAVE_ERR_MSG)==NULL) { \ -	Tcl_DecrRefCount(field); \ -	return TCL_ERROR; \ -    } - -    Tcl_IncrRefCount(field); +	TclDecrRefCount(field);						\ +	return TCL_ERROR;						\ +    }									\ +    TclDecrRefCount(field);      /*       * Watch out porters; the inode is meant to be an *unsigned* value, so the -     * cast might fail when there isn't a real arithmentic 'long long' type... +     * cast might fail when there isn't a real arithmetic 'long long' type...       */      STORE_ARY("dev",	Tcl_NewLongObj((long)statPtr->st_dev)); @@ -1494,9 +2587,12 @@ StoreStatData(interp, varName, statPtr)      STORE_ARY("uid",	Tcl_NewLongObj((long)statPtr->st_uid));      STORE_ARY("gid",	Tcl_NewLongObj((long)statPtr->st_gid));      STORE_ARY("size",	Tcl_NewWideIntObj((Tcl_WideInt)statPtr->st_size)); -#ifdef HAVE_ST_BLOCKS +#ifdef HAVE_STRUCT_STAT_ST_BLOCKS      STORE_ARY("blocks",	Tcl_NewWideIntObj((Tcl_WideInt)statPtr->st_blocks));  #endif +#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE +    STORE_ARY("blksize", Tcl_NewLongObj((long)statPtr->st_blksize)); +#endif      STORE_ARY("atime",	Tcl_NewLongObj((long)statPtr->st_atime));      STORE_ARY("mtime",	Tcl_NewLongObj((long)statPtr->st_mtime));      STORE_ARY("ctime",	Tcl_NewLongObj((long)statPtr->st_ctime)); @@ -1505,7 +2601,6 @@ StoreStatData(interp, varName, statPtr)      STORE_ARY("type",	Tcl_NewStringObj(GetTypeFromMode(mode), -1));  #undef STORE_ARY -    Tcl_DecrRefCount(field);      return TCL_OK;  } @@ -1525,9 +2620,9 @@ StoreStatData(interp, varName, statPtr)   *----------------------------------------------------------------------   */ -static char * -GetTypeFromMode(mode) -    int mode; +static const char * +GetTypeFromMode( +    int mode)  {      if (S_ISREG(mode)) {  	return "file"; @@ -1570,77 +2665,210 @@ GetTypeFromMode(mode)   * Side effects:   *	See the user documentation.   * + * Notes: + *	This command is split into a lot of pieces so that it can avoid doing + *	reentrant TEBC calls. This makes things rather hard to follow, but + *	here's the plan: + * + *	NR:	---------------_\ + *	Direct:	Tcl_ForObjCmd -> TclNRForObjCmd + *					| + *				ForSetupCallback + *					| + *	[while] ------------> TclNRForIterCallback <---------. + *					|		     | + *				 ForCondCallback	     | + *					|		     | + *				 ForNextCallback ------------| + *					|		     | + *			       ForPostNextCallback	     | + *					|____________________| + *   *----------------------------------------------------------------------   */  	/* ARGSUSED */  int -Tcl_ForObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ +Tcl_ForObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{ +    return Tcl_NRCallObjProc(interp, TclNRForObjCmd, dummy, objc, objv); +} + +int +TclNRForObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */  { -    int result, value; +    Interp *iPtr = (Interp *) interp; +    ForIterData *iterPtr;      if (objc != 5) {  	Tcl_WrongNumArgs(interp, 1, objv, "start test next command");  	return TCL_ERROR;      } -    result = Tcl_EvalObjEx(interp, objv[1], 0); +    TclSmallAllocEx(interp, sizeof(ForIterData), iterPtr); +    iterPtr->cond = objv[2]; +    iterPtr->body = objv[4]; +    iterPtr->next = objv[3]; +    iterPtr->msg  = "\n    (\"for\" body line %d)"; +    iterPtr->word = 4; + +    TclNRAddCallback(interp, ForSetupCallback, iterPtr, NULL, NULL, NULL); + +    /* +     * TIP #280. Make invoking context available to initial script. +     */ + +    return TclNREvalObjEx(interp, objv[1], 0, iPtr->cmdFramePtr, 1); +} + +static int +ForSetupCallback( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    ForIterData *iterPtr = data[0]; +      if (result != TCL_OK) {  	if (result == TCL_ERROR) {  	    Tcl_AddErrorInfo(interp, "\n    (\"for\" initial command)");  	} +	TclSmallFreeEx(interp, iterPtr);  	return result;      } -    while (1) { +    TclNRAddCallback(interp, TclNRForIterCallback, iterPtr, NULL, NULL, NULL); +    return TCL_OK; +} + +int +TclNRForIterCallback( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    ForIterData *iterPtr = data[0]; +    Tcl_Obj *boolObj; + +    switch (result) { +    case TCL_OK: +    case TCL_CONTINUE:  	/* -	 * We need to reset the result before passing it off to -	 * Tcl_ExprBooleanObj. Otherwise, any error message will be appended -	 * to the result of the last evaluation. +	 * We need to reset the result before evaluating the expression. +	 * Otherwise, any error message will be appended to the result of the +	 * last evaluation.  	 */  	Tcl_ResetResult(interp); -	result = Tcl_ExprBooleanObj(interp, objv[2], &value); -	if (result != TCL_OK) { -	    return result; -	} -	if (!value) { -	    break; -	} -	result = Tcl_EvalObjEx(interp, objv[4], 0); -	if ((result != TCL_OK) && (result != TCL_CONTINUE)) { -	    if (result == TCL_ERROR) { -		TclFormatToErrorInfo(interp, "\n    (\"for\" body line %d)", -			interp->errorLine); -	    } -	    break; -	} -	result = Tcl_EvalObjEx(interp, objv[3], 0); -	if (result == TCL_BREAK) { -	    break; -	} else if (result != TCL_OK) { -	    if (result == TCL_ERROR) { -		Tcl_AddErrorInfo(interp, "\n    (\"for\" loop-end command)"); -	    } -	    return result; +	TclNewObj(boolObj); +	TclNRAddCallback(interp, ForCondCallback, iterPtr, boolObj, NULL, +		NULL); +	return Tcl_NRExprObj(interp, iterPtr->cond, boolObj); +    case TCL_BREAK: +	result = TCL_OK; +	Tcl_ResetResult(interp); +	break; +    case TCL_ERROR: +	Tcl_AppendObjToErrorInfo(interp, +		Tcl_ObjPrintf(iterPtr->msg, Tcl_GetErrorLine(interp))); +    } +    TclSmallFreeEx(interp, iterPtr); +    return result; +} + +static int +ForCondCallback( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    Interp *iPtr = (Interp *) interp; +    ForIterData *iterPtr = data[0]; +    Tcl_Obj *boolObj = data[1]; +    int value; + +    if (result != TCL_OK) { +	Tcl_DecrRefCount(boolObj); +	TclSmallFreeEx(interp, iterPtr); +	return result; +    } else if (Tcl_GetBooleanFromObj(interp, boolObj, &value) != TCL_OK) { +	Tcl_DecrRefCount(boolObj); +	TclSmallFreeEx(interp, iterPtr); +	return TCL_ERROR; +    } +    Tcl_DecrRefCount(boolObj); + +    if (value) { +	/* TIP #280. */ +	if (iterPtr->next) { +	    TclNRAddCallback(interp, ForNextCallback, iterPtr, NULL, NULL, +		    NULL); +	} else { +	    TclNRAddCallback(interp, TclNRForIterCallback, iterPtr, NULL, +		    NULL, NULL);  	} +	return TclNREvalObjEx(interp, iterPtr->body, 0, iPtr->cmdFramePtr, +		iterPtr->word);      } -    if (result == TCL_BREAK) { -	result = TCL_OK; +    TclSmallFreeEx(interp, iterPtr); +    return result; +} + +static int +ForNextCallback( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    Interp *iPtr = (Interp *) interp; +    ForIterData *iterPtr = data[0]; +    Tcl_Obj *next = iterPtr->next; + +    if ((result == TCL_OK) || (result == TCL_CONTINUE)) { +	TclNRAddCallback(interp, ForPostNextCallback, iterPtr, NULL, NULL, +		NULL); + +	/* +	 * TIP #280. Make invoking context available to next script. +	 */ + +	return TclNREvalObjEx(interp, next, 0, iPtr->cmdFramePtr, 3);      } -    if (result == TCL_OK) { -	Tcl_ResetResult(interp); + +    TclNRAddCallback(interp, TclNRForIterCallback, iterPtr, NULL, NULL, NULL); +    return result; +} + +static int +ForPostNextCallback( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    ForIterData *iterPtr = data[0]; + +    if ((result != TCL_BREAK) && (result != TCL_OK)) { +	if (result == TCL_ERROR) { +	    Tcl_AddErrorInfo(interp, "\n    (\"for\" loop-end command)"); +	    TclSmallFreeEx(interp, iterPtr); +	} +	return result;      } +    TclNRAddCallback(interp, TclNRForIterCallback, iterPtr, NULL, NULL, NULL);      return result;  }  /*   *----------------------------------------------------------------------   * - * Tcl_ForeachObjCmd -- + * Tcl_ForeachObjCmd, TclNRForeachCmd, EachloopCmd --   *   *	This object-based procedure is invoked to process the "foreach" Tcl   *	command. See the user documentation for details on what it does. @@ -1656,42 +2884,57 @@ Tcl_ForObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_ForeachObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ -{ -    int result = TCL_OK; -    int i;			/* i selects a value list */ -    int j, maxj;		/* Number of loop iterations */ -    int v;			/* v selects a loop variable */ -    int numLists;		/* Count of value lists */ -    Tcl_Obj *bodyPtr; +Tcl_ForeachObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{ +    return Tcl_NRCallObjProc(interp, TclNRForeachCmd, dummy, objc, objv); +} -    /* -     * We copy the argument object pointers into a local array to avoid the -     * problem that "objv" might become invalid. It is a pointer into the -     * evaluation stack and that stack might be grown and reallocated if the -     * loop body requires a large amount of stack space. -     */ +int +TclNRForeachCmd( +    ClientData dummy, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    return EachloopCmd(interp, TCL_EACH_KEEP_NONE, objc, objv); +} -#define NUM_ARGS 9 -    Tcl_Obj *(argObjStorage[NUM_ARGS]); -    Tcl_Obj **argObjv = argObjStorage; +int +Tcl_LmapObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{ +    return Tcl_NRCallObjProc(interp, TclNRLmapCmd, dummy, objc, objv); +} -#define STATIC_LIST_SIZE 4 -    int indexArray[STATIC_LIST_SIZE]; -    int varcListArray[STATIC_LIST_SIZE]; -    Tcl_Obj **varvListArray[STATIC_LIST_SIZE]; -    int argcListArray[STATIC_LIST_SIZE]; -    Tcl_Obj **argvListArray[STATIC_LIST_SIZE]; +int +TclNRLmapCmd( +    ClientData dummy, +    Tcl_Interp *interp, +    int objc, +    Tcl_Obj *const objv[]) +{ +    return EachloopCmd(interp, TCL_EACH_COLLECT, objc, objv); +} -    int *index = indexArray;		/* Array of value list indices */ -    int *varcList = varcListArray;	/* # loop variables per list */ -    Tcl_Obj ***varvList = varvListArray;/* Array of var name lists */ -    int *argcList = argcListArray;	/* Array of value list sizes */ -    Tcl_Obj ***argvList = argvListArray;/* Array of value lists */ +static inline int +EachloopCmd( +    Tcl_Interp *interp,		/* Our context for variables and script +				 * evaluation. */ +    int collect,		/* Select collecting or accumulating mode +				 * (TCL_EACH_*) */ +    int objc,			/* The arguments being passed in... */ +    Tcl_Obj *const objv[]) +{ +    int numLists = (objc-2) / 2; +    register struct ForeachState *statePtr; +    int i, j, result;      if (objc < 4 || (objc%2 != 0)) {  	Tcl_WrongNumArgs(interp, 1, objv, @@ -1700,155 +2943,244 @@ Tcl_ForeachObjCmd(dummy, interp, objc, objv)      }      /* -     * Create the object argument array "argObjv". Make sure argObjv is large -     * enough to hold the objc arguments. -     */ - -    if (objc > NUM_ARGS) { -	argObjv = (Tcl_Obj **) ckalloc(objc * sizeof(Tcl_Obj *)); -    } -    for (i=0 ; i<objc ; i++) { -	argObjv[i] = objv[i]; -    } - -    /*       * Manage numList parallel value lists. -     * argvList[i] is a value list counted by argcList[i]l; -     * varvList[i] is the list of variables associated with the value list; -     * varcList[i] is the number of variables associated with the value list; -     * index[i] is the current pointer into the value list argvList[i]. +     * statePtr->argvList[i] is a value list counted by statePtr->argcList[i]; +     * statePtr->varvList[i] is the list of variables associated with the +     *		value list; +     * statePtr->varcList[i] is the number of variables associated with the +     *		value list; +     * statePtr->index[i] is the current pointer into the value list +     *		statePtr->argvList[i]. +     * +     * The setting up of all of these pointers is moderately messy, but allows +     * the rest of this code to be simple and for us to use a single memory +     * allocation for better performance.       */ -    numLists = (objc-2)/2; -    if (numLists > STATIC_LIST_SIZE) { -	index = (int *) ckalloc(numLists * sizeof(int)); -	varcList = (int *) ckalloc(numLists * sizeof(int)); -	varvList = (Tcl_Obj ***) ckalloc(numLists * sizeof(Tcl_Obj **)); -	argcList = (int *) ckalloc(numLists * sizeof(int)); -	argvList = (Tcl_Obj ***) ckalloc(numLists * sizeof(Tcl_Obj **)); -    } -    for (i = 0;  i < numLists;  i++) { -	index[i] = 0; -	varcList[i] = 0; -	varvList[i] = (Tcl_Obj **) NULL; -	argcList[i] = 0; -	argvList[i] = (Tcl_Obj **) NULL; +    statePtr = TclStackAlloc(interp, +	    sizeof(struct ForeachState) + 3 * numLists * sizeof(int) +	    + 2 * numLists * (sizeof(Tcl_Obj **) + sizeof(Tcl_Obj *))); +    memset(statePtr, 0, +	    sizeof(struct ForeachState) + 3 * numLists * sizeof(int) +	    + 2 * numLists * (sizeof(Tcl_Obj **) + sizeof(Tcl_Obj *))); +    statePtr->varvList = (Tcl_Obj ***) (statePtr + 1); +    statePtr->argvList = statePtr->varvList + numLists; +    statePtr->vCopyList = (Tcl_Obj **) (statePtr->argvList + numLists); +    statePtr->aCopyList = statePtr->vCopyList + numLists; +    statePtr->index = (int *) (statePtr->aCopyList + numLists); +    statePtr->varcList = statePtr->index + numLists; +    statePtr->argcList = statePtr->varcList + numLists; + +    statePtr->numLists = numLists; +    statePtr->bodyPtr = objv[objc - 1]; +    statePtr->bodyIdx = objc - 1; + +    if (collect == TCL_EACH_COLLECT) { +	statePtr->resultList = Tcl_NewListObj(0, NULL); +    } else { +	statePtr->resultList = NULL;      }      /*       * Break up the value lists and variable lists into elements.       */ -    maxj = 0;      for (i=0 ; i<numLists ; i++) { -	result = Tcl_ListObjGetElements(interp, argObjv[1+i*2], -		&varcList[i], &varvList[i]); -	if (result != TCL_OK) { +	statePtr->vCopyList[i] = TclListObjCopy(interp, objv[1+i*2]); +	if (statePtr->vCopyList[i] == NULL) { +	    result = TCL_ERROR;  	    goto done;  	} -	if (varcList[i] < 1) { -	    Tcl_AppendResult(interp, "foreach varlist is empty", NULL); +	TclListObjGetElements(NULL, statePtr->vCopyList[i], +		&statePtr->varcList[i], &statePtr->varvList[i]); +	if (statePtr->varcList[i] < 1) { +	    Tcl_SetObjResult(interp, Tcl_ObjPrintf( +		    "%s varlist is empty", +		    (statePtr->resultList != NULL ? "lmap" : "foreach"))); +	    Tcl_SetErrorCode(interp, "TCL", "OPERATION", +		    (statePtr->resultList != NULL ? "LMAP" : "FOREACH"), +		    "NEEDVARS", NULL);  	    result = TCL_ERROR;  	    goto done;  	} -	result = Tcl_ListObjGetElements(interp, argObjv[2+i*2], -		&argcList[i], &argvList[i]); -	if (result != TCL_OK) { +	statePtr->aCopyList[i] = TclListObjCopy(interp, objv[2+i*2]); +	if (statePtr->aCopyList[i] == NULL) { +	    result = TCL_ERROR;  	    goto done;  	} +	TclListObjGetElements(NULL, statePtr->aCopyList[i], +		&statePtr->argcList[i], &statePtr->argvList[i]); -	j = argcList[i] / varcList[i]; -	if ((argcList[i] % varcList[i]) != 0) { +	j = statePtr->argcList[i] / statePtr->varcList[i]; +	if ((statePtr->argcList[i] % statePtr->varcList[i]) != 0) {  	    j++;  	} -	if (j > maxj) { -	    maxj = j; +	if (j > statePtr->maxj) { +	    statePtr->maxj = j;  	}      }      /* -     * Iterate maxj times through the lists in parallel. If some value lists -     * run out of values, set loop vars to "" +     * If there is any work to do, assign the variables and set things going +     * non-recursively.       */ -    bodyPtr = argObjv[objc-1]; -    for (j=0 ; j<maxj ; j++) { -	for (i=0 ; i<numLists ; i++) { -	    /* -	     * Refetch the list members; we assume that the sizes are the -	     * same, but the array of elements might be different if the -	     * internal rep of the objects has been lost and recreated (it is -	     * too difficult to accurately tell when this happens, which can -	     * lead to some wierd crashes, like Bug #494348...) -	     */ - -	    result = Tcl_ListObjGetElements(interp, argObjv[1+i*2], -		    &varcList[i], &varvList[i]); -	    if (result != TCL_OK) { -		Tcl_Panic("Tcl_ForeachObjCmd: could not reconvert variable list %d to a list object\n", i); -	    } -	    result = Tcl_ListObjGetElements(interp, argObjv[2+i*2], -		    &argcList[i], &argvList[i]); -	    if (result != TCL_OK) { -		Tcl_Panic("Tcl_ForeachObjCmd: could not reconvert value list %d to a list object\n", i); -	    } +    if (statePtr->maxj > 0) { +	result = ForeachAssignments(interp, statePtr); +	if (result == TCL_ERROR) { +	    goto done; +	} -	    for (v=0 ; v<varcList[i] ; v++) { -		int k = index[i]++; -		Tcl_Obj *valuePtr, *varValuePtr; - -		if (k < argcList[i]) { -		    valuePtr = argvList[i][k]; -		} else { -		    valuePtr = Tcl_NewObj(); /* empty string */ -		} -		varValuePtr = Tcl_ObjSetVar2(interp, varvList[i][v], -			NULL, valuePtr, 0); -		if (varValuePtr == NULL) { -		    Tcl_ResetResult(interp); -		    Tcl_AppendResult(interp, "couldn't set loop variable: \"", -			    TclGetString(varvList[i][v]), "\"", (char *) NULL); -		    result = TCL_ERROR; -		    goto done; -		} -	    } +	TclNRAddCallback(interp, ForeachLoopStep, statePtr, NULL, NULL, NULL); +	return TclNREvalObjEx(interp, objv[objc-1], 0, +		((Interp *) interp)->cmdFramePtr, objc-1); +    } + +    /* +     * This cleanup stage is only used when an error occurs during setup or if +     * there is no work to do. +     */ + +    result = TCL_OK; +  done: +    ForeachCleanup(interp, statePtr); +    return result; +} + +/* + * Post-body processing handler. + */ + +static int +ForeachLoopStep( +    ClientData data[], +    Tcl_Interp *interp, +    int result) +{ +    register struct ForeachState *statePtr = data[0]; + +    /* +     * Process the result code from this run of the [foreach] body. Note that +     * this switch uses fallthroughs in several places. Maintainer aware! +     */ + +    switch (result) { +    case TCL_CONTINUE: +	result = TCL_OK; +	break; +    case TCL_OK: +	if (statePtr->resultList != NULL) { +	    Tcl_ListObjAppendElement(interp, statePtr->resultList, +		    Tcl_GetObjResult(interp));  	} +	break; +    case TCL_BREAK: +	result = TCL_OK; +	goto finish; +    case TCL_ERROR: +	Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf( +		"\n    (\"%s\" body line %d)", +		(statePtr->resultList != NULL ? "lmap" : "foreach"), +		Tcl_GetErrorLine(interp))); +    default: +	goto done; +    } -	result = Tcl_EvalObjEx(interp, bodyPtr, 0); -	if (result != TCL_OK) { -	    if (result == TCL_CONTINUE) { -		result = TCL_OK; -	    } else if (result == TCL_BREAK) { -		result = TCL_OK; -		break; -	    } else if (result == TCL_ERROR) { -		TclFormatToErrorInfo(interp, -			"\n    (\"foreach\" body line %d)", interp->errorLine); -		break; -	    } else { -		break; -	    } +    /* +     * Test if there is work still to be done. If so, do the next round of +     * variable assignments, reschedule ourselves and run the body again. +     */ + +    if (statePtr->maxj > ++statePtr->j) { +	result = ForeachAssignments(interp, statePtr); +	if (result == TCL_ERROR) { +	    goto done;  	} + +	TclNRAddCallback(interp, ForeachLoopStep, statePtr, NULL, NULL, NULL); +	return TclNREvalObjEx(interp, statePtr->bodyPtr, 0, +		((Interp *) interp)->cmdFramePtr, statePtr->bodyIdx);      } -    if (result == TCL_OK) { + +    /* +     * We're done. Tidy up our work space and finish off. +     */ + +  finish: +    if (statePtr->resultList == NULL) {  	Tcl_ResetResult(interp); +    } else { +	Tcl_SetObjResult(interp, statePtr->resultList); +	statePtr->resultList = NULL;	/* Don't clean it up */      }    done: -    if (numLists > STATIC_LIST_SIZE) { -	ckfree((char *) index); -	ckfree((char *) varcList); -	ckfree((char *) argcList); -	ckfree((char *) varvList); -	ckfree((char *) argvList); +    ForeachCleanup(interp, statePtr); +    return result; +} + +/* + * Factored out code to do the assignments in [foreach]. + */ + +static inline int +ForeachAssignments( +    Tcl_Interp *interp, +    struct ForeachState *statePtr) +{ +    int i, v, k; +    Tcl_Obj *valuePtr, *varValuePtr; + +    for (i=0 ; i<statePtr->numLists ; i++) { +	for (v=0 ; v<statePtr->varcList[i] ; v++) { +	    k = statePtr->index[i]++; + +	    if (k < statePtr->argcList[i]) { +		valuePtr = statePtr->argvList[i][k]; +	    } else { +		TclNewObj(valuePtr);	/* Empty string */ +	    } + +	    varValuePtr = Tcl_ObjSetVar2(interp, statePtr->varvList[i][v], +		    NULL, valuePtr, TCL_LEAVE_ERR_MSG); + +	    if (varValuePtr == NULL) { +		Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf( +			"\n    (setting %s loop variable \"%s\")", +			(statePtr->resultList != NULL ? "lmap" : "foreach"), +			TclGetString(statePtr->varvList[i][v]))); +		return TCL_ERROR; +	    } +	}      } -    if (argObjv != argObjStorage) { -	ckfree((char *) argObjv); + +    return TCL_OK; +} + +/* + * Factored out code for cleaning up the state of the foreach. + */ + +static inline void +ForeachCleanup( +    Tcl_Interp *interp, +    struct ForeachState *statePtr) +{ +    int i; + +    for (i=0 ; i<statePtr->numLists ; i++) { +	if (statePtr->vCopyList[i]) { +	    TclDecrRefCount(statePtr->vCopyList[i]); +	} +	if (statePtr->aCopyList[i]) { +	    TclDecrRefCount(statePtr->aCopyList[i]); +	}      } -    return result; -#undef STATIC_LIST_SIZE -#undef NUM_ARGS +    if (statePtr->resultList != NULL) { +	TclDecrRefCount(statePtr->resultList); +    } +    TclStackFree(interp, statePtr);  }  /* @@ -1870,511 +3202,25 @@ Tcl_ForeachObjCmd(dummy, interp, objc, objv)  	/* ARGSUSED */  int -Tcl_FormatObjCmd(dummy, interp, objc, objv) -    ClientData dummy;		/* Not used. */ -    Tcl_Interp *interp;		/* Current interpreter. */ -    int objc;			/* Number of arguments. */ -    Tcl_Obj *CONST objv[];	/* Argument objects. */ -{ -#ifndef NEW_FORMAT -    char *format;		/* Used to read characters from the format -				 * string. */ -    int formatLen;		/* The length of the format string */ -    char *endPtr;		/* Points to the last char in format array */ -    char newFormat[43];		/* A new format specifier is generated here. */ -    int width;			/* Field width from field specifier, or 0 if -				 * no width given. */ -    int precision;		/* Field precision from field specifier, or 0 -				 * if no precision given. */ -    int size;			/* Number of bytes needed for result of -				 * conversion, based on type of conversion -				 * ("e", "s", etc.), width, and precision. */ -    long intValue;		/* Used to hold value to pass to sprintf, if -				 * it's a one-word integer or char value */ -    char *ptrValue = NULL;	/* Used to hold value to pass to sprintf, if -				 * it's a one-word value. */ -    double doubleValue;		/* Used to hold value to pass to sprintf if -				 * it's a double value. */ -    Tcl_WideInt wideValue;	/* Used to hold value to pass to sprintf if -				 * it's a 'long long' value. */ -    int whichValue;		/* Indicates which of intValue, ptrValue, or -				 * doubleValue has the value to pass to -				 * sprintf, according to the following -				 * definitions: */ -#define INT_VALUE	0 -#define CHAR_VALUE	1 -#define PTR_VALUE	2 -#define DOUBLE_VALUE	3 -#define STRING_VALUE	4 -#define WIDE_VALUE	5 -#define MAX_FLOAT_SIZE	320 - -#endif +Tcl_FormatObjCmd( +    ClientData dummy,		/* Not used. */ +    Tcl_Interp *interp,		/* Current interpreter. */ +    int objc,			/* Number of arguments. */ +    Tcl_Obj *const objv[])	/* Argument objects. */ +{      Tcl_Obj *resultPtr;		/* Where result is stored finally. */ -#ifndef NEW_FORMAT -    char staticBuf[MAX_FLOAT_SIZE + 1]; -				/* A static buffer to copy the format results -				 * into */ -    char *dst = staticBuf;	/* The buffer that sprintf writes into each -				 * time the format processes a specifier */ -    int dstSize = MAX_FLOAT_SIZE; -				/* The size of the dst buffer */ -    int noPercent;		/* Special case for speed: indicates there's -				 * no field specifier, just a string to -				 * copy. */ -    int objIndex;		/* Index of argument to substitute next. */ -    int gotXpg = 0;		/* Non-zero means that an XPG3 %n$-style -				 * specifier has been seen. */ -    int gotSequential = 0;	/* Non-zero means that a regular sequential -				 * (non-XPG3) conversion specifier has been -				 * seen. */ -    int useShort;		/* Value to be printed is short (half word). */ -    char *end;			/* Used to locate end of numerical fields. */ -    int stringLen = 0;		/* Length of string in characters rather than -				 * bytes. Used for %s substitution. */ -    int gotMinus;		/* Non-zero indicates that a minus flag has -				 * been seen in the current field. */ -    int gotPrecision;		/* Non-zero indicates that a precision has -				 * been set for the current field. */ -    int gotZero;		/* Non-zero indicates that a zero flag has -				 * been seen in the current field. */ -    int useWide;		/* Value to be printed is Tcl_WideInt. */ - -    /* -     * This procedure is a bit nasty. The goal is to use sprintf to do most of -     * the dirty work. There are several problems: -     * 1. this procedure can't trust its arguments. -     * 2. we must be able to provide a large enough result area to hold -     *	  whatever's generated. This is hard to estimate. -     * 3. there's no way to move the arguments from objv to the call to -     *	  sprintf in a reasonable way. This is particularly nasty because -     *	  some of the arguments may be two-word values (doubles and -     *	  wide-ints). -     * So, what happens here is to scan the format string one % group at a -     * time, making many individual calls to sprintf. -     */ -#endif      if (objc < 2) { -	Tcl_WrongNumArgs(interp, 1, objv, "formatString ?arg arg ...?"); +	Tcl_WrongNumArgs(interp, 1, objv, "formatString ?arg ...?");  	return TCL_ERROR;      } -#ifdef NEW_FORMAT -    resultPtr = Tcl_NewObj(); -    Tcl_IncrRefCount(resultPtr); -    if (TclAppendFormattedObjs(interp, resultPtr, Tcl_GetString(objv[1]), -	    objc-2, objv+2) != TCL_OK) { -	Tcl_DecrRefCount(resultPtr); +    resultPtr = Tcl_Format(interp, TclGetString(objv[1]), objc-2, objv+2); +    if (resultPtr == NULL) {  	return TCL_ERROR;      }      Tcl_SetObjResult(interp, resultPtr); -    Tcl_DecrRefCount(resultPtr);      return TCL_OK; -#else -    format = Tcl_GetStringFromObj(objv[1], &formatLen); -    endPtr = format + formatLen; -    resultPtr = Tcl_NewObj(); -    objIndex = 2; - -    while (format < endPtr) { -	register char *newPtr = newFormat; - -	width = precision = noPercent = useShort = 0; -	gotZero = gotMinus = gotPrecision = 0; -	useWide = 0; -	whichValue = PTR_VALUE; - -	/* -	 * Get rid of any characters before the next field specifier. -	 */ - -	if (*format != '%') { -	    ptrValue = format; -	    while ((*format != '%') && (format < endPtr)) { -		format++; -	    } -	    size = format - ptrValue; -	    noPercent = 1; -	    goto doField; -	} - -	if (format[1] == '%') { -	    ptrValue = format; -	    size = 1; -	    noPercent = 1; -	    format += 2; -	    goto doField; -	} - -	/* -	 * Parse off a field specifier, compute how many characters will be -	 * needed to store the result, and substitute for "*" size specifiers. -	 */ - -	*newPtr = '%'; -	newPtr++; -	format++; -	if (isdigit(UCHAR(*format))) { /* INTL: Tcl source. */ -	    int tmp; - -	    /* -	     * Check for an XPG3-style %n$ specification. Note: there must not -	     * be a mixture of XPG3 specs and non-XPG3 specs in the same -	     * format string. -	     */ - -	    tmp = strtoul(format, &end, 10);	/* INTL: "C" locale. */ -	    if (*end != '$') { -		goto notXpg; -	    } -	    format = end+1; -	    gotXpg = 1; -	    if (gotSequential) { -		goto mixedXPG; -	    } -	    objIndex = tmp+1; -	    if ((objIndex < 2) || (objIndex >= objc)) { -		goto badIndex; -	    } -	    goto xpgCheckDone; -	} - -    notXpg: -	gotSequential = 1; -	if (gotXpg) { -	    goto mixedXPG; -	} - -    xpgCheckDone: -	while ((*format == '-') || (*format == '#') || (*format == '0') -		|| (*format == ' ') || (*format == '+')) { -	    if (*format == '-') { -		gotMinus = 1; -	    } -	    if (*format == '0') { -		/* -		 * This will be handled by sprintf for numbers, but we need to -		 * do the char/string ones ourselves. -		 */ - -		gotZero = 1; -	    } -	    *newPtr = *format; -	    newPtr++; -	    format++; -	} -	if (isdigit(UCHAR(*format))) {		/* INTL: Tcl source. */ -	    width = strtoul(format, &end, 10);	/* INTL: Tcl source. */ -	    format = end; -	} else if (*format == '*') { -	    if (objIndex >= objc) { -		goto badIndex; -	    } -	    if (Tcl_GetIntFromObj(interp,	/* INTL: Tcl source. */ -		    objv[objIndex], &width) != TCL_OK) { -		goto fmtError; -	    } -	    if (width < 0) { -		width = -width; -		*newPtr = '-'; -		gotMinus = 1; -		newPtr++; -	    } -	    objIndex++; -	    format++; -	} -	if (width > 100000) { -	    /* -	     * Don't allow arbitrarily large widths: could cause core dump -	     * when we try to allocate a zillion bytes of memory below. -	     */ - -	    width = 100000; -	} else if (width < 0) { -	    width = 0; -	} -	if (width != 0) { -	    TclFormatInt(newPtr, width);	/* INTL: printf format. */ -	    while (*newPtr != 0) { -		newPtr++; -	    } -	} -	if (*format == '.') { -	    *newPtr = '.'; -	    newPtr++; -	    format++; -	    gotPrecision = 1; -	} -	if (isdigit(UCHAR(*format))) {		/* INTL: Tcl source. */ -	    precision = strtoul(format, &end, 10);	/* INTL: "C" locale. */ -	    format = end; -	} else if (*format == '*') { -	    if (objIndex >= objc) { -		goto badIndex; -	    } -	    if (Tcl_GetIntFromObj(interp,	/* INTL: Tcl source. */ -		    objv[objIndex], &precision) != TCL_OK) { -		goto fmtError; -	    } -	    objIndex++; -	    format++; -	} -	if (gotPrecision) { -	    TclFormatInt(newPtr, precision);	/* INTL: printf format. */ -	    while (*newPtr != 0) { -		newPtr++; -	    } -	} -	if (*format == 'l') { -	    useWide = 1; - -	    /* -	     * Only add a 'll' modifier for integer values as it makes some -	     * libc's go into spasm otherwise. [Bug #702622] -	     */ - -	    switch (format[1]) { -	    case 'i': -	    case 'd': -	    case 'o': -	    case 'u': -	    case 'x': -	    case 'X': -		strcpy(newPtr, TCL_LL_MODIFIER); -		newPtr += TCL_LL_MODIFIER_SIZE; -	    } -	    format++; -	} else if (*format == 'h') { -	    useShort = 1; -	    *newPtr = 'h'; -	    newPtr++; -	    format++; -	} -	*newPtr = *format; -	newPtr++; -	*newPtr = 0; -	if (objIndex >= objc) { -	    goto badIndex; -	} -	switch (*format) { -	case 'i': -	    newPtr[-1] = 'd'; -	case 'd': -	case 'o': -	case 'u': -	case 'x': -	case 'X': -	    if (useWide) { -		if (Tcl_GetWideIntFromObj(interp,	/* INTL: Tcl source. */ -			objv[objIndex], &wideValue) != TCL_OK) { -		    goto fmtError; -		} -		whichValue = WIDE_VALUE; -		size = 40 + precision; -		break; -	    } -	    if (Tcl_GetLongFromObj(interp,	/* INTL: Tcl source. */ -		    objv[objIndex], &intValue) != TCL_OK) { -		goto fmtError; -	    } -#if (LONG_MAX > INT_MAX) -	    if (!useShort) { -		/* -		 * Add the 'l' for long format type because we are on an LP64 -		 * archtecture and we are really going to pass a long argument -		 * to sprintf. -		 * -		 * Do not add this if we're going to pass in a short (i.e. if -		 * we've got an 'h' modifier already in the string); some libc -		 * implementations of sprintf() do not like it at all. [Bug -		 * 1154163] -		 */ - -		newPtr++; -		*newPtr = 0; -		newPtr[-1] = newPtr[-2]; -		newPtr[-2] = 'l'; -	    } -#endif /* LONG_MAX > INT_MAX */ -	    whichValue = INT_VALUE; -	    size = 40 + precision; -	    break; -	case 's': -	    /* -	     * Compute the length of the string in characters and add any -	     * additional space required by the field width. All of the extra -	     * characters will be spaces, so one byte per character is -	     * adequate. -	     */ - -	    whichValue = STRING_VALUE; -	    ptrValue = Tcl_GetStringFromObj(objv[objIndex], &size); -	    stringLen = Tcl_NumUtfChars(ptrValue, size); -	    if (gotPrecision && (precision < stringLen)) { -		stringLen = precision; -	    } -	    size = Tcl_UtfAtIndex(ptrValue, stringLen) - ptrValue; -	    if (width > stringLen) { -		size += (width - stringLen); -	    } -	    break; -	case 'c': -	    if (Tcl_GetLongFromObj(interp,	/* INTL: Tcl source. */ -		    objv[objIndex], &intValue) != TCL_OK) { -		goto fmtError; -	    } -	    whichValue = CHAR_VALUE; -	    size = width + TCL_UTF_MAX; -	    break; -	case 'e': -	case 'E': -	case 'f': -	case 'g': -	case 'G': -	    if (Tcl_GetDoubleFromObj(interp,	/* INTL: Tcl source. */ -		    objv[objIndex], &doubleValue) != TCL_OK) { -		/*TODO: figure out ACCEPT_NAN */ -		goto fmtError; -	    } -	    whichValue = DOUBLE_VALUE; -	    size = MAX_FLOAT_SIZE; -	    if (precision > 10) { -		size += precision; -	    } -	    break; -	case 0: -	    Tcl_SetResult(interp, -		    "format string ended in middle of field specifier", -		    TCL_STATIC); -	    goto fmtError; -	default: -	{ -	    char buf[40]; - -	    sprintf(buf, "bad field specifier \"%c\"", *format); -	    Tcl_SetResult(interp, buf, TCL_VOLATILE); -	    goto fmtError; -	} -	} -	objIndex++; -	format++; - -	/* -	 * Make sure that there's enough space to hold the formatted result, -	 * then format it. -	 */ - -    doField: -	if (width > size) { -	    size = width; -	} -	if (noPercent) { -	    Tcl_AppendToObj(resultPtr, ptrValue, size); -	} else { -	    if (size > dstSize) { -		if (dst != staticBuf) { -		    ckfree(dst); -		} -		dst = (char *) ckalloc((unsigned) (size + 1)); -		dstSize = size; -	    } -	    switch (whichValue) { -	    case DOUBLE_VALUE: -		sprintf(dst, newFormat, doubleValue); /* INTL: user locale. */ -		break; -	    case WIDE_VALUE: -		sprintf(dst, newFormat, wideValue); -		break; -	    case INT_VALUE: -		if (useShort) { -		    sprintf(dst, newFormat, (short) intValue); -		} else { -		    sprintf(dst, newFormat, intValue); -		} -		break; -	    case CHAR_VALUE: { -		char *ptr; -		char padChar = (gotZero ? '0' : ' '); -		ptr = dst; -		if (!gotMinus) { -		    for ( ; --width > 0; ptr++) { -			*ptr = padChar; -		    } -		} -		ptr += Tcl_UniCharToUtf(intValue, ptr); -		for ( ; --width > 0; ptr++) { -		    *ptr = padChar; -		} -		*ptr = '\0'; -		break; -	    } -	    case STRING_VALUE: { -		char *ptr; -		char padChar = (gotZero ? '0' : ' '); -		int pad; - -		ptr = dst; -		if (width > stringLen) { -		    pad = width - stringLen; -		} else { -		    pad = 0; -		} - -		if (!gotMinus) { -		    while (pad > 0) { -			*ptr++ = padChar; -			pad--; -		    } -		} - -		size = Tcl_UtfAtIndex(ptrValue, stringLen) - ptrValue; -		if (size) { -		    memcpy(ptr, ptrValue, (size_t) size); -		    ptr += size; -		} -		while (pad > 0) { -		    *ptr++ = padChar; -		    pad--; -		} -		*ptr = '\0'; -		break; -	    } -	    default: -		sprintf(dst, newFormat, ptrValue); -		break; -	    } -	    Tcl_AppendToObj(resultPtr, dst, -1); -	} -    } - -    Tcl_SetObjResult(interp, resultPtr); -    if (dst != staticBuf) { -	ckfree(dst); -    } -    return TCL_OK; - -  mixedXPG: -    Tcl_SetResult(interp, -	    "cannot mix \"%\" and \"%n$\" conversion specifiers", TCL_STATIC); -    goto fmtError; - -  badIndex: -    if (gotXpg) { -	Tcl_SetResult(interp, -		"\"%n$\" argument index out of range", TCL_STATIC); -    } else { -	Tcl_SetResult(interp, -		"not enough arguments for all format specifiers", TCL_STATIC); -    } - -  fmtError: -    if (dst != staticBuf) { -	ckfree(dst); -    } -    Tcl_DecrRefCount(resultPtr); -    return TCL_ERROR; -#endif  }  /* | 
