Debian Codegraph @

pTk/mTk/tclGeneric/tclCmdAH.c

raw symbols SCIP
1 /*
2 * tclCmdAH.c --
3 *
4 * This file contains the top-level command routines for most of
5 * the Tcl built-in commands whose names begin with the letters
6 * A to H.
7 *
8 * Copyright (c) 1987-1993 The Regents of the University of California.
9 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
10 *
11 * See the file "license.terms" for information on usage and redistribution
12 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 *
14 * RCS: @(#) $Id: tclCmdAH.c,v 1.27.2.7 2003/10/22 08:21:15 dkf Exp $
15 */
16
17 #include "tclInt.h"
18 #include "tclPort.h"
19 #include <locale.h>
20
21 /*
22 * Prototypes for local procedures defined in this file:
23 */
24
25 static int CheckAccess _ANSI_ARGS_((Tcl_Interp *interp,
26 Tcl_Obj *objPtr, int mode));
27 static int GetStatBuf _ANSI_ARGS_((Tcl_Interp *interp,
28 Tcl_Obj *objPtr, Tcl_FSStatProc *statProc,
29 Tcl_StatBuf *statPtr));
30 static char * GetTypeFromMode _ANSI_ARGS_((int mode));
31 static int StoreStatData _ANSI_ARGS_((Tcl_Interp *interp,
32 char *varName, Tcl_StatBuf *statPtr));
33
34 /*
35 *----------------------------------------------------------------------
36 *
37 * Tcl_BreakObjCmd --
38 *
39 * This procedure is invoked to process the "break" Tcl command.
40 * See the user documentation for details on what it does.
41 *
42 * With the bytecode compiler, this procedure is only called when
43 * a command name is computed at runtime, and is "break" or the name
44 * to which "break" was renamed: e.g., "set z break; $z"
45 *
46 * Results:
47 * A standard Tcl result.
48 *
49 * Side effects:
50 * See the user documentation.
51 *
52 *----------------------------------------------------------------------
53 */
54
55 /* ARGSUSED */
56 int
57 Tcl_BreakObjCmd(dummy, interp, objc, objv)
58 ClientData dummy; /* Not used. */
59 Tcl_Interp *interp; /* Current interpreter. */
60 int objc; /* Number of arguments. */
61 Tcl_Obj *CONST objv[]; /* Argument objects. */
62 {
63 if (objc != 1) {
64 Tcl_WrongNumArgs(interp, 1, objv, NULL);
65 return TCL_ERROR;
66 }
67 return TCL_BREAK;
68 }
69
70 /*
71 *----------------------------------------------------------------------
72 *
73 * Tcl_CaseObjCmd --
74 *
75 * This procedure is invoked to process the "case" Tcl command.
76 * See the user documentation for details on what it does.
77 *
78 * Results:
79 * A standard Tcl object result.
80 *
81 * Side effects:
82 * See the user documentation.
83 *
84 *----------------------------------------------------------------------
85 */
86
87 /* ARGSUSED */
88 int
89 Tcl_CaseObjCmd(dummy, interp, objc, objv)
90 ClientData dummy; /* Not used. */
91 Tcl_Interp *interp; /* Current interpreter. */
92 int objc; /* Number of arguments. */
93 Tcl_Obj *CONST objv[]; /* Argument objects. */
94 {
95 register int i;
96 int body, result, caseObjc;
97 char *string, *arg;
98 Tcl_Obj *CONST *caseObjv;
99 Tcl_Obj *armPtr;
100
101 if (objc < 3) {
102 Tcl_WrongNumArgs(interp, 1, objv,
103 "string ?in? patList body ... ?default body?");
104 return TCL_ERROR;
105 }
106
107 string = Tcl_GetString(objv[1]);
108 body = -1;
109
110 arg = Tcl_GetString(objv[2]);
111 if (strcmp(arg, "in") == 0) {
112 i = 3;
113 } else {
114 i = 2;
115 }
116 caseObjc = objc - i;
117 caseObjv = objv + i;
118
119 /*
120 * If all of the pattern/command pairs are lumped into a single
121 * argument, split them out again.
122 */
123
124 if (caseObjc == 1) {
125 Tcl_Obj **newObjv;
126
127 Tcl_ListObjGetElements(interp, caseObjv[0], &caseObjc, &newObjv);
128 caseObjv = newObjv;
129 }
130
131 for (i = 0; i < caseObjc; i += 2) {
132 int patObjc, j;
133 CONST char **patObjv;
134 char *pat;
135 unsigned char *p;
136
137 if (i == (caseObjc - 1)) {
138 Tcl_ResetResult(interp);
139 Tcl_AppendToObj(Tcl_GetObjResult(interp),
140 "extra case pattern with no body", -1);
141 return TCL_ERROR;
142 }
143
144 /*
145 * Check for special case of single pattern (no list) with
146 * no backslash sequences.
147 */
148
149 pat = Tcl_GetString(caseObjv[i]);
150 for (p = (unsigned char *) pat; *p != '\0'; p++) {
151 if (isspace(*p) || (*p == '\\')) { /* INTL: ISO space, UCHAR */
152 break;
153 }
154 }
155 if (*p == '\0') {
156 if ((*pat == 'd') && (strcmp(pat, "default") == 0)) {
157 body = i + 1;
158 }
159 if (Tcl_StringMatch(string, pat)) {
160 body = i + 1;
161 goto match;
162 }
163 continue;
164 }
165
166
167 /*
168 * Break up pattern lists, then check each of the patterns
169 * in the list.
170 */
171
172 result = Tcl_SplitList(interp, pat, &patObjc, &patObjv);
173 if (result != TCL_OK) {
174 return result;
175 }
176 for (j = 0; j < patObjc; j++) {
177 if (Tcl_StringMatch(string, patObjv[j])) {
178 body = i + 1;
179 break;
180 }
181 }
182 ckfree((char *) patObjv);
183 if (j < patObjc) {
184 break;
185 }
186 }
187
188 match:
189 if (body != -1) {
190 armPtr = caseObjv[body - 1];
191 result = Tcl_EvalObjEx(interp, caseObjv[body], 0);
192 if (result == TCL_ERROR) {
193 char msg[100 + TCL_INTEGER_SPACE];
194
195 arg = Tcl_GetString(armPtr);
196 sprintf(msg,
197 "\n (\"%.50s\" arm line %d)", arg,
198 interp->errorLine);
199 Tcl_AddObjErrorInfo(interp, msg, -1);
200 }
201 return result;
202 }
203
204 /*
205 * Nothing matched: return nothing.
206 */
207
208 return TCL_OK;
209 }
210
211 /*
212 *----------------------------------------------------------------------
213 *
214 * Tcl_CatchObjCmd --
215 *
216 * This object-based procedure is invoked to process the "catch" Tcl
217 * command. See the user documentation for details on what it does.
218 *
219 * Results:
220 * A standard Tcl object result.
221 *
222 * Side effects:
223 * See the user documentation.
224 *
225 *----------------------------------------------------------------------
226 */
227
228 /* ARGSUSED */
229 int
230 Tcl_CatchObjCmd(dummy, interp, objc, objv)
231 ClientData dummy; /* Not used. */
232 Tcl_Interp *interp; /* Current interpreter. */
233 int objc; /* Number of arguments. */
234 Tcl_Obj *CONST objv[]; /* Argument objects. */
235 {
236 Tcl_Obj *varNamePtr = NULL;
237 int result;
238
239 if ((objc != 2) && (objc != 3)) {
240 Tcl_WrongNumArgs(interp, 1, objv, "command ?varName?");
241 return TCL_ERROR;
242 }
243
244 /*
245 * Save a pointer to the variable name object, if any, in case the
246 * Tcl_EvalObj reallocates the bytecode interpreter's evaluation
247 * stack rendering objv invalid.
248 */
249
250 if (objc == 3) {
251 varNamePtr = objv[2];
252 }
253
254 result = Tcl_EvalObjEx(interp, objv[1], 0);
255
256 if (objc == 3) {
257 if (Tcl_ObjSetVar2(interp, varNamePtr, NULL,
258 Tcl_GetObjResult(interp), 0) == NULL) {
259 Tcl_ResetResult(interp);
260 Tcl_AppendToObj(Tcl_GetObjResult(interp),
261 "couldn't save command result in variable", -1);
262 return TCL_ERROR;
263 }
264 }
265
266 /*
267 * Set the interpreter's object result to an integer object holding the
268 * integer Tcl_EvalObj result. Note that we don't bother generating a
269 * string representation. We reset the interpreter's object result
270 * to an unshared empty object and then set it to be an integer object.
271 */
272
273 Tcl_ResetResult(interp);
274 Tcl_SetIntObj(Tcl_GetObjResult(interp), result);
275 return TCL_OK;
276 }
277
278 /*
279 *----------------------------------------------------------------------
280 *
281 * Tcl_CdObjCmd --
282 *
283 * This procedure is invoked to process the "cd" Tcl command.
284 * See the user documentation for details on what it does.
285 *
286 * Results:
287 * A standard Tcl result.
288 *
289 * Side effects:
290 * See the user documentation.
291 *
292 *----------------------------------------------------------------------
293 */
294
295 /* ARGSUSED */
296 int
297 Tcl_CdObjCmd(dummy, interp, objc, objv)
298 ClientData dummy; /* Not used. */
299 Tcl_Interp *interp; /* Current interpreter. */
300 int objc; /* Number of arguments. */
301 Tcl_Obj *CONST objv[]; /* Argument objects. */
302 {
303 Tcl_Obj *dir;
304 int result;
305
306 if (objc > 2) {
307 Tcl_WrongNumArgs(interp, 1, objv, "?dirName?");
308 return TCL_ERROR;
309 }
310
311 if (objc == 2) {
312 dir = objv[1];
313 } else {
314 dir = Tcl_NewStringObj("~",1);
315 Tcl_IncrRefCount(dir);
316 }
317 if (Tcl_FSConvertToPathType(interp, dir) != TCL_OK) {
318 result = TCL_ERROR;
319 } else {
320 result = Tcl_FSChdir(dir);
321 if (result != TCL_OK) {
322 Tcl_AppendResult(interp, "couldn't change working directory to \"",
323 Tcl_GetString(dir), "\": ", Tcl_PosixError(interp), (char *) NULL);
324 result = TCL_ERROR;
325 }
326 }
327 if (objc != 2) {
328 Tcl_DecrRefCount(dir);
329 }
330 return result;
331 }
332
333 /*
334 *----------------------------------------------------------------------
335 *
336 * Tcl_ConcatObjCmd --
337 *
338 * This object-based procedure is invoked to process the "concat" Tcl
339 * command. See the user documentation for details on what it does.
340 *
341 * Results:
342 * A standard Tcl object result.
343 *
344 * Side effects:
345 * See the user documentation.
346 *
347 *----------------------------------------------------------------------
348 */
349
350 /* ARGSUSED */
351 int
352 Tcl_ConcatObjCmd(dummy, interp, objc, objv)
353 ClientData dummy; /* Not used. */
354 Tcl_Interp *interp; /* Current interpreter. */
355 int objc; /* Number of arguments. */
356 Tcl_Obj *CONST objv[]; /* Argument objects. */
357 {
358 if (objc >= 2) {
359 Tcl_SetObjResult(interp, Tcl_ConcatObj(objc-1, objv+1));
360 }
361 return TCL_OK;
362 }
363
364 /*
365 *----------------------------------------------------------------------
366 *
367 * Tcl_ContinueObjCmd -
368 *
369 * This procedure is invoked to process the "continue" Tcl command.
370 * See the user documentation for details on what it does.
371 *
372 * With the bytecode compiler, this procedure is only called when
373 * a command name is computed at runtime, and is "continue" or the name
374 * to which "continue" was renamed: e.g., "set z continue; $z"
375 *
376 * Results:
377 * A standard Tcl result.
378 *
379 * Side effects:
380 * See the user documentation.
381 *
382 *----------------------------------------------------------------------
383 */
384
385 /* ARGSUSED */
386 int
387 Tcl_ContinueObjCmd(dummy, interp, objc, objv)
388 ClientData dummy; /* Not used. */
389 Tcl_Interp *interp; /* Current interpreter. */
390 int objc; /* Number of arguments. */
391 Tcl_Obj *CONST objv[]; /* Argument objects. */
392 {
393 if (objc != 1) {
394 Tcl_WrongNumArgs(interp, 1, objv, NULL);
395 return TCL_ERROR;
396 }
397 return TCL_CONTINUE;
398 }
399
400 /*
401 *----------------------------------------------------------------------
402 *
403 * Tcl_EncodingObjCmd --
404 *
405 * This command manipulates encodings.
406 *
407 * Results:
408 * A standard Tcl result.
409 *
410 * Side effects:
411 * See the user documentation.
412 *
413 *----------------------------------------------------------------------
414 */
415
416 int
417 Tcl_EncodingObjCmd(dummy, interp, objc, objv)
418 ClientData dummy; /* Not used. */
419 Tcl_Interp *interp; /* Current interpreter. */
420 int objc; /* Number of arguments. */
421 Tcl_Obj *CONST objv[]; /* Argument objects. */
422 {
423 int index, length;
424 Tcl_Encoding encoding;
425 char *string;
426 Tcl_DString ds;
427 Tcl_Obj *resultPtr;
428
429 static CONST char *optionStrings[] = {
430 "convertfrom", "convertto", "names", "system",
431 NULL
432 };
433 enum options {
434 ENC_CONVERTFROM, ENC_CONVERTTO, ENC_NAMES, ENC_SYSTEM
435 };
436
437 if (objc < 2) {
438 Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
439 return TCL_ERROR;
440 }
441 if (Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0,
442 &index) != TCL_OK) {
443 return TCL_ERROR;
444 }
445
446 switch ((enum options) index) {
447 case ENC_CONVERTTO:
448 case ENC_CONVERTFROM: {
449 char *name;
450 Tcl_Obj *data;
451 if (objc == 3) {
452 name = NULL;
453 data = objv[2];
454 } else if (objc == 4) {
455 name = Tcl_GetString(objv[2]);
456 data = objv[3];
457 } else {
458 Tcl_WrongNumArgs(interp, 2, objv, "?encoding? data");
459 return TCL_ERROR;
460 }
461
462 encoding = Tcl_GetEncoding(interp, name);
463 if (!encoding) {
464 return TCL_ERROR;
465 }
466
467 if ((enum options) index == ENC_CONVERTFROM) {
468 /*
469 * Treat the string as binary data.
470 */
471
472 string = (char *) Tcl_GetByteArrayFromObj(data, &length);
473 Tcl_ExternalToUtfDString(encoding, string, length, &ds);
474
475 /*
476 * Note that we cannot use Tcl_DStringResult here because
477 * it will truncate the string at the first null byte.
478 */
479
480 Tcl_SetStringObj(Tcl_GetObjResult(interp),
481 Tcl_DStringValue(&ds), Tcl_DStringLength(&ds));
482 Tcl_DStringFree(&ds);
483 } else {
484 /*
485 * Store the result as binary data.
486 */
487
488 string = Tcl_GetStringFromObj(data, &length);
489 Tcl_UtfToExternalDString(encoding, string, length, &ds);
490 resultPtr = Tcl_GetObjResult(interp);
491 Tcl_SetByteArrayObj(resultPtr,
492 (unsigned char *) Tcl_DStringValue(&ds),
493 Tcl_DStringLength(&ds));
494 Tcl_DStringFree(&ds);
495 }
496
497 Tcl_FreeEncoding(encoding);
498 break;
499 }
500 case ENC_NAMES: {
501 if (objc > 2) {
502 Tcl_WrongNumArgs(interp, 2, objv, NULL);
503 return TCL_ERROR;
504 }
505 Tcl_GetEncodingNames(interp);
506 break;
507 }
508 case ENC_SYSTEM: {
509 if (objc > 3) {
510 Tcl_WrongNumArgs(interp, 2, objv, "?encoding?");
511 return TCL_ERROR;
512 }
513 if (objc == 2) {
514 Tcl_SetStringObj(Tcl_GetObjResult(interp),
515 Tcl_GetEncodingName(NULL), -1);
516 } else {
517 return Tcl_SetSystemEncoding(interp,
518 Tcl_GetStringFromObj(objv[2], NULL));
519 }
520 break;
521 }
522 }
523 return TCL_OK;
524 }
525
526 /*
527 *----------------------------------------------------------------------
528 *
529 * Tcl_ErrorObjCmd --
530 *
531 * This procedure is invoked to process the "error" Tcl command.
532 * See the user documentation for details on what it does.
533 *
534 * Results:
535 * A standard Tcl object result.
536 *
537 * Side effects:
538 * See the user documentation.
539 *
540 *----------------------------------------------------------------------
541 */
542
543 /* ARGSUSED */
544 int
545 Tcl_ErrorObjCmd(dummy, interp, objc, objv)
546 ClientData dummy; /* Not used. */
547 Tcl_Interp *interp; /* Current interpreter. */
548 int objc; /* Number of arguments. */
549 Tcl_Obj *CONST objv[]; /* Argument objects. */
550 {
551 Interp *iPtr = (Interp *) interp;
552 char *info;
553 int infoLen;
554
555 if ((objc < 2) || (objc > 4)) {
556 Tcl_WrongNumArgs(interp, 1, objv, "message ?errorInfo? ?errorCode?");
557 return TCL_ERROR;
558 }
559
560 if (objc >= 3) { /* process the optional info argument */
561 info = Tcl_GetStringFromObj(objv[2], &infoLen);
562 if (infoLen > 0) {
563 Tcl_AddObjErrorInfo(interp, info, infoLen);
564 iPtr->flags |= ERR_ALREADY_LOGGED;
565 }
566 }
567
568 if (objc == 4) {
569 Tcl_SetVar2Ex(interp, "errorCode", NULL, objv[3], TCL_GLOBAL_ONLY);
570 iPtr->flags |= ERROR_CODE_SET;
571 }
572
573 Tcl_SetObjResult(interp, objv[1]);
574 return TCL_ERROR;
575 }
576
577 /*
578 *----------------------------------------------------------------------
579 *
580 * Tcl_EvalObjCmd --
581 *
582 * This object-based procedure is invoked to process the "eval" Tcl
583 * command. See the user documentation for details on what it does.
584 *
585 * Results:
586 * A standard Tcl object result.
587 *
588 * Side effects:
589 * See the user documentation.
590 *
591 *----------------------------------------------------------------------
592 */
593
594 /* ARGSUSED */
595 int
596 Tcl_EvalObjCmd(dummy, interp, objc, objv)
597 ClientData dummy; /* Not used. */
598 Tcl_Interp *interp; /* Current interpreter. */
599 int objc; /* Number of arguments. */
600 Tcl_Obj *CONST objv[]; /* Argument objects. */
601 {
602 int result;
603 register Tcl_Obj *objPtr;
604
605 if (objc < 2) {
606 Tcl_WrongNumArgs(interp, 1, objv, "arg ?arg ...?");
607 return TCL_ERROR;
608 }
609
610 if (objc == 2) {
611 result = Tcl_EvalObjEx(interp, objv[1], TCL_EVAL_DIRECT);
612 } else {
613 /*
614 * More than one argument: concatenate them together with spaces
615 * between, then evaluate the result. Tcl_EvalObjEx will delete
616 * the object when it decrements its refcount after eval'ing it.
617 */
618 objPtr = Tcl_ConcatObj(objc-1, objv+1);
619 result = Tcl_EvalObjEx(interp, objPtr, TCL_EVAL_DIRECT);
620 }
621 if (result == TCL_ERROR) {
622 char msg[32 + TCL_INTEGER_SPACE];
623
624 sprintf(msg, "\n (\"eval\" body line %d)", interp->errorLine);
625 Tcl_AddObjErrorInfo(interp, msg, -1);
626 }
627 return result;
628 }
629
630 /*
631 *----------------------------------------------------------------------
632 *
633 * Tcl_ExitObjCmd --
634 *
635 * This procedure is invoked to process the "exit" Tcl command.
636 * See the user documentation for details on what it does.
637 *
638 * Results:
639 * A standard Tcl object result.
640 *
641 * Side effects:
642 * See the user documentation.
643 *
644 *----------------------------------------------------------------------
645 */
646
647 /* ARGSUSED */
648 int
649 Tcl_ExitObjCmd(dummy, interp, objc, objv)
650 ClientData dummy; /* Not used. */
651 Tcl_Interp *interp; /* Current interpreter. */
652 int objc; /* Number of arguments. */
653 Tcl_Obj *CONST objv[]; /* Argument objects. */
654 {
655 int value;
656
657 if ((objc != 1) && (objc != 2)) {
658 Tcl_WrongNumArgs(interp, 1, objv, "?returnCode?");
659 return TCL_ERROR;
660 }
661
662 if (objc == 1) {
663 value = 0;
664 } else if (Tcl_GetIntFromObj(interp, objv[1], &value) != TCL_OK) {
665 return TCL_ERROR;
666 }
667 Tcl_Exit(value);
668 /*NOTREACHED*/
669 return TCL_OK; /* Better not ever reach this! */
670 }
671
672 /*
673 *----------------------------------------------------------------------
674 *
675 * Tcl_ExprObjCmd --
676 *
677 * This object-based procedure is invoked to process the "expr" Tcl
678 * command. See the user documentation for details on what it does.
679 *
680 * With the bytecode compiler, this procedure is called in two
681 * circumstances: 1) to execute expr commands that are too complicated
682 * or too unsafe to try compiling directly into an inline sequence of
683 * instructions, and 2) to execute commands where the command name is
684 * computed at runtime and is "expr" or the name to which "expr" was
685 * renamed (e.g., "set z expr; $z 2+3")
686 *
687 * Results:
688 * A standard Tcl object result.
689 *
690 * Side effects:
691 * See the user documentation.
692 *
693 *----------------------------------------------------------------------
694 */
695
696 /* ARGSUSED */
697 int
698 Tcl_ExprObjCmd(dummy, interp, objc, objv)
699 ClientData dummy; /* Not used. */
700 Tcl_Interp *interp; /* Current interpreter. */
701 int objc; /* Number of arguments. */
702 Tcl_Obj *CONST objv[]; /* Argument objects. */
703 {
704 register Tcl_Obj *objPtr;
705 Tcl_Obj *resultPtr;
706 register char *bytes;
707 int length, i, result;
708
709 if (objc < 2) {
710 Tcl_WrongNumArgs(interp, 1, objv, "arg ?arg ...?");
711 return TCL_ERROR;
712 }
713
714 if (objc == 2) {
715 result = Tcl_ExprObj(interp, objv[1], &resultPtr);
716 if (result == TCL_OK) {
717 Tcl_SetObjResult(interp, resultPtr);
718 Tcl_DecrRefCount(resultPtr); /* done with the result object */
719 }
720 return result;
721 }
722
723 /*
724 * Create a new object holding the concatenated argument strings.
725 */
726
727 /*** QUESTION: Do we need to copy the slow way? ***/
728 bytes = Tcl_GetStringFromObj(objv[1], &length);
729 objPtr = Tcl_NewStringObj(bytes, length);
730 Tcl_IncrRefCount(objPtr);
731 for (i = 2; i < objc; i++) {
732 Tcl_AppendToObj(objPtr, " ", 1);
733 bytes = Tcl_GetStringFromObj(objv[i], &length);
734 Tcl_AppendToObj(objPtr, bytes, length);
735 }
736
737 /*
738 * Evaluate the concatenated string object.
739 */
740
741 result = Tcl_ExprObj(interp, objPtr, &resultPtr);
742 if (result == TCL_OK) {
743 Tcl_SetObjResult(interp, resultPtr);
744 Tcl_DecrRefCount(resultPtr); /* done with the result object */
745 }
746
747 /*
748 * Free allocated resources.
749 */
750
751 Tcl_DecrRefCount(objPtr);
752 return result;
753 }
754
755 /*
756 *----------------------------------------------------------------------
757 *
758 * Tcl_FileObjCmd --
759 *
760 * This procedure is invoked to process the "file" Tcl command.
761 * See the user documentation for details on what it does.
762 * PLEASE NOTE THAT THIS FAILS WITH FILENAMES AND PATHS WITH
763 * EMBEDDED NULLS, WHICH COULD THEORETICALLY HAPPEN ON A MAC.
764 * With the object-based Tcl_FS APIs, the above NOTE may no
765 * longer be true. In any case this assertion should be tested.
766 *
767 * Results:
768 * A standard Tcl result.
769 *
770 * Side effects:
771 * See the user documentation.
772 *
773 *----------------------------------------------------------------------
774 */
775
776 /* ARGSUSED */
777 int
778 Tcl_FileObjCmd(dummy, interp, objc, objv)
779 ClientData dummy; /* Not used. */
780 Tcl_Interp *interp; /* Current interpreter. */
781 int objc; /* Number of arguments. */
782 Tcl_Obj *CONST objv[]; /* Argument objects. */
783 {
784 int index;
785
786 /*
787 * This list of constants should match the fileOption string array below.
788 */
789
790 static CONST char *fileOptions[] = {
791 "atime", "attributes", "channels", "copy",
792 "delete",
793 "dirname", "executable", "exists", "extension",
794 "isdirectory", "isfile", "join", "link",
795 "lstat", "mtime", "mkdir", "nativename",
796 "normalize", "owned",
797 "pathtype", "readable", "readlink", "rename",
798 "rootname", "separator", "size", "split",
799 "stat", "system",
800 "tail", "type", "volumes", "writable",
801 (char *) NULL
802 };
803 enum options {
804 FCMD_ATIME, FCMD_ATTRIBUTES, FCMD_CHANNELS, FCMD_COPY,
805 FCMD_DELETE,
806 FCMD_DIRNAME, FCMD_EXECUTABLE, FCMD_EXISTS, FCMD_EXTENSION,
807 FCMD_ISDIRECTORY, FCMD_ISFILE, FCMD_JOIN, FCMD_LINK,
808 FCMD_LSTAT, FCMD_MTIME, FCMD_MKDIR, FCMD_NATIVENAME,
809 FCMD_NORMALIZE, FCMD_OWNED,
810 FCMD_PATHTYPE, FCMD_READABLE, FCMD_READLINK, FCMD_RENAME,
811 FCMD_ROOTNAME, FCMD_SEPARATOR, FCMD_SIZE, FCMD_SPLIT,
812 FCMD_STAT, FCMD_SYSTEM,
813 FCMD_TAIL, FCMD_TYPE, FCMD_VOLUMES, FCMD_WRITABLE
814 };
815
816 if (objc < 2) {
817 Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
818 return TCL_ERROR;
819 }
820 if (Tcl_GetIndexFromObj(interp, objv[1], fileOptions, "option", 0,
821 &index) != TCL_OK) {
822 return TCL_ERROR;
823 }
824
825 switch ((enum options) index) {
826 case FCMD_ATIME: {
827 Tcl_StatBuf buf;
828 struct utimbuf tval;
829
830 if ((objc < 3) || (objc > 4)) {
831 Tcl_WrongNumArgs(interp, 2, objv, "name ?time?");
832 return TCL_ERROR;
833 }
834 if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) {
835 return TCL_ERROR;
836 }
837 if (objc == 4) {
838 long newTime;
839
840 if (Tcl_GetLongFromObj(interp, objv[3], &newTime) != TCL_OK) {
841 return TCL_ERROR;
842 }
843 tval.actime = newTime;
844 tval.modtime = buf.st_mtime;
845 if (Tcl_FSUtime(objv[2], &tval) != 0) {
846 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
847 "could not set access time for file \"",
848 Tcl_GetString(objv[2]), "\": ",
849 Tcl_PosixError(interp), (char *) NULL);
850 return TCL_ERROR;
851 }
852 /*
853 * Do another stat to ensure that the we return the
854 * new recognized atime - hopefully the same as the
855 * one we sent in. However, fs's like FAT don't
856 * even know what atime is.
857 */
858 if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) {
859 return TCL_ERROR;
860 }
861 }
862 Tcl_SetLongObj(Tcl_GetObjResult(interp), (long) buf.st_atime);
863 return TCL_OK;
864 }
865 case FCMD_ATTRIBUTES: {
866 return TclFileAttrsCmd(interp, objc, objv);
867 }
868 case FCMD_CHANNELS: {
869 if ((objc < 2) || (objc > 3)) {
870 Tcl_WrongNumArgs(interp, 2, objv, "?pattern?");
871 return TCL_ERROR;
872 }
873 return Tcl_GetChannelNamesEx(interp,
874 ((objc == 2) ? NULL : Tcl_GetString(objv[2])));
875 }
876 case FCMD_COPY: {
877 return TclFileCopyCmd(interp, objc, objv);
878 }
879 case FCMD_DELETE: {
880 return TclFileDeleteCmd(interp, objc, objv);
881 }
882 case FCMD_DIRNAME: {
883 Tcl_Obj *dirPtr;
884 if (objc != 3) {
885 goto only3Args;
886 }
887 dirPtr = TclFileDirname(interp, objv[2]);
888 if (dirPtr == NULL) {
889 return TCL_ERROR;
890 } else {
891 Tcl_SetObjResult(interp, dirPtr);
892 Tcl_DecrRefCount(dirPtr);
893 return TCL_OK;
894 }
895 }
896 case FCMD_EXECUTABLE: {
897 if (objc != 3) {
898 goto only3Args;
899 }
900 return CheckAccess(interp, objv[2], X_OK);
901 }
902 case FCMD_EXISTS: {
903 if (objc != 3) {
904 goto only3Args;
905 }
906 return CheckAccess(interp, objv[2], F_OK);
907 }
908 case FCMD_EXTENSION: {
909 char *fileName, *extension;
910 if (objc != 3) {
911 goto only3Args;
912 }
913 fileName = Tcl_GetString(objv[2]);
914 extension = TclGetExtension(fileName);
915 if (extension != NULL) {
916 Tcl_SetStringObj(Tcl_GetObjResult(interp), extension, -1);
917 }
918 return TCL_OK;
919 }
920 case FCMD_ISDIRECTORY: {
921 int value;
922 Tcl_StatBuf buf;
923
924 if (objc != 3) {
925 goto only3Args;
926 }
927 value = 0;
928 if (GetStatBuf(NULL, objv[2], Tcl_FSStat, &buf) == TCL_OK) {
929 value = S_ISDIR(buf.st_mode);
930 }
931 Tcl_SetBooleanObj(Tcl_GetObjResult(interp), value);
932 return TCL_OK;
933 }
934 case FCMD_ISFILE: {
935 int value;
936 Tcl_StatBuf buf;
937
938 if (objc != 3) {
939 goto only3Args;
940 }
941 value = 0;
942 if (GetStatBuf(NULL, objv[2], Tcl_FSStat, &buf) == TCL_OK) {
943 value = S_ISREG(buf.st_mode);
944 }
945 Tcl_SetBooleanObj(Tcl_GetObjResult(interp), value);
946 return TCL_OK;
947 }
948 case FCMD_JOIN: {
949 Tcl_Obj *resObj;
950
951 if (objc < 3) {
952 Tcl_WrongNumArgs(interp, 2, objv, "name ?name ...?");
953 return TCL_ERROR;
954 }
955 resObj = Tcl_FSJoinToPath(NULL, objc - 2, objv + 2);
956 Tcl_SetObjResult(interp, resObj);
957 return TCL_OK;
958 }
959 case FCMD_LINK: {
960 Tcl_Obj *contents;
961 int index;
962
963 if (objc < 3 || objc > 5) {
964 Tcl_WrongNumArgs(interp, 2, objv,
965 "?-linktype? linkname ?target?");
966 return TCL_ERROR;
967 }
968
969 /* Index of the 'source' argument */
970 if (objc == 5) {
971 index = 3;
972 } else {
973 index = 2;
974 }
975
976 if (objc > 3) {
977 int linkAction;
978 if (objc == 5) {
979 /* We have a '-linktype' argument */
980 static CONST char *linkTypes[] = {
981 "-symbolic", "-hard", NULL
982 };
983 if (Tcl_GetIndexFromObj(interp, objv[2], linkTypes,
984 "switch", 0, &linkAction) != TCL_OK) {
985 return TCL_ERROR;
986 }
987 if (linkAction == 0) {
988 linkAction = TCL_CREATE_SYMBOLIC_LINK;
989 } else {
990 linkAction = TCL_CREATE_HARD_LINK;
991 }
992 } else {
993 linkAction = TCL_CREATE_SYMBOLIC_LINK|TCL_CREATE_HARD_LINK;
994 }
995 if (Tcl_FSConvertToPathType(interp, objv[index]) != TCL_OK) {
996 return TCL_ERROR;
997 }
998 /* Create link from source to target */
999 contents = Tcl_FSLink(objv[index], objv[index+1], linkAction);
1000 if (contents == NULL) {
1001 /*
1002 * We handle two common error cases specially, and
1003 * for all other errors, we use the standard posix
1004 * error message.
1005 */
1006 if (errno == EEXIST) {
1007 Tcl_AppendResult(interp, "could not create new link \"",
1008 Tcl_GetString(objv[index]),
1009 "\": that path already exists", (char *) NULL);
1010 } else if (errno == ENOENT) {
1011 Tcl_AppendResult(interp, "could not create new link \"",
1012 Tcl_GetString(objv[index]),
1013 "\" since target \"",
1014 Tcl_GetString(objv[index+1]),
1015 "\" doesn't exist",
1016 (char *) NULL);
1017 } else {
1018 Tcl_AppendResult(interp, "could not create new link \"",
1019 Tcl_GetString(objv[index]), "\" pointing to \"",
1020 Tcl_GetString(objv[index+1]), "\": ",
1021 Tcl_PosixError(interp), (char *) NULL);
1022 }
1023 return TCL_ERROR;
1024 }
1025 } else {
1026 if (Tcl_FSConvertToPathType(interp, objv[index]) != TCL_OK) {
1027 return TCL_ERROR;
1028 }
1029 /* Read link */
1030 contents = Tcl_FSLink(objv[index], NULL, 0);
1031 if (contents == NULL) {
1032 Tcl_AppendResult(interp, "could not read link \"",
1033 Tcl_GetString(objv[index]), "\": ",
1034 Tcl_PosixError(interp), (char *) NULL);
1035 return TCL_ERROR;
1036 }
1037 }
1038 Tcl_SetObjResult(interp, contents);
1039 if (objc == 3) {
1040 /*
1041 * If we are reading a link, we need to free this
1042 * result refCount. If we are creating a link, this
1043 * will just be objv[index+1], and so we don't own it.
1044 */
1045 Tcl_DecrRefCount(contents);
1046 }
1047 return TCL_OK;
1048 }
1049 case FCMD_LSTAT: {
1050 char *varName;
1051 Tcl_StatBuf buf;
1052
1053 if (objc != 4) {
1054 Tcl_WrongNumArgs(interp, 2, objv, "name varName");
1055 return TCL_ERROR;
1056 }
1057 if (GetStatBuf(interp, objv[2], Tcl_FSLstat, &buf) != TCL_OK) {
1058 return TCL_ERROR;
1059 }
1060 varName = Tcl_GetString(objv[3]);
1061 return StoreStatData(interp, varName, &buf);
1062 }
1063 case FCMD_MTIME: {
1064 Tcl_StatBuf buf;
1065 struct utimbuf tval;
1066
1067 if ((objc < 3) || (objc > 4)) {
1068 Tcl_WrongNumArgs(interp, 2, objv, "name ?time?");
1069 return TCL_ERROR;
1070 }
1071 if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) {
1072 return TCL_ERROR;
1073 }
1074 if (objc == 4) {
1075 long newTime;
1076
1077 if (Tcl_GetLongFromObj(interp, objv[3], &newTime) != TCL_OK) {
1078 return TCL_ERROR;
1079 }
1080 tval.actime = buf.st_atime;
1081 tval.modtime = newTime;
1082 if (Tcl_FSUtime(objv[2], &tval) != 0) {
1083 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1084 "could not set modification time for file \"",
1085 Tcl_GetString(objv[2]), "\": ",
1086 Tcl_PosixError(interp), (char *) NULL);
1087 return TCL_ERROR;
1088 }
1089 /*
1090 * Do another stat to ensure that the we return the
1091 * new recognized atime - hopefully the same as the
1092 * one we sent in. However, fs's like FAT don't
1093 * even know what atime is.
1094 */
1095 if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) {
1096 return TCL_ERROR;
1097 }
1098 }
1099 Tcl_SetLongObj(Tcl_GetObjResult(interp), (long) buf.st_mtime);
1100 return TCL_OK;
1101 }
1102 case FCMD_MKDIR: {
1103 if (objc < 3) {
1104 Tcl_WrongNumArgs(interp, 2, objv, "name ?name ...?");
1105 return TCL_ERROR;
1106 }
1107 return TclFileMakeDirsCmd(interp, objc, objv);
1108 }
1109 case FCMD_NATIVENAME: {
1110 CONST char *fileName;
1111 Tcl_DString ds;
1112
1113 if (objc != 3) {
1114 goto only3Args;
1115 }
1116 fileName = Tcl_GetString(objv[2]);
1117 fileName = Tcl_TranslateFileName(interp, fileName, &ds);
1118 if (fileName == NULL) {
1119 return TCL_ERROR;
1120 }
1121 Tcl_SetStringObj(Tcl_GetObjResult(interp), fileName,
1122 Tcl_DStringLength(&ds));
1123 Tcl_DStringFree(&ds);
1124 return TCL_OK;
1125 }
1126 case FCMD_NORMALIZE: {
1127 Tcl_Obj *fileName;
1128
1129 if (objc != 3) {
1130 Tcl_WrongNumArgs(interp, 2, objv, "filename");
1131 return TCL_ERROR;
1132 }
1133
1134 fileName = Tcl_FSGetNormalizedPath(interp, objv[2]);
1135 Tcl_SetObjResult(interp, fileName);
1136 return TCL_OK;
1137 }
1138 case FCMD_OWNED: {
1139 int value;
1140 Tcl_StatBuf buf;
1141
1142 if (objc != 3) {
1143 goto only3Args;
1144 }
1145 value = 0;
1146 if (GetStatBuf(NULL, objv[2], Tcl_FSStat, &buf) == TCL_OK) {
1147 /*
1148 * For Windows and Macintosh, there are no user ids
1149 * associated with a file, so we always return 1.
1150 */
1151
1152 #if (defined(__WIN32__) || defined(MAC_TCL))
1153 value = 1;
1154 #else
1155 value = (geteuid() == buf.st_uid);
1156 #endif
1157 }
1158 Tcl_SetBooleanObj(Tcl_GetObjResult(interp), value);
1159 return TCL_OK;
1160 }
1161 case FCMD_PATHTYPE: {
1162 if (objc != 3) {
1163 goto only3Args;
1164 }
1165 switch (Tcl_FSGetPathType(objv[2])) {
1166 case TCL_PATH_ABSOLUTE:
1167 Tcl_SetStringObj(Tcl_GetObjResult(interp), "absolute", -1);
1168 break;
1169 case TCL_PATH_RELATIVE:
1170 Tcl_SetStringObj(Tcl_GetObjResult(interp), "relative", -1);
1171 break;
1172 case TCL_PATH_VOLUME_RELATIVE:
1173 Tcl_SetStringObj(Tcl_GetObjResult(interp),
1174 "volumerelative", -1);
1175 break;
1176 }
1177 return TCL_OK;
1178 }
1179 case FCMD_READABLE: {
1180 if (objc != 3) {
1181 goto only3Args;
1182 }
1183 return CheckAccess(interp, objv[2], R_OK);
1184 }
1185 case FCMD_READLINK: {
1186 Tcl_Obj *contents;
1187
1188 if (objc != 3) {
1189 goto only3Args;
1190 }
1191
1192 if (Tcl_FSConvertToPathType(interp, objv[2]) != TCL_OK) {
1193 return TCL_ERROR;
1194 }
1195
1196 contents = Tcl_FSLink(objv[2], NULL, 0);
1197
1198 if (contents == NULL) {
1199 Tcl_AppendResult(interp, "could not readlink \"",
1200 Tcl_GetString(objv[2]), "\": ",
1201 Tcl_PosixError(interp), (char *) NULL);
1202 return TCL_ERROR;
1203 }
1204 Tcl_SetObjResult(interp, contents);
1205 Tcl_DecrRefCount(contents);
1206 return TCL_OK;
1207 }
1208 case FCMD_RENAME: {
1209 return TclFileRenameCmd(interp, objc, objv);
1210 }
1211 case FCMD_ROOTNAME: {
1212 int length;
1213 char *fileName, *extension;
1214
1215 if (objc != 3) {
1216 goto only3Args;
1217 }
1218 fileName = Tcl_GetStringFromObj(objv[2], &length);
1219 extension = TclGetExtension(fileName);
1220 if (extension == NULL) {
1221 Tcl_SetObjResult(interp, objv[2]);
1222 } else {
1223 Tcl_SetStringObj(Tcl_GetObjResult(interp), fileName,
1224 (int) (length - strlen(extension)));
1225 }
1226 return TCL_OK;
1227 }
1228 case FCMD_SEPARATOR: {
1229 if ((objc < 2) || (objc > 3)) {
1230 Tcl_WrongNumArgs(interp, 2, objv, "?name?");
1231 return TCL_ERROR;
1232 }
1233 if (objc == 2) {
1234 char *separator = NULL; /* lint */
1235 switch (tclPlatform) {
1236 case TCL_PLATFORM_UNIX:
1237 separator = "/";
1238 break;
1239 case TCL_PLATFORM_WINDOWS:
1240 separator = "\\";
1241 break;
1242 case TCL_PLATFORM_MAC:
1243 separator = ":";
1244 break;
1245 }
1246 Tcl_SetObjResult(interp, Tcl_NewStringObj(separator,1));
1247 } else {
1248 Tcl_Obj *separatorObj = Tcl_FSPathSeparator(objv[2]);
1249 if (separatorObj != NULL) {
1250 Tcl_SetObjResult(interp, separatorObj);
1251 } else {
1252 Tcl_SetObjResult(interp,
1253 Tcl_NewStringObj("Unrecognised path",-1));
1254 return TCL_ERROR;
1255 }
1256 }
1257 return TCL_OK;
1258 }
1259 case FCMD_SIZE: {
1260 Tcl_StatBuf buf;
1261
1262 if (objc != 3) {
1263 goto only3Args;
1264 }
1265 if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) {
1266 return TCL_ERROR;
1267 }
1268 Tcl_SetWideIntObj(Tcl_GetObjResult(interp),
1269 (Tcl_WideInt) buf.st_size);
1270 return TCL_OK;
1271 }
1272 case FCMD_SPLIT: {
1273 if (objc != 3) {
1274 goto only3Args;
1275 }
1276 Tcl_SetObjResult(interp, Tcl_FSSplitPath(objv[2], NULL));
1277 return TCL_OK;
1278 }
1279 case FCMD_STAT: {
1280 char *varName;
1281 Tcl_StatBuf buf;
1282
1283 if (objc != 4) {
1284 Tcl_WrongNumArgs(interp, 1, objv, "stat name varName");
1285 return TCL_ERROR;
1286 }
1287 if (GetStatBuf(interp, objv[2], Tcl_FSStat, &buf) != TCL_OK) {
1288 return TCL_ERROR;
1289 }
1290 varName = Tcl_GetString(objv[3]);
1291 return StoreStatData(interp, varName, &buf);
1292 }
1293 case FCMD_SYSTEM: {
1294 Tcl_Obj* fsInfo;
1295 if (objc != 3) {
1296 goto only3Args;
1297 }
1298 fsInfo = Tcl_FSFileSystemInfo(objv[2]);
1299 if (fsInfo != NULL) {
1300 Tcl_SetObjResult(interp, fsInfo);
1301 return TCL_OK;
1302 } else {
1303 Tcl_SetObjResult(interp,
1304 Tcl_NewStringObj("Unrecognised path",-1));
1305 return TCL_ERROR;
1306 }
1307 }
1308 case FCMD_TAIL: {
1309 int splitElements;
1310 Tcl_Obj *splitPtr;
1311
1312 if (objc != 3) {
1313 goto only3Args;
1314 }
1315 /*
1316 * The behaviour we want here is slightly different to
1317 * the standard Tcl_FSSplitPath in the handling of home
1318 * directories; Tcl_FSSplitPath preserves the "~" while
1319 * this code computes the actual full path name, if we
1320 * had just a single component.
1321 */
1322 splitPtr = Tcl_FSSplitPath(objv[2], &splitElements);
1323 if ((splitElements == 1) && (Tcl_GetString(objv[2])[0] == '~')) {
1324 Tcl_DecrRefCount(splitPtr);
1325 splitPtr = Tcl_FSGetNormalizedPath(interp, objv[2]);
1326 if (splitPtr == NULL) {
1327 return TCL_ERROR;
1328 }
1329 splitPtr = Tcl_FSSplitPath(splitPtr, &splitElements);
1330 }
1331
1332 /*
1333 * Return the last component, unless it is the only component,
1334 * and it is the root of an absolute path.
1335 */
1336
1337 if (splitElements > 0) {
1338 if ((splitElements > 1)
1339 || (Tcl_FSGetPathType(objv[2]) == TCL_PATH_RELATIVE)) {
1340
1341 Tcl_Obj *tail = NULL;
1342 Tcl_ListObjIndex(NULL, splitPtr, splitElements-1, &tail);
1343 Tcl_SetObjResult(interp, tail);
1344 }
1345 }
1346 Tcl_DecrRefCount(splitPtr);
1347 return TCL_OK;
1348 }
1349 case FCMD_TYPE: {
1350 Tcl_StatBuf buf;
1351
1352 if (objc != 3) {
1353 goto only3Args;
1354 }
1355 if (GetStatBuf(interp, objv[2], Tcl_FSLstat, &buf) != TCL_OK) {
1356 return TCL_ERROR;
1357 }
1358 Tcl_SetStringObj(Tcl_GetObjResult(interp),
1359 GetTypeFromMode((unsigned short) buf.st_mode), -1);
1360 return TCL_OK;
1361 }
1362 case FCMD_VOLUMES: {
1363 if (objc != 2) {
1364 Tcl_WrongNumArgs(interp, 2, objv, NULL);
1365 return TCL_ERROR;
1366 }
1367 Tcl_SetObjResult(interp, Tcl_FSListVolumes());
1368 return TCL_OK;
1369 }
1370 case FCMD_WRITABLE: {
1371 if (objc != 3) {
1372 goto only3Args;
1373 }
1374 return CheckAccess(interp, objv[2], W_OK);
1375 }
1376 }
1377
1378 only3Args:
1379 Tcl_WrongNumArgs(interp, 2, objv, "name");
1380 return TCL_ERROR;
1381 }
1382
1383 /*
1384 *---------------------------------------------------------------------------
1385 *
1386 * CheckAccess --
1387 *
1388 * Utility procedure used by Tcl_FileObjCmd() to query file
1389 * attributes available through the access() system call.
1390 *
1391 * Results:
1392 * Always returns TCL_OK. Sets interp's result to boolean true or
1393 * false depending on whether the file has the specified attribute.
1394 *
1395 * Side effects:
1396 * None.
1397 *
1398 *---------------------------------------------------------------------------
1399 */
1400
1401 static int
1402 CheckAccess(interp, objPtr, mode)
1403 Tcl_Interp *interp; /* Interp for status return. Must not be
1404 * NULL. */
1405 Tcl_Obj *objPtr; /* Name of file to check. */
1406 int mode; /* Attribute to check; passed as argument to
1407 * access(). */
1408 {
1409 int value;
1410
1411 if (Tcl_FSConvertToPathType(interp, objPtr) != TCL_OK) {
1412 value = 0;
1413 } else {
1414 value = (Tcl_FSAccess(objPtr, mode) == 0);
1415 }
1416 Tcl_SetBooleanObj(Tcl_GetObjResult(interp), value);
1417
1418 return TCL_OK;
1419 }
1420
1421 /*
1422 *---------------------------------------------------------------------------
1423 *
1424 * GetStatBuf --
1425 *
1426 * Utility procedure used by Tcl_FileObjCmd() to query file
1427 * attributes available through the stat() or lstat() system call.
1428 *
1429 * Results:
1430 * The return value is TCL_OK if the specified file exists and can
1431 * be stat'ed, TCL_ERROR otherwise. If TCL_ERROR is returned, an
1432 * error message is left in interp's result. If TCL_OK is returned,
1433 * *statPtr is filled with information about the specified file.
1434 *
1435 * Side effects:
1436 * None.
1437 *
1438 *---------------------------------------------------------------------------
1439 */
1440
1441 static int
1442 GetStatBuf(interp, objPtr, statProc, statPtr)
1443 Tcl_Interp *interp; /* Interp for error return. May be NULL. */
1444 Tcl_Obj *objPtr; /* Path name to examine. */
1445 Tcl_FSStatProc *statProc; /* Either stat() or lstat() depending on
1446 * desired behavior. */
1447 Tcl_StatBuf *statPtr; /* Filled with info about file obtained by
1448 * calling (*statProc)(). */
1449 {
1450 int status;
1451
1452 if (Tcl_FSConvertToPathType(interp, objPtr) != TCL_OK) {
1453 return TCL_ERROR;
1454 }
1455
1456 status = (*statProc)(objPtr, statPtr);
1457
1458 if (status < 0) {
1459 if (interp != NULL) {
1460 Tcl_AppendResult(interp, "could not read \"",
1461 Tcl_GetString(objPtr), "\": ",
1462 Tcl_PosixError(interp), (char *) NULL);
1463 }
1464 return TCL_ERROR;
1465 }
1466 return TCL_OK;
1467 }
1468
1469 /*
1470 *----------------------------------------------------------------------
1471 *
1472 * StoreStatData --
1473 *
1474 * This is a utility procedure that breaks out the fields of a
1475 * "stat" structure and stores them in textual form into the
1476 * elements of an associative array.
1477 *
1478 * Results:
1479 * Returns a standard Tcl return value. If an error occurs then
1480 * a message is left in interp's result.
1481 *
1482 * Side effects:
1483 * Elements of the associative array given by "varName" are modified.
1484 *
1485 *----------------------------------------------------------------------
1486 */
1487
1488 static int
1489 StoreStatData(interp, varName, statPtr)
1490 Tcl_Interp *interp; /* Interpreter for error reports. */
1491 char *varName; /* Name of associative array variable
1492 * in which to store stat results. */
1493 Tcl_StatBuf *statPtr; /* Pointer to buffer containing
1494 * stat data to store in varName. */
1495 {
1496 Tcl_Obj *var = Tcl_NewStringObj(varName, -1);
1497 Tcl_Obj *field = Tcl_NewObj();
1498 Tcl_Obj *value;
1499 register unsigned short mode;
1500
1501 /*
1502 * Assume Tcl_ObjSetVar2() does not keep a copy of the field name!
1503 */
1504 #define STORE_ARY(fieldName, object) \
1505 Tcl_SetStringObj(field, (fieldName), -1); \
1506 value = (object); \
1507 if (Tcl_ObjSetVar2(interp,var,field,value,TCL_LEAVE_ERR_MSG) == NULL) { \
1508 Tcl_DecrRefCount(var); \
1509 Tcl_DecrRefCount(field); \
1510 Tcl_DecrRefCount(value); \
1511 return TCL_ERROR; \
1512 }
1513
1514 Tcl_IncrRefCount(var);
1515 Tcl_IncrRefCount(field);
1516 STORE_ARY("dev", Tcl_NewLongObj((long)statPtr->st_dev));
1517 /*
1518 * Watch out porters; the inode is meant to be an *unsigned* value,
1519 * so the cast might fail when there isn't a real arithmentic 'long
1520 * long' type...
1521 */
1522 STORE_ARY("ino", Tcl_NewWideIntObj((Tcl_WideInt)statPtr->st_ino));
1523 STORE_ARY("nlink", Tcl_NewLongObj((long)statPtr->st_nlink));
1524 STORE_ARY("uid", Tcl_NewLongObj((long)statPtr->st_uid));
1525 STORE_ARY("gid", Tcl_NewLongObj((long)statPtr->st_gid));
1526 STORE_ARY("size", Tcl_NewWideIntObj((Tcl_WideInt)statPtr->st_size));
1527 #ifdef HAVE_ST_BLOCKS
1528 STORE_ARY("blocks",Tcl_NewWideIntObj((Tcl_WideInt)statPtr->st_blocks));
1529 #endif
1530 STORE_ARY("atime", Tcl_NewLongObj((long)statPtr->st_atime));
1531 STORE_ARY("mtime", Tcl_NewLongObj((long)statPtr->st_mtime));
1532 STORE_ARY("ctime", Tcl_NewLongObj((long)statPtr->st_ctime));
1533 mode = (unsigned short) statPtr->st_mode;
1534 STORE_ARY("mode", Tcl_NewIntObj(mode));
1535 STORE_ARY("type", Tcl_NewStringObj(GetTypeFromMode(mode), -1));
1536 #undef STORE_ARY
1537 Tcl_DecrRefCount(var);
1538 Tcl_DecrRefCount(field);
1539 return TCL_OK;
1540 }
1541
1542 /*
1543 *----------------------------------------------------------------------
1544 *
1545 * GetTypeFromMode --
1546 *
1547 * Given a mode word, returns a string identifying the type of a
1548 * file.
1549 *
1550 * Results:
1551 * A static text string giving the file type from mode.
1552 *
1553 * Side effects:
1554 * None.
1555 *
1556 *----------------------------------------------------------------------
1557 */
1558
1559 static char *
1560 GetTypeFromMode(mode)
1561 int mode;
1562 {
1563 if (S_ISREG(mode)) {
1564 return "file";
1565 } else if (S_ISDIR(mode)) {
1566 return "directory";
1567 } else if (S_ISCHR(mode)) {
1568 return "characterSpecial";
1569 } else if (S_ISBLK(mode)) {
1570 return "blockSpecial";
1571 } else if (S_ISFIFO(mode)) {
1572 return "fifo";
1573 #ifdef S_ISLNK
1574 } else if (S_ISLNK(mode)) {
1575 return "link";
1576 #endif
1577 #ifdef S_ISSOCK
1578 } else if (S_ISSOCK(mode)) {
1579 return "socket";
1580 #endif
1581 }
1582 return "unknown";
1583 }
1584
1585 /*
1586 *----------------------------------------------------------------------
1587 *
1588 * Tcl_ForObjCmd --
1589 *
1590 * This procedure is invoked to process the "for" Tcl command.
1591 * See the user documentation for details on what it does.
1592 *
1593 * With the bytecode compiler, this procedure is only called when
1594 * a command name is computed at runtime, and is "for" or the name
1595 * to which "for" was renamed: e.g.,
1596 * "set z for; $z {set i 0} {$i<100} {incr i} {puts $i}"
1597 *
1598 * Results:
1599 * A standard Tcl result.
1600 *
1601 * Side effects:
1602 * See the user documentation.
1603 *
1604 *----------------------------------------------------------------------
1605 */
1606
1607 /* ARGSUSED */
1608 int
1609 Tcl_ForObjCmd(dummy, interp, objc, objv)
1610 ClientData dummy; /* Not used. */
1611 Tcl_Interp *interp; /* Current interpreter. */
1612 int objc; /* Number of arguments. */
1613 Tcl_Obj *CONST objv[]; /* Argument objects. */
1614 {
1615 int result, value;
1616
1617 if (objc != 5) {
1618 Tcl_WrongNumArgs(interp, 1, objv, "start test next command");
1619 return TCL_ERROR;
1620 }
1621
1622 result = Tcl_EvalObjEx(interp, objv[1], 0);
1623 if (result != TCL_OK) {
1624 if (result == TCL_ERROR) {
1625 Tcl_AddErrorInfo(interp, "\n (\"for\" initial command)");
1626 }
1627 return result;
1628 }
1629 while (1) {
1630 /*
1631 * We need to reset the result before passing it off to
1632 * Tcl_ExprBooleanObj. Otherwise, any error message will be appended
1633 * to the result of the last evaluation.
1634 */
1635
1636 Tcl_ResetResult(interp);
1637 result = Tcl_ExprBooleanObj(interp, objv[2], &value);
1638 if (result != TCL_OK) {
1639 return result;
1640 }
1641 if (!value) {
1642 break;
1643 }
1644 result = Tcl_EvalObjEx(interp, objv[4], 0);
1645 if ((result != TCL_OK) && (result != TCL_CONTINUE)) {
1646 if (result == TCL_ERROR) {
1647 char msg[32 + TCL_INTEGER_SPACE];
1648
1649 sprintf(msg, "\n (\"for\" body line %d)",interp->errorLine);
1650 Tcl_AddErrorInfo(interp, msg);
1651 }
1652 break;
1653 }
1654 result = Tcl_EvalObjEx(interp, objv[3], 0);
1655 if (result == TCL_BREAK) {
1656 break;
1657 } else if (result != TCL_OK) {
1658 if (result == TCL_ERROR) {
1659 Tcl_AddErrorInfo(interp, "\n (\"for\" loop-end command)");
1660 }
1661 return result;
1662 }
1663 }
1664 if (result == TCL_BREAK) {
1665 result = TCL_OK;
1666 }
1667 if (result == TCL_OK) {
1668 Tcl_ResetResult(interp);
1669 }
1670 return result;
1671 }
1672
1673 /*
1674 *----------------------------------------------------------------------
1675 *
1676 * Tcl_ForeachObjCmd --
1677 *
1678 * This object-based procedure is invoked to process the "foreach" Tcl
1679 * command. See the user documentation for details on what it does.
1680 *
1681 * Results:
1682 * A standard Tcl object result.
1683 *
1684 * Side effects:
1685 * See the user documentation.
1686 *
1687 *----------------------------------------------------------------------
1688 */
1689
1690 /* ARGSUSED */
1691 int
1692 Tcl_ForeachObjCmd(dummy, interp, objc, objv)
1693 ClientData dummy; /* Not used. */
1694 Tcl_Interp *interp; /* Current interpreter. */
1695 int objc; /* Number of arguments. */
1696 Tcl_Obj *CONST objv[]; /* Argument objects. */
1697 {
1698 int result = TCL_OK;
1699 int i; /* i selects a value list */
1700 int j, maxj; /* Number of loop iterations */
1701 int v; /* v selects a loop variable */
1702 int numLists; /* Count of value lists */
1703 Tcl_Obj *bodyPtr;
1704
1705 /*
1706 * We copy the argument object pointers into a local array to avoid
1707 * the problem that "objv" might become invalid. It is a pointer into
1708 * the evaluation stack and that stack might be grown and reallocated
1709 * if the loop body requires a large amount of stack space.
1710 */
1711
1712 #define NUM_ARGS 9
1713 Tcl_Obj *(argObjStorage[NUM_ARGS]);
1714 Tcl_Obj **argObjv = argObjStorage;
1715
1716 #define STATIC_LIST_SIZE 4
1717 int indexArray[STATIC_LIST_SIZE];
1718 int varcListArray[STATIC_LIST_SIZE];
1719 Tcl_Obj **varvListArray[STATIC_LIST_SIZE];
1720 int argcListArray[STATIC_LIST_SIZE];
1721 Tcl_Obj **argvListArray[STATIC_LIST_SIZE];
1722
1723 int *index = indexArray; /* Array of value list indices */
1724 int *varcList = varcListArray; /* # loop variables per list */
1725 Tcl_Obj ***varvList = varvListArray; /* Array of var name lists */
1726 int *argcList = argcListArray; /* Array of value list sizes */
1727 Tcl_Obj ***argvList = argvListArray; /* Array of value lists */
1728
1729 if (objc < 4 || (objc%2 != 0)) {
1730 Tcl_WrongNumArgs(interp, 1, objv,
1731 "varList list ?varList list ...? command");
1732 return TCL_ERROR;
1733 }
1734
1735 /*
1736 * Create the object argument array "argObjv". Make sure argObjv is
1737 * large enough to hold the objc arguments.
1738 */
1739
1740 if (objc > NUM_ARGS) {
1741 argObjv = (Tcl_Obj **) ckalloc(objc * sizeof(Tcl_Obj *));
1742 }
1743 for (i = 0; i < objc; i++) {
1744 argObjv[i] = objv[i];
1745 }
1746
1747 /*
1748 * Manage numList parallel value lists.
1749 * argvList[i] is a value list counted by argcList[i]
1750 * varvList[i] is the list of variables associated with the value list
1751 * varcList[i] is the number of variables associated with the value list
1752 * index[i] is the current pointer into the value list argvList[i]
1753 */
1754
1755 numLists = (objc-2)/2;
1756 if (numLists > STATIC_LIST_SIZE) {
1757 index = (int *) ckalloc(numLists * sizeof(int));
1758 varcList = (int *) ckalloc(numLists * sizeof(int));
1759 varvList = (Tcl_Obj ***) ckalloc(numLists * sizeof(Tcl_Obj **));
1760 argcList = (int *) ckalloc(numLists * sizeof(int));
1761 argvList = (Tcl_Obj ***) ckalloc(numLists * sizeof(Tcl_Obj **));
1762 }
1763 for (i = 0; i < numLists; i++) {
1764 index[i] = 0;
1765 varcList[i] = 0;
1766 varvList[i] = (Tcl_Obj **) NULL;
1767 argcList[i] = 0;
1768 argvList[i] = (Tcl_Obj **) NULL;
1769 }
1770
1771 /*
1772 * Break up the value lists and variable lists into elements
1773 */
1774
1775 maxj = 0;
1776 for (i = 0; i < numLists; i++) {
1777 result = Tcl_ListObjGetElements(interp, argObjv[1+i*2],
1778 &varcList[i], &varvList[i]);
1779 if (result != TCL_OK) {
1780 goto done;
1781 }
1782 if (varcList[i] < 1) {
1783 Tcl_AppendToObj(Tcl_GetObjResult(interp),
1784 "foreach varlist is empty", -1);
1785 result = TCL_ERROR;
1786 goto done;
1787 }
1788
1789 result = Tcl_ListObjGetElements(interp, argObjv[2+i*2],
1790 &argcList[i], &argvList[i]);
1791 if (result != TCL_OK) {
1792 goto done;
1793 }
1794
1795 j = argcList[i] / varcList[i];
1796 if ((argcList[i] % varcList[i]) != 0) {
1797 j++;
1798 }
1799 if (j > maxj) {
1800 maxj = j;
1801 }
1802 }
1803
1804 /*
1805 * Iterate maxj times through the lists in parallel
1806 * If some value lists run out of values, set loop vars to ""
1807 */
1808
1809 bodyPtr = argObjv[objc-1];
1810 for (j = 0; j < maxj; j++) {
1811 for (i = 0; i < numLists; i++) {
1812 /*
1813 * Refetch the list members; we assume that the sizes are
1814 * the same, but the array of elements might be different
1815 * if the internal rep of the objects has been lost and
1816 * recreated (it is too difficult to accurately tell when
1817 * this happens, which can lead to some wierd crashes,
1818 * like Bug #494348...)
1819 */
1820
1821 result = Tcl_ListObjGetElements(interp, argObjv[1+i*2],
1822 &varcList[i], &varvList[i]);
1823 if (result != TCL_OK) {
1824 panic("Tcl_ForeachObjCmd: could not reconvert variable list %d to a list object\n", i);
1825 }
1826 result = Tcl_ListObjGetElements(interp, argObjv[2+i*2],
1827 &argcList[i], &argvList[i]);
1828 if (result != TCL_OK) {
1829 panic("Tcl_ForeachObjCmd: could not reconvert value list %d to a list object\n", i);
1830 }
1831
1832 for (v = 0; v < varcList[i]; v++) {
1833 int k = index[i]++;
1834 Tcl_Obj *valuePtr, *varValuePtr;
1835 int isEmptyObj = 0;
1836
1837 if (k < argcList[i]) {
1838 valuePtr = argvList[i][k];
1839 } else {
1840 valuePtr = Tcl_NewObj(); /* empty string */
1841 isEmptyObj = 1;
1842 }
1843 varValuePtr = Tcl_ObjSetVar2(interp, varvList[i][v],
1844 NULL, valuePtr, 0);
1845 if (varValuePtr == NULL) {
1846 if (isEmptyObj) {
1847 Tcl_DecrRefCount(valuePtr);
1848 }
1849 Tcl_ResetResult(interp);
1850 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
1851 "couldn't set loop variable: \"",
1852 Tcl_GetString(varvList[i][v]), "\"", (char *) NULL);
1853 result = TCL_ERROR;
1854 goto done;
1855 }
1856
1857 }
1858 }
1859
1860 result = Tcl_EvalObjEx(interp, bodyPtr, 0);
1861 if (result != TCL_OK) {
1862 if (result == TCL_CONTINUE) {
1863 result = TCL_OK;
1864 } else if (result == TCL_BREAK) {
1865 result = TCL_OK;
1866 break;
1867 } else if (result == TCL_ERROR) {
1868 char msg[32 + TCL_INTEGER_SPACE];
1869
1870 sprintf(msg, "\n (\"foreach\" body line %d)",
1871 interp->errorLine);
1872 Tcl_AddObjErrorInfo(interp, msg, -1);
1873 break;
1874 } else {
1875 break;
1876 }
1877 }
1878 }
1879 if (result == TCL_OK) {
1880 Tcl_ResetResult(interp);
1881 }
1882
1883 done:
1884 if (numLists > STATIC_LIST_SIZE) {
1885 ckfree((char *) index);
1886 ckfree((char *) varcList);
1887 ckfree((char *) argcList);
1888 ckfree((char *) varvList);
1889 ckfree((char *) argvList);
1890 }
1891 if (argObjv != argObjStorage) {
1892 ckfree((char *) argObjv);
1893 }
1894 return result;
1895 #undef STATIC_LIST_SIZE
1896 #undef NUM_ARGS
1897 }
1898
1899 /*
1900 *----------------------------------------------------------------------
1901 *
1902 * Tcl_FormatObjCmd --
1903 *
1904 * This procedure is invoked to process the "format" Tcl command.
1905 * See the user documentation for details on what it does.
1906 *
1907 * Results:
1908 * A standard Tcl result.
1909 *
1910 * Side effects:
1911 * See the user documentation.
1912 *
1913 *----------------------------------------------------------------------
1914 */
1915
1916 /* ARGSUSED */
1917 int
1918 Tcl_FormatObjCmd(dummy, interp, objc, objv)
1919 ClientData dummy; /* Not used. */
1920 Tcl_Interp *interp; /* Current interpreter. */
1921 int objc; /* Number of arguments. */
1922 Tcl_Obj *CONST objv[]; /* Argument objects. */
1923 {
1924 char *format; /* Used to read characters from the format
1925 * string. */
1926 int formatLen; /* The length of the format string */
1927 char *endPtr; /* Points to the last char in format array */
1928 char newFormat[43]; /* A new format specifier is generated here. */
1929 int width; /* Field width from field specifier, or 0 if
1930 * no width given. */
1931 int precision; /* Field precision from field specifier, or 0
1932 * if no precision given. */
1933 int size; /* Number of bytes needed for result of
1934 * conversion, based on type of conversion
1935 * ("e", "s", etc.), width, and precision. */
1936 long intValue; /* Used to hold value to pass to sprintf, if
1937 * it's a one-word integer or char value */
1938 char *ptrValue = NULL; /* Used to hold value to pass to sprintf, if
1939 * it's a one-word value. */
1940 double doubleValue; /* Used to hold value to pass to sprintf if
1941 * it's a double value. */
1942 Tcl_WideInt wideValue; /* Used to hold value to pass to sprintf if
1943 * it's a 'long long' value. */
1944 int whichValue; /* Indicates which of intValue, ptrValue,
1945 * or doubleValue has the value to pass to
1946 * sprintf, according to the following
1947 * definitions: */
1948 # define INT_VALUE 0
1949 # define CHAR_VALUE 1
1950 # define PTR_VALUE 2
1951 # define DOUBLE_VALUE 3
1952 # define STRING_VALUE 4
1953 # define WIDE_VALUE 5
1954 # define MAX_FLOAT_SIZE 320
1955
1956 Tcl_Obj *resultPtr; /* Where result is stored finally. */
1957 char staticBuf[MAX_FLOAT_SIZE + 1];
1958 /* A static buffer to copy the format results
1959 * into */
1960 char *dst = staticBuf; /* The buffer that sprintf writes into each
1961 * time the format processes a specifier */
1962 int dstSize = MAX_FLOAT_SIZE;
1963 /* The size of the dst buffer */
1964 int noPercent; /* Special case for speed: indicates there's
1965 * no field specifier, just a string to copy.*/
1966 int objIndex; /* Index of argument to substitute next. */
1967 int gotXpg = 0; /* Non-zero means that an XPG3 %n$-style
1968 * specifier has been seen. */
1969 int gotSequential = 0; /* Non-zero means that a regular sequential
1970 * (non-XPG3) conversion specifier has been
1971 * seen. */
1972 int useShort; /* Value to be printed is short (half word). */
1973 char *end; /* Used to locate end of numerical fields. */
1974 int stringLen = 0; /* Length of string in characters rather
1975 * than bytes. Used for %s substitution. */
1976 int gotMinus; /* Non-zero indicates that a minus flag has
1977 * been seen in the current field. */
1978 int gotPrecision; /* Non-zero indicates that a precision has
1979 * been set for the current field. */
1980 int gotZero; /* Non-zero indicates that a zero flag has
1981 * been seen in the current field. */
1982 int useWide; /* Value to be printed is Tcl_WideInt. */
1983
1984 /*
1985 * This procedure is a bit nasty. The goal is to use sprintf to
1986 * do most of the dirty work. There are several problems:
1987 * 1. this procedure can't trust its arguments.
1988 * 2. we must be able to provide a large enough result area to hold
1989 * whatever's generated. This is hard to estimate.
1990 * 3. there's no way to move the arguments from objv to the call
1991 * to sprintf in a reasonable way. This is particularly nasty
1992 * because some of the arguments may be two-word values (doubles
1993 * and wide-ints).
1994 * So, what happens here is to scan the format string one % group
1995 * at a time, making many individual calls to sprintf.
1996 */
1997
1998 if (objc < 2) {
1999 Tcl_WrongNumArgs(interp, 1, objv, "formatString ?arg arg ...?");
2000 return TCL_ERROR;
2001 }
2002
2003 format = Tcl_GetStringFromObj(objv[1], &formatLen);
2004 endPtr = format + formatLen;
2005 resultPtr = Tcl_NewObj();
2006 objIndex = 2;
2007
2008 while (format < endPtr) {
2009 register char *newPtr = newFormat;
2010
2011 width = precision = noPercent = useShort = 0;
2012 gotZero = gotMinus = gotPrecision = 0;
2013 useWide = 0;
2014 whichValue = PTR_VALUE;
2015
2016 /*
2017 * Get rid of any characters before the next field specifier.
2018 */
2019 if (*format != '%') {
2020 ptrValue = format;
2021 while ((*format != '%') && (format < endPtr)) {
2022 format++;
2023 }
2024 size = format - ptrValue;
2025 noPercent = 1;
2026 goto doField;
2027 }
2028
2029 if (format[1] == '%') {
2030 ptrValue = format;
2031 size = 1;
2032 noPercent = 1;
2033 format += 2;
2034 goto doField;
2035 }
2036
2037 /*
2038 * Parse off a field specifier, compute how many characters
2039 * will be needed to store the result, and substitute for
2040 * "*" size specifiers.
2041 */
2042 *newPtr = '%';
2043 newPtr++;
2044 format++;
2045 if (isdigit(UCHAR(*format))) { /* INTL: Tcl source. */
2046 int tmp;
2047
2048 /*
2049 * Check for an XPG3-style %n$ specification. Note: there
2050 * must not be a mixture of XPG3 specs and non-XPG3 specs
2051 * in the same format string.
2052 */
2053
2054 tmp = strtoul(format, &end, 10); /* INTL: "C" locale. */
2055 if (*end != '$') {
2056 goto notXpg;
2057 }
2058 format = end+1;
2059 gotXpg = 1;
2060 if (gotSequential) {
2061 goto mixedXPG;
2062 }
2063 objIndex = tmp+1;
2064 if ((objIndex < 2) || (objIndex >= objc)) {
2065 goto badIndex;
2066 }
2067 goto xpgCheckDone;
2068 }
2069
2070 notXpg:
2071 gotSequential = 1;
2072 if (gotXpg) {
2073 goto mixedXPG;
2074 }
2075
2076 xpgCheckDone:
2077 while ((*format == '-') || (*format == '#') || (*format == '0')
2078 || (*format == ' ') || (*format == '+')) {
2079 if (*format == '-') {
2080 gotMinus = 1;
2081 }
2082 if (*format == '0') {
2083 /*
2084 * This will be handled by sprintf for numbers, but we
2085 * need to do the char/string ones ourselves
2086 */
2087 gotZero = 1;
2088 }
2089 *newPtr = *format;
2090 newPtr++;
2091 format++;
2092 }
2093 if (isdigit(UCHAR(*format))) { /* INTL: Tcl source. */
2094 width = strtoul(format, &end, 10); /* INTL: Tcl source. */
2095 format = end;
2096 } else if (*format == '*') {
2097 if (objIndex >= objc) {
2098 goto badIndex;
2099 }
2100 if (Tcl_GetIntFromObj(interp, /* INTL: Tcl source. */
2101 objv[objIndex], &width) != TCL_OK) {
2102 goto fmtError;
2103 }
2104 if (width < 0) {
2105 width = -width;
2106 *newPtr = '-';
2107 gotMinus = 1;
2108 newPtr++;
2109 }
2110 objIndex++;
2111 format++;
2112 }
2113 if (width > 100000) {
2114 /*
2115 * Don't allow arbitrarily large widths: could cause core
2116 * dump when we try to allocate a zillion bytes of memory
2117 * below.
2118 */
2119
2120 width = 100000;
2121 } else if (width < 0) {
2122 width = 0;
2123 }
2124 if (width != 0) {
2125 TclFormatInt(newPtr, width); /* INTL: printf format. */
2126 while (*newPtr != 0) {
2127 newPtr++;
2128 }
2129 }
2130 if (*format == '.') {
2131 *newPtr = '.';
2132 newPtr++;
2133 format++;
2134 gotPrecision = 1;
2135 }
2136 if (isdigit(UCHAR(*format))) { /* INTL: Tcl source. */
2137 precision = strtoul(format, &end, 10); /* INTL: "C" locale. */
2138 format = end;
2139 } else if (*format == '*') {
2140 if (objIndex >= objc) {
2141 goto badIndex;
2142 }
2143 if (Tcl_GetIntFromObj(interp, /* INTL: Tcl source. */
2144 objv[objIndex], &precision) != TCL_OK) {
2145 goto fmtError;
2146 }
2147 objIndex++;
2148 format++;
2149 }
2150 if (gotPrecision) {
2151 TclFormatInt(newPtr, precision); /* INTL: printf format. */
2152 while (*newPtr != 0) {
2153 newPtr++;
2154 }
2155 }
2156 if (*format == 'l') {
2157 useWide = 1;
2158 /*
2159 * Only add a 'll' modifier for integer values as it makes
2160 * some libc's go into spasm otherwise. [Bug #702622]
2161 */
2162 switch (format[1]) {
2163 case 'i':
2164 case 'd':
2165 case 'o':
2166 case 'u':
2167 case 'x':
2168 case 'X':
2169 strcpy(newPtr, TCL_LL_MODIFIER);
2170 newPtr += TCL_LL_MODIFIER_SIZE;
2171 }
2172 format++;
2173 } else if (*format == 'h') {
2174 useShort = 1;
2175 *newPtr = 'h';
2176 newPtr++;
2177 format++;
2178 }
2179 *newPtr = *format;
2180 newPtr++;
2181 *newPtr = 0;
2182 if (objIndex >= objc) {
2183 goto badIndex;
2184 }
2185 switch (*format) {
2186 case 'i':
2187 newPtr[-1] = 'd';
2188 case 'd':
2189 case 'o':
2190 case 'u':
2191 case 'x':
2192 case 'X':
2193 size = 40 + precision;
2194
2195 /*
2196 * Peek what kind of value we've got so as not to be
2197 * converting stuff unduly. [Bug #699060]
2198 */
2199 if (objv[objIndex]->typePtr == &tclWideIntType) {
2200 Tcl_GetWideIntFromObj(NULL, objv[objIndex], &wideValue);
2201 if (useWide) {
2202 whichValue = WIDE_VALUE;
2203 break;
2204 } else {
2205 whichValue = INT_VALUE;
2206 if (wideValue>ULONG_MAX || wideValue<LONG_MIN) {
2207 /*
2208 * Value too big for type. Generate an error.
2209 */
2210 Tcl_GetLongFromObj(interp, objv[objIndex], &intValue);
2211 goto fmtError;
2212 }
2213 intValue = Tcl_WideAsLong(wideValue);
2214 }
2215 } else if (objv[objIndex]->typePtr == &tclIntType) {
2216 Tcl_GetLongFromObj(NULL, objv[objIndex], &intValue);
2217 if (useWide) {
2218 whichValue = WIDE_VALUE;
2219 wideValue = Tcl_LongAsWide(intValue);
2220 break;
2221 } else {
2222 whichValue = INT_VALUE;
2223 }
2224 } else {
2225 /*
2226 * No existing numeric interpretation, so we can
2227 * coerce to whichever is convenient.
2228 */
2229 if (useWide) {
2230 if (Tcl_GetWideIntFromObj(interp, /* INTL: Tcl source. */
2231 objv[objIndex], &wideValue) != TCL_OK) {
2232 goto fmtError;
2233 }
2234 whichValue = WIDE_VALUE;
2235 break;
2236 }
2237 if (Tcl_GetLongFromObj(interp, /* INTL: Tcl source. */
2238 objv[objIndex], &intValue) != TCL_OK) {
2239 goto fmtError;
2240 }
2241 }
2242 #if (LONG_MAX > INT_MAX)
2243 /*
2244 * Add the 'l' for long format type because we are on an
2245 * LP64 archtecture and we are really going to pass a long
2246 * argument to sprintf.
2247 */
2248 newPtr++;
2249 *newPtr = 0;
2250 newPtr[-1] = newPtr[-2];
2251 newPtr[-2] = 'l';
2252 #endif /* LONG_MAX > INT_MAX */
2253 whichValue = INT_VALUE;
2254 break;
2255 case 's':
2256 /*
2257 * Compute the length of the string in characters and add
2258 * any additional space required by the field width. All
2259 * of the extra characters will be spaces, so one byte per
2260 * character is adequate.
2261 */
2262
2263 whichValue = STRING_VALUE;
2264 ptrValue = Tcl_GetStringFromObj(objv[objIndex], &size);
2265 stringLen = Tcl_NumUtfChars(ptrValue, size);
2266 if (gotPrecision && (precision < stringLen)) {
2267 stringLen = precision;
2268 }
2269 size = Tcl_UtfAtIndex(ptrValue, stringLen) - ptrValue;
2270 if (width > stringLen) {
2271 size += (width - stringLen);
2272 }
2273 break;
2274 case 'c':
2275 if (Tcl_GetLongFromObj(interp, /* INTL: Tcl source. */
2276 objv[objIndex], &intValue) != TCL_OK) {
2277 goto fmtError;
2278 }
2279 whichValue = CHAR_VALUE;
2280 size = width + TCL_UTF_MAX;
2281 break;
2282 case 'e':
2283 case 'E':
2284 case 'f':
2285 case 'g':
2286 case 'G':
2287 if (Tcl_GetDoubleFromObj(interp, /* INTL: Tcl source. */
2288 objv[objIndex], &doubleValue) != TCL_OK) {
2289 goto fmtError;
2290 }
2291 whichValue = DOUBLE_VALUE;
2292 size = MAX_FLOAT_SIZE;
2293 if (precision > 10) {
2294 size += precision;
2295 }
2296 break;
2297 case 0:
2298 Tcl_SetResult(interp,
2299 "format string ended in middle of field specifier",
2300 TCL_STATIC);
2301 goto fmtError;
2302 default:
2303 {
2304 char buf[40];
2305
2306 sprintf(buf, "bad field specifier \"%c\"", *format);
2307 Tcl_SetResult(interp, buf, TCL_VOLATILE);
2308 goto fmtError;
2309 }
2310 }
2311 objIndex++;
2312 format++;
2313
2314 /*
2315 * Make sure that there's enough space to hold the formatted
2316 * result, then format it.
2317 */
2318
2319 doField:
2320 if (width > size) {
2321 size = width;
2322 }
2323 if (noPercent) {
2324 Tcl_AppendToObj(resultPtr, ptrValue, size);
2325 } else {
2326 if (size > dstSize) {
2327 if (dst != staticBuf) {
2328 ckfree(dst);
2329 }
2330 dst = (char *) ckalloc((unsigned) (size + 1));
2331 dstSize = size;
2332 }
2333 switch (whichValue) {
2334 case DOUBLE_VALUE:
2335 sprintf(dst, newFormat, doubleValue); /* INTL: user locale. */
2336 break;
2337 case WIDE_VALUE:
2338 sprintf(dst, newFormat, wideValue);
2339 break;
2340 case INT_VALUE:
2341 if (useShort) {
2342 sprintf(dst, newFormat, (short) intValue);
2343 } else {
2344 sprintf(dst, newFormat, intValue);
2345 }
2346 break;
2347 case CHAR_VALUE: {
2348 char *ptr;
2349 char padChar = (gotZero ? '0' : ' ');
2350 ptr = dst;
2351 if (!gotMinus) {
2352 for ( ; --width > 0; ptr++) {
2353 *ptr = padChar;
2354 }
2355 }
2356 ptr += Tcl_UniCharToUtf(intValue, ptr);
2357 for ( ; --width > 0; ptr++) {
2358 *ptr = padChar;
2359 }
2360 *ptr = '\0';
2361 break;
2362 }
2363 case STRING_VALUE: {
2364 char *ptr;
2365 char padChar = (gotZero ? '0' : ' ');
2366 int pad;
2367
2368 ptr = dst;
2369 if (width > stringLen) {
2370 pad = width - stringLen;
2371 } else {
2372 pad = 0;
2373 }
2374
2375 if (!gotMinus) {
2376 while (pad > 0) {
2377 *ptr++ = padChar;
2378 pad--;
2379 }
2380 }
2381
2382 size = Tcl_UtfAtIndex(ptrValue, stringLen) - ptrValue;
2383 if (size) {
2384 memcpy(ptr, ptrValue, (size_t) size);
2385 ptr += size;
2386 }
2387 while (pad > 0) {
2388 *ptr++ = padChar;
2389 pad--;
2390 }
2391 *ptr = '\0';
2392 break;
2393 }
2394 default:
2395 sprintf(dst, newFormat, ptrValue);
2396 break;
2397 }
2398 Tcl_AppendToObj(resultPtr, dst, -1);
2399 }
2400 }
2401
2402 Tcl_SetObjResult(interp, resultPtr);
2403 if (dst != staticBuf) {
2404 ckfree(dst);
2405 }
2406 return TCL_OK;
2407
2408 mixedXPG:
2409 Tcl_SetResult(interp,
2410 "cannot mix \"%\" and \"%n$\" conversion specifiers", TCL_STATIC);
2411 goto fmtError;
2412
2413 badIndex:
2414 if (gotXpg) {
2415 Tcl_SetResult(interp,
2416 "\"%n$\" argument index out of range", TCL_STATIC);
2417 } else {
2418 Tcl_SetResult(interp,
2419 "not enough arguments for all format specifiers", TCL_STATIC);
2420 }
2421
2422 fmtError:
2423 if (dst != staticBuf) {
2424 ckfree(dst);
2425 }
2426 Tcl_DecrRefCount(resultPtr);
2427 return TCL_ERROR;
2428 }