Debian Codegraph @

generic/tclBinary.c

raw
1 /*
2 * tclBinary.c --
3 *
4 * This file contains the implementation of the "binary" Tcl built-in
5 * command and the Tcl binary data object.
6 *
7 * Copyright (c) 1997 Sun Microsystems, Inc.
8 * Copyright (c) 1998-1999 Scriptics Corporation.
9 *
10 * See the file "license.terms" for information on usage and redistribution of
11 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 */
13
14 #include "tclInt.h"
15 #include "tommath.h"
16
17 #include <math.h>
18
19 /*
20 * The following constants are used by GetFormatSpec to indicate various
21 * special conditions in the parsing of a format specifier.
22 */
23
24 #define BINARY_ALL -1 /* Use all elements in the argument. */
25 #define BINARY_NOCOUNT -2 /* No count was specified in format. */
26
27 /*
28 * The following flags may be OR'ed together and returned by GetFormatSpec
29 */
30
31 #define BINARY_SIGNED 0 /* Field to be read as signed data */
32 #define BINARY_UNSIGNED 1 /* Field to be read as unsigned data */
33
34 /*
35 * The following defines the maximum number of different (integer) numbers
36 * placed in the object cache by 'binary scan' before it bails out and
37 * switches back to Plan A (creating a new object for each value.)
38 * Theoretically, it would be possible to keep the cache about for the values
39 * that are already in it, but that makes the code slower in practice when
40 * overflow happens, and makes little odds the rest of the time (as measured
41 * on my machine.) It is also slower (on the sample I tried at least) to grow
42 * the cache to hold all items we might want to put in it; presumably the
43 * extra cost of managing the memory for the enlarged table outweighs the
44 * benefit from allocating fewer objects. This is probably because as the
45 * number of objects increases, the likelihood of reuse of any particular one
46 * drops, and there is very little gain from larger maximum cache sizes (the
47 * value below is chosen to allow caching to work in full with conversion of
48 * bytes.) - DKF
49 */
50
51 #define BINARY_SCAN_MAX_CACHE 260
52
53 /*
54 * Prototypes for local procedures defined in this file:
55 */
56
57 static void DupByteArrayInternalRep(Tcl_Obj *srcPtr,
58 Tcl_Obj *copyPtr);
59 static int FormatNumber(Tcl_Interp *interp, int type,
60 Tcl_Obj *src, unsigned char **cursorPtr);
61 static void FreeByteArrayInternalRep(Tcl_Obj *objPtr);
62 static int GetFormatSpec(const char **formatPtr, char *cmdPtr,
63 int *countPtr, int *flagsPtr);
64 static Tcl_Obj * ScanNumber(unsigned char *buffer, int type,
65 int flags, Tcl_HashTable **numberCachePtr);
66 static int SetByteArrayFromAny(Tcl_Interp *interp,
67 Tcl_Obj *objPtr);
68 static void UpdateStringOfByteArray(Tcl_Obj *listPtr);
69 static void DeleteScanNumberCache(Tcl_HashTable *numberCachePtr);
70 static int NeedReversing(int format);
71 static void CopyNumber(const void *from, void *to,
72 unsigned int length, int type);
73 /* Binary ensemble commands */
74 static Tcl_ObjCmdProc BinaryFormatCmd;
75 static Tcl_ObjCmdProc BinaryScanCmd;
76 /* Binary encoding sub-ensemble commands */
77 static Tcl_ObjCmdProc BinaryEncodeHex;
78 static Tcl_ObjCmdProc BinaryDecodeHex;
79 static Tcl_ObjCmdProc BinaryEncode64;
80 static Tcl_ObjCmdProc BinaryDecode64;
81 static Tcl_ObjCmdProc BinaryEncodeUu;
82 static Tcl_ObjCmdProc BinaryDecodeUu;
83
84 /*
85 * The following tables are used by the binary encoders
86 */
87
88 static const char HexDigits[16] = {
89 '0', '1', '2', '3', '4', '5', '6', '7',
90 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
91 };
92
93 static const char UueDigits[65] = {
94 '`', '!', '"', '#', '$', '%', '&', '\'',
95 '(', ')', '*', '+', ',', '-', '.', '/',
96 '0', '1', '2', '3', '4', '5', '6', '7',
97 '8', '9', ':', ';', '<', '=', '>', '?',
98 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
99 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
100 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
101 'X', 'Y', 'Z', '[', '\\',']', '^', '_',
102 '`'
103 };
104
105 static const char B64Digits[65] = {
106 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
107 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
108 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
109 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
110 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
111 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
112 'w', 'x', 'y', 'z', '0', '1', '2', '3',
113 '4', '5', '6', '7', '8', '9', '+', '/',
114 '='
115 };
116
117 /*
118 * How to construct the ensembles.
119 */
120
121 static const EnsembleImplMap binaryMap[] = {
122 { "format", BinaryFormatCmd, TclCompileBasicMin1ArgCmd, NULL, NULL, 0 },
123 { "scan", BinaryScanCmd, TclCompileBasicMin2ArgCmd, NULL, NULL, 0 },
124 { "encode", NULL, NULL, NULL, NULL, 0 },
125 { "decode", NULL, NULL, NULL, NULL, 0 },
126 { NULL, NULL, NULL, NULL, NULL, 0 }
127 };
128 static const EnsembleImplMap encodeMap[] = {
129 { "hex", BinaryEncodeHex, TclCompileBasic1ArgCmd, NULL, NULL, 0 },
130 { "uuencode", BinaryEncodeUu, NULL, NULL, NULL, 0 },
131 { "base64", BinaryEncode64, NULL, NULL, NULL, 0 },
132 { NULL, NULL, NULL, NULL, NULL, 0 }
133 };
134 static const EnsembleImplMap decodeMap[] = {
135 { "hex", BinaryDecodeHex, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0 },
136 { "uuencode", BinaryDecodeUu, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0 },
137 { "base64", BinaryDecode64, TclCompileBasic1Or2ArgCmd, NULL, NULL, 0 },
138 { NULL, NULL, NULL, NULL, NULL, 0 }
139 };
140
141 /*
142 * The following object type represents an array of bytes. An array of bytes
143 * is not equivalent to an internationalized string. Conceptually, a string is
144 * an array of 16-bit quantities organized as a sequence of properly formed
145 * UTF-8 characters, while a ByteArray is an array of 8-bit quantities.
146 * Accessor functions are provided to convert a ByteArray to a String or a
147 * String to a ByteArray. Two or more consecutive bytes in an array of bytes
148 * may look like a single UTF-8 character if the array is casually treated as
149 * a string. But obtaining the String from a ByteArray is guaranteed to
150 * produced properly formed UTF-8 sequences so that there is a one-to-one map
151 * between bytes and characters.
152 *
153 * Converting a ByteArray to a String proceeds by casting each byte in the
154 * array to a 16-bit quantity, treating that number as a Unicode character,
155 * and storing the UTF-8 version of that Unicode character in the String. For
156 * ByteArrays consisting entirely of values 1..127, the corresponding String
157 * representation is the same as the ByteArray representation.
158 *
159 * Converting a String to a ByteArray proceeds by getting the Unicode
160 * representation of each character in the String, casting it to a byte by
161 * truncating the upper 8 bits, and then storing the byte in the ByteArray.
162 * Converting from ByteArray to String and back to ByteArray is not lossy, but
163 * converting an arbitrary String to a ByteArray may be.
164 */
165
166 const Tcl_ObjType tclByteArrayType = {
167 "bytearray",
168 FreeByteArrayInternalRep,
169 DupByteArrayInternalRep,
170 UpdateStringOfByteArray,
171 SetByteArrayFromAny
172 };
173
174 /*
175 * The following structure is the internal rep for a ByteArray object. Keeps
176 * track of how much memory has been used and how much has been allocated for
177 * the byte array to enable growing and shrinking of the ByteArray object with
178 * fewer mallocs.
179 */
180
181 typedef struct ByteArray {
182 unsigned int used; /* The number of bytes used in the byte
183 * array. */
184 unsigned int allocated; /* The number of bytes allocated for storage
185 * of the following "bytes" field. */
186 unsigned char bytes[TCLFLEXARRAY];
187 /* The array of bytes. The actual size of this
188 * field is stored in the 'allocated' field
189 * above. */
190 } ByteArray;
191
192 #define BYTEARRAY_SIZE(len) \
193 (((unsigned)TclOffset(ByteArray, bytes) + (len)))
194 #define GET_BYTEARRAY(objPtr) \
195 ((ByteArray *) (objPtr)->internalRep.twoPtrValue.ptr1)
196 #define SET_BYTEARRAY(objPtr, baPtr) \
197 (objPtr)->internalRep.twoPtrValue.ptr1 = (void *) (baPtr)
198
199
200 /*
201 *----------------------------------------------------------------------
202 *
203 * Tcl_NewByteArrayObj --
204 *
205 * This procedure is creates a new ByteArray object and initializes it
206 * from the given array of bytes.
207 *
208 * Results:
209 * The newly created object is returned. This object has no initial
210 * string representation. The returned object has a ref count of 0.
211 *
212 * Side effects:
213 * Memory allocated for new object and copy of byte array argument.
214 *
215 *----------------------------------------------------------------------
216 */
217
218 #undef Tcl_NewByteArrayObj
219
220 Tcl_Obj *
221 Tcl_NewByteArrayObj(
222 const unsigned char *bytes, /* The array of bytes used to initialize the
223 * new object. */
224 int numBytes) /* Number of bytes in the array,
225 * must be >= 0. */
226 {
227 #ifdef TCL_MEM_DEBUG
228 return Tcl_DbNewByteArrayObj(bytes, numBytes, "unknown", 0);
229 #else /* if not TCL_MEM_DEBUG */
230 Tcl_Obj *objPtr;
231
232 TclNewObj(objPtr);
233 Tcl_SetByteArrayObj(objPtr, bytes, numBytes);
234 return objPtr;
235 #endif /* TCL_MEM_DEBUG */
236 }
237
238 /*
239 *----------------------------------------------------------------------
240 *
241 * Tcl_DbNewByteArrayObj --
242 *
243 * This procedure is normally called when debugging: i.e., when
244 * TCL_MEM_DEBUG is defined. It is the same as the Tcl_NewByteArrayObj
245 * above except that it calls Tcl_DbCkalloc directly with the file name
246 * and line number from its caller. This simplifies debugging since then
247 * the [memory active] command will report the correct file name and line
248 * number when reporting objects that haven't been freed.
249 *
250 * When TCL_MEM_DEBUG is not defined, this procedure just returns the
251 * result of calling Tcl_NewByteArrayObj.
252 *
253 * Results:
254 * The newly created object is returned. This object has no initial
255 * string representation. The returned object has a ref count of 0.
256 *
257 * Side effects:
258 * Memory allocated for new object and copy of byte array argument.
259 *
260 *----------------------------------------------------------------------
261 */
262
263 Tcl_Obj *
264 Tcl_DbNewByteArrayObj(
265 const unsigned char *bytes, /* The array of bytes used to initialize the
266 * new object. */
267 int numBytes, /* Number of bytes in the array,
268 * must be >= 0. */
269 const char *file, /* The name of the source file calling this
270 * procedure; used for debugging. */
271 int line) /* Line number in the source file; used for
272 * debugging. */
273 {
274 #ifdef TCL_MEM_DEBUG
275 Tcl_Obj *objPtr;
276
277 TclDbNewObj(objPtr, file, line);
278 Tcl_SetByteArrayObj(objPtr, bytes, numBytes);
279 return objPtr;
280 #else /* if not TCL_MEM_DEBUG */
281 return Tcl_NewByteArrayObj(bytes, numBytes);
282 #endif /* TCL_MEM_DEBUG */
283 }
284
285 /*
286 *---------------------------------------------------------------------------
287 *
288 * Tcl_SetByteArrayObj --
289 *
290 * Modify an object to be a ByteArray object and to have the specified
291 * array of bytes as its value.
292 *
293 * Results:
294 * None.
295 *
296 * Side effects:
297 * The object's old string rep and internal rep is freed. Memory
298 * allocated for copy of byte array argument.
299 *
300 *----------------------------------------------------------------------
301 */
302
303 void
304 Tcl_SetByteArrayObj(
305 Tcl_Obj *objPtr, /* Object to initialize as a ByteArray. */
306 const unsigned char *bytes, /* The array of bytes to use as the new value.
307 * May be NULL even if numBytes > 0. */
308 int numBytes) /* Number of bytes in the array,
309 * must be >= 0 */
310 {
311 ByteArray *byteArrayPtr;
312
313 if (Tcl_IsShared(objPtr)) {
314 Tcl_Panic("%s called with shared object", "Tcl_SetByteArrayObj");
315 }
316 TclFreeIntRep(objPtr);
317 TclInvalidateStringRep(objPtr);
318
319 if (numBytes < 0) {
320 numBytes = 0;
321 }
322 byteArrayPtr = (ByteArray *)ckalloc(BYTEARRAY_SIZE(numBytes));
323 byteArrayPtr->used = numBytes;
324 byteArrayPtr->allocated = numBytes;
325
326 if ((bytes != NULL) && (numBytes > 0)) {
327 memcpy(byteArrayPtr->bytes, bytes, numBytes);
328 }
329 objPtr->typePtr = &tclByteArrayType;
330 SET_BYTEARRAY(objPtr, byteArrayPtr);
331 }
332
333 /*
334 *----------------------------------------------------------------------
335 *
336 * Tcl_GetByteArrayFromObj --
337 *
338 * Attempt to get the array of bytes from the Tcl object. If the object
339 * is not already a ByteArray object, an attempt will be made to convert
340 * it to one.
341 *
342 * Results:
343 * Pointer to array of bytes representing the ByteArray object.
344 *
345 * Side effects:
346 * Frees old internal rep. Allocates memory for new internal rep.
347 *
348 *----------------------------------------------------------------------
349 */
350
351 unsigned char *
352 Tcl_GetByteArrayFromObj(
353 Tcl_Obj *objPtr, /* The ByteArray object. */
354 int *numBytesPtr) /* If non-NULL, write the number of bytes
355 * in the array here */
356 {
357 ByteArray *baPtr;
358
359 if (objPtr->typePtr != &tclByteArrayType) {
360 SetByteArrayFromAny(NULL, objPtr);
361 }
362 baPtr = GET_BYTEARRAY(objPtr);
363
364 if (numBytesPtr != NULL) {
365 *numBytesPtr = baPtr->used;
366 }
367 return (unsigned char *)baPtr->bytes;
368 }
369
370 /*
371 *----------------------------------------------------------------------
372 *
373 * Tcl_SetByteArrayLength --
374 *
375 * This procedure changes the length of the byte array for this object.
376 * Once the caller has set the length of the array, it is acceptable to
377 * directly modify the bytes in the array up until Tcl_GetStringFromObj()
378 * has been called on this object.
379 *
380 * Results:
381 * The new byte array of the specified length.
382 *
383 * Side effects:
384 * Allocates enough memory for an array of bytes of the requested size.
385 * When growing the array, the old array is copied to the new array; new
386 * bytes are undefined. When shrinking, the old array is truncated to the
387 * specified length.
388 *
389 *----------------------------------------------------------------------
390 */
391
392 unsigned char *
393 Tcl_SetByteArrayLength(
394 Tcl_Obj *objPtr, /* The ByteArray object. */
395 int numBytes) /* Number of bytes in resized array */
396 {
397 ByteArray *byteArrayPtr;
398
399 if (Tcl_IsShared(objPtr)) {
400 Tcl_Panic("%s called with shared object", "Tcl_SetByteArrayLength");
401 }
402 if (objPtr->typePtr != &tclByteArrayType) {
403 SetByteArrayFromAny(NULL, objPtr);
404 }
405 if (numBytes < 0) {
406 numBytes = 0;
407 }
408 byteArrayPtr = GET_BYTEARRAY(objPtr);
409 if ((unsigned int)numBytes > byteArrayPtr->allocated) {
410 byteArrayPtr = (ByteArray *)ckrealloc(byteArrayPtr, BYTEARRAY_SIZE(numBytes));
411 byteArrayPtr->allocated = numBytes;
412 SET_BYTEARRAY(objPtr, byteArrayPtr);
413 }
414 TclInvalidateStringRep(objPtr);
415 byteArrayPtr->used = numBytes;
416 return byteArrayPtr->bytes;
417 }
418
419 /*
420 *----------------------------------------------------------------------
421 *
422 * SetByteArrayFromAny --
423 *
424 * Generate the ByteArray internal rep from the string rep.
425 *
426 * Results:
427 * The return value is always TCL_OK.
428 *
429 * Side effects:
430 * A ByteArray object is stored as the internal rep of objPtr.
431 *
432 *----------------------------------------------------------------------
433 */
434
435 static int
436 SetByteArrayFromAny(
437 Tcl_Interp *interp, /* Not used. */
438 Tcl_Obj *objPtr) /* The object to convert to type ByteArray. */
439 {
440 int length;
441 const char *src, *srcEnd;
442 unsigned char *dst;
443 ByteArray *byteArrayPtr;
444 Tcl_UniChar ch = 0;
445
446 if (objPtr->typePtr != &tclByteArrayType) {
447 src = TclGetStringFromObj(objPtr, &length);
448 srcEnd = src + length;
449
450 byteArrayPtr = (ByteArray *)ckalloc(BYTEARRAY_SIZE(length));
451 for (dst = byteArrayPtr->bytes; src < srcEnd; ) {
452 src += TclUtfToUniChar(src, &ch);
453 *dst++ = UCHAR(ch);
454 }
455
456 byteArrayPtr->used = dst - byteArrayPtr->bytes;
457 byteArrayPtr->allocated = length;
458
459 TclFreeIntRep(objPtr);
460 objPtr->typePtr = &tclByteArrayType;
461 SET_BYTEARRAY(objPtr, byteArrayPtr);
462 }
463 return TCL_OK;
464 }
465
466 /*
467 *----------------------------------------------------------------------
468 *
469 * FreeByteArrayInternalRep --
470 *
471 * Deallocate the storage associated with a ByteArray data object's
472 * internal representation.
473 *
474 * Results:
475 * None.
476 *
477 * Side effects:
478 * Frees memory.
479 *
480 *----------------------------------------------------------------------
481 */
482
483 static void
484 FreeByteArrayInternalRep(
485 Tcl_Obj *objPtr) /* Object with internal rep to free. */
486 {
487 ckfree(GET_BYTEARRAY(objPtr));
488 objPtr->typePtr = NULL;
489 }
490
491 /*
492 *----------------------------------------------------------------------
493 *
494 * DupByteArrayInternalRep --
495 *
496 * Initialize the internal representation of a ByteArray Tcl_Obj to a
497 * copy of the internal representation of an existing ByteArray object.
498 *
499 * Results:
500 * None.
501 *
502 * Side effects:
503 * Allocates memory.
504 *
505 *----------------------------------------------------------------------
506 */
507
508 static void
509 DupByteArrayInternalRep(
510 Tcl_Obj *srcPtr, /* Object with internal rep to copy. */
511 Tcl_Obj *copyPtr) /* Object with internal rep to set. */
512 {
513 unsigned int length;
514 ByteArray *srcArrayPtr, *copyArrayPtr;
515
516 srcArrayPtr = GET_BYTEARRAY(srcPtr);
517 length = srcArrayPtr->used;
518
519 copyArrayPtr = (ByteArray *)ckalloc(BYTEARRAY_SIZE(length));
520 copyArrayPtr->used = length;
521 copyArrayPtr->allocated = length;
522 memcpy(copyArrayPtr->bytes, srcArrayPtr->bytes, length);
523 SET_BYTEARRAY(copyPtr, copyArrayPtr);
524
525 copyPtr->typePtr = &tclByteArrayType;
526 }
527
528 /*
529 *----------------------------------------------------------------------
530 *
531 * UpdateStringOfByteArray --
532 *
533 * Update the string representation for a ByteArray data object. Note:
534 * This procedure does not invalidate an existing old string rep so
535 * storage will be lost if this has not already been done.
536 *
537 * Results:
538 * None.
539 *
540 * Side effects:
541 * The object's string is set to a valid string that results from the
542 * ByteArray-to-string conversion.
543 *
544 * The object becomes a string object -- the internal rep is discarded
545 * and the typePtr becomes NULL.
546 *
547 *----------------------------------------------------------------------
548 */
549
550 static void
551 UpdateStringOfByteArray(
552 Tcl_Obj *objPtr) /* ByteArray object whose string rep to
553 * update. */
554 {
555 unsigned int i, length, size;
556 unsigned char *src;
557 char *dst;
558 ByteArray *byteArrayPtr;
559
560 byteArrayPtr = GET_BYTEARRAY(objPtr);
561 src = byteArrayPtr->bytes;
562 length = byteArrayPtr->used;
563
564 /*
565 * How much space will string rep need?
566 */
567
568 size = length;
569 for (i = 0; i < length && size <= INT_MAX; i++) {
570 if ((src[i] == 0) || (src[i] > 127)) {
571 size++;
572 }
573 }
574 if (size > INT_MAX) {
575 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
576 }
577
578 dst = (char *)ckalloc(size + 1U);
579 objPtr->bytes = dst;
580 objPtr->length = size;
581
582 if (size == length) {
583 memcpy(dst, src, size);
584 dst[size] = '\0';
585 } else {
586 for (i = 0; i < length; i++) {
587 dst += Tcl_UniCharToUtf(src[i], dst);
588 }
589 *dst = '\0';
590 }
591 }
592
593 /*
594 *----------------------------------------------------------------------
595 *
596 * TclAppendBytesToByteArray --
597 *
598 * This function appends an array of bytes to a byte array object. Note
599 * that the object *must* be unshared, and the array of bytes *must not*
600 * refer to the object being appended to.
601 *
602 * Results:
603 * None.
604 *
605 * Side effects:
606 * Allocates enough memory for an array of bytes of the requested total
607 * size, or possibly larger. [Bug 2992970]
608 *
609 *----------------------------------------------------------------------
610 */
611
612 void
613 TclAppendBytesToByteArray(
614 Tcl_Obj *objPtr,
615 const unsigned char *bytes,
616 int len)
617 {
618 ByteArray *byteArrayPtr;
619 unsigned int needed;
620
621 if (Tcl_IsShared(objPtr)) {
622 Tcl_Panic("%s called with shared object","TclAppendBytesToByteArray");
623 }
624 if (len < 0) {
625 Tcl_Panic("%s must be called with definite number of bytes to append",
626 "TclAppendBytesToByteArray");
627 }
628 if (len == 0) {
629 /*
630 * Append zero bytes is a no-op.
631 */
632
633 return;
634 }
635 if (objPtr->typePtr != &tclByteArrayType) {
636 SetByteArrayFromAny(NULL, objPtr);
637 }
638 byteArrayPtr = GET_BYTEARRAY(objPtr);
639
640 if ((unsigned int)len > INT_MAX - byteArrayPtr->used) {
641 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
642 }
643
644 needed = byteArrayPtr->used + len;
645 /*
646 * If we need to, resize the allocated space in the byte array.
647 */
648
649 if (needed > byteArrayPtr->allocated) {
650 ByteArray *ptr = NULL;
651 unsigned int attempt;
652
653 if (needed <= INT_MAX/2) {
654 /*
655 * Try to allocate double the total space that is needed.
656 */
657
658 attempt = 2 * needed;
659 ptr = (ByteArray *)attemptckrealloc(byteArrayPtr, BYTEARRAY_SIZE(attempt));
660 }
661 if (ptr == NULL) {
662 /*
663 * Try to allocate double the increment that is needed (plus).
664 */
665
666 unsigned int limit = INT_MAX - needed;
667 unsigned int extra = len + TCL_MIN_GROWTH;
668 int growth = (int) ((extra > limit) ? limit : extra);
669
670 attempt = needed + growth;
671 ptr = (ByteArray *)attemptckrealloc(byteArrayPtr, BYTEARRAY_SIZE(attempt));
672 }
673 if (ptr == NULL) {
674 /*
675 * Last chance: Try to allocate exactly what is needed.
676 */
677
678 attempt = needed;
679 ptr = (ByteArray *)ckrealloc(byteArrayPtr, BYTEARRAY_SIZE(attempt));
680 }
681 byteArrayPtr = ptr;
682 byteArrayPtr->allocated = attempt;
683 SET_BYTEARRAY(objPtr, byteArrayPtr);
684 }
685
686 if (bytes) {
687 memcpy(byteArrayPtr->bytes + byteArrayPtr->used, bytes, len);
688 }
689 byteArrayPtr->used += len;
690 TclInvalidateStringRep(objPtr);
691 }
692
693 /*
694 *----------------------------------------------------------------------
695 *
696 * TclInitBinaryCmd --
697 *
698 * This function is called to create the "binary" Tcl command. See the
699 * user documentation for details on what it does.
700 *
701 * Results:
702 * A command token for the new command.
703 *
704 * Side effects:
705 * Creates a new binary command as a mapped ensemble.
706 *
707 *----------------------------------------------------------------------
708 */
709
710 Tcl_Command
711 TclInitBinaryCmd(
712 Tcl_Interp *interp)
713 {
714 Tcl_Command binaryEnsemble;
715
716 binaryEnsemble = TclMakeEnsemble(interp, "binary", binaryMap);
717 TclMakeEnsemble(interp, "binary encode", encodeMap);
718 TclMakeEnsemble(interp, "binary decode", decodeMap);
719 return binaryEnsemble;
720 }
721
722 /*
723 *----------------------------------------------------------------------
724 *
725 * BinaryFormatCmd --
726 *
727 * This procedure implements the "binary format" Tcl command.
728 *
729 * Results:
730 * A standard Tcl result.
731 *
732 * Side effects:
733 * See the user documentation.
734 *
735 *----------------------------------------------------------------------
736 */
737
738 static int
739 BinaryFormatCmd(
740 ClientData dummy, /* Not used. */
741 Tcl_Interp *interp, /* Current interpreter. */
742 int objc, /* Number of arguments. */
743 Tcl_Obj *const objv[]) /* Argument objects. */
744 {
745 int arg; /* Index of next argument to consume. */
746 int value = 0; /* Current integer value to be packed.
747 * Initialized to avoid compiler warning. */
748 char cmd; /* Current format character. */
749 int count; /* Count associated with current format
750 * character. */
751 int flags; /* Format field flags */
752 const char *format; /* Pointer to current position in format
753 * string. */
754 Tcl_Obj *resultPtr = NULL; /* Object holding result buffer. */
755 unsigned char *buffer; /* Start of result buffer. */
756 unsigned char *cursor; /* Current position within result buffer. */
757 unsigned char *maxPos; /* Greatest position within result buffer that
758 * cursor has visited.*/
759 const char *errorString;
760 const char *errorValue, *str;
761 int offset, size, length;
762
763 if (objc < 2) {
764 Tcl_WrongNumArgs(interp, 1, objv, "formatString ?arg ...?");
765 return TCL_ERROR;
766 }
767
768 /*
769 * To avoid copying the data, we format the string in two passes. The
770 * first pass computes the size of the output buffer. The second pass
771 * places the formatted data into the buffer.
772 */
773
774 format = TclGetString(objv[1]);
775 arg = 2;
776 offset = 0;
777 length = 0;
778 while (*format != '\0') {
779 str = format;
780 flags = 0;
781 if (!GetFormatSpec(&format, &cmd, &count, &flags)) {
782 break;
783 }
784 switch (cmd) {
785 case 'a':
786 case 'A':
787 case 'b':
788 case 'B':
789 case 'h':
790 case 'H':
791 /*
792 * For string-type specifiers, the count corresponds to the number
793 * of bytes in a single argument.
794 */
795
796 if (arg >= objc) {
797 goto badIndex;
798 }
799 if (count == BINARY_ALL) {
800 Tcl_GetByteArrayFromObj(objv[arg], &count);
801 } else if (count == BINARY_NOCOUNT) {
802 count = 1;
803 }
804 arg++;
805 if (cmd == 'a' || cmd == 'A') {
806 offset += count;
807 } else if (cmd == 'b' || cmd == 'B') {
808 offset += (count + 7) / 8;
809 } else {
810 offset += (count + 1) / 2;
811 }
812 break;
813 case 'c':
814 size = 1;
815 goto doNumbers;
816 case 't':
817 case 's':
818 case 'S':
819 size = 2;
820 goto doNumbers;
821 case 'n':
822 case 'i':
823 case 'I':
824 size = 4;
825 goto doNumbers;
826 case 'm':
827 case 'w':
828 case 'W':
829 size = 8;
830 goto doNumbers;
831 case 'r':
832 case 'R':
833 case 'f':
834 size = sizeof(float);
835 goto doNumbers;
836 case 'q':
837 case 'Q':
838 case 'd':
839 size = sizeof(double);
840
841 doNumbers:
842 if (arg >= objc) {
843 goto badIndex;
844 }
845
846 /*
847 * For number-type specifiers, the count corresponds to the number
848 * of elements in the list stored in a single argument. If no
849 * count is specified, then the argument is taken as a single
850 * non-list value.
851 */
852
853 if (count == BINARY_NOCOUNT) {
854 arg++;
855 count = 1;
856 } else {
857 int listc;
858 Tcl_Obj **listv;
859
860 /*
861 * The macro evals its args more than once: avoid arg++
862 */
863
864 if (TclListObjGetElements(interp, objv[arg], &listc,
865 &listv) != TCL_OK) {
866 return TCL_ERROR;
867 }
868
869 if (count == BINARY_ALL) {
870 count = listc;
871 } else if (count > listc) {
872 Tcl_SetObjResult(interp, Tcl_NewStringObj(
873 "number of elements in list does not match count",
874 -1));
875 return TCL_ERROR;
876 }
877 arg++;
878 }
879 offset += count*size;
880 break;
881
882 case 'x':
883 if (count == BINARY_ALL) {
884 Tcl_SetObjResult(interp, Tcl_NewStringObj(
885 "cannot use \"*\" in format string with \"x\"", -1));
886 return TCL_ERROR;
887 } else if (count == BINARY_NOCOUNT) {
888 count = 1;
889 }
890 offset += count;
891 break;
892 case 'X':
893 if (count == BINARY_NOCOUNT) {
894 count = 1;
895 }
896 if ((count > offset) || (count == BINARY_ALL)) {
897 count = offset;
898 }
899 if (offset > length) {
900 length = offset;
901 }
902 offset -= count;
903 break;
904 case '@':
905 if (offset > length) {
906 length = offset;
907 }
908 if (count == BINARY_ALL) {
909 offset = length;
910 } else if (count == BINARY_NOCOUNT) {
911 goto badCount;
912 } else {
913 offset = count;
914 }
915 break;
916 default:
917 errorString = str;
918 goto badField;
919 }
920 }
921 if (offset > length) {
922 length = offset;
923 }
924 if (length == 0) {
925 return TCL_OK;
926 }
927
928 /*
929 * Prepare the result object by preallocating the calculated number of
930 * bytes and filling with nulls.
931 */
932
933 TclNewObj(resultPtr);
934 buffer = Tcl_SetByteArrayLength(resultPtr, length);
935 memset(buffer, 0, length);
936
937 /*
938 * Pack the data into the result object. Note that we can skip the error
939 * checking during this pass, since we have already parsed the string
940 * once.
941 */
942
943 arg = 2;
944 format = TclGetString(objv[1]);
945 cursor = buffer;
946 maxPos = cursor;
947 while (*format != 0) {
948 flags = 0;
949 if (!GetFormatSpec(&format, &cmd, &count, &flags)) {
950 break;
951 }
952 if ((count == 0) && (cmd != '@')) {
953 if (cmd != 'x') {
954 arg++;
955 }
956 continue;
957 }
958 switch (cmd) {
959 case 'a':
960 case 'A': {
961 char pad = (char) (cmd == 'a' ? '\0' : ' ');
962 unsigned char *bytes;
963
964 bytes = Tcl_GetByteArrayFromObj(objv[arg++], &length);
965
966 if (count == BINARY_ALL) {
967 count = length;
968 } else if (count == BINARY_NOCOUNT) {
969 count = 1;
970 }
971 if (length >= count) {
972 memcpy(cursor, bytes, count);
973 } else {
974 memcpy(cursor, bytes, length);
975 memset(cursor + length, pad, count - length);
976 }
977 cursor += count;
978 break;
979 }
980 case 'b':
981 case 'B': {
982 unsigned char *last;
983
984 str = TclGetStringFromObj(objv[arg], &length);
985 arg++;
986 if (count == BINARY_ALL) {
987 count = length;
988 } else if (count == BINARY_NOCOUNT) {
989 count = 1;
990 }
991 last = cursor + ((count + 7) / 8);
992 if (count > length) {
993 count = length;
994 }
995 value = 0;
996 errorString = "binary";
997 if (cmd == 'B') {
998 for (offset = 0; offset < count; offset++) {
999 value <<= 1;
1000 if (str[offset] == '1') {
1001 value |= 1;
1002 } else if (str[offset] != '0') {
1003 errorValue = str;
1004 Tcl_DecrRefCount(resultPtr);
1005 goto badValue;
1006 }
1007 if (((offset + 1) % 8) == 0) {
1008 *cursor++ = UCHAR(value);
1009 value = 0;
1010 }
1011 }
1012 } else {
1013 for (offset = 0; offset < count; offset++) {
1014 value >>= 1;
1015 if (str[offset] == '1') {
1016 value |= 128;
1017 } else if (str[offset] != '0') {
1018 errorValue = str;
1019 Tcl_DecrRefCount(resultPtr);
1020 goto badValue;
1021 }
1022 if (!((offset + 1) % 8)) {
1023 *cursor++ = UCHAR(value);
1024 value = 0;
1025 }
1026 }
1027 }
1028 if ((offset % 8) != 0) {
1029 if (cmd == 'B') {
1030 value <<= 8 - (offset % 8);
1031 } else {
1032 value >>= 8 - (offset % 8);
1033 }
1034 *cursor++ = UCHAR(value);
1035 }
1036 while (cursor < last) {
1037 *cursor++ = '\0';
1038 }
1039 break;
1040 }
1041 case 'h':
1042 case 'H': {
1043 unsigned char *last;
1044 int c;
1045
1046 str = TclGetStringFromObj(objv[arg], &length);
1047 arg++;
1048 if (count == BINARY_ALL) {
1049 count = length;
1050 } else if (count == BINARY_NOCOUNT) {
1051 count = 1;
1052 }
1053 last = cursor + ((count + 1) / 2);
1054 if (count > length) {
1055 count = length;
1056 }
1057 value = 0;
1058 errorString = "hexadecimal";
1059 if (cmd == 'H') {
1060 for (offset = 0; offset < count; offset++) {
1061 value <<= 4;
1062 if (!isxdigit(UCHAR(str[offset]))) { /* INTL: digit */
1063 errorValue = str;
1064 Tcl_DecrRefCount(resultPtr);
1065 goto badValue;
1066 }
1067 c = str[offset] - '0';
1068 if (c > 9) {
1069 c += ('0' - 'A') + 10;
1070 }
1071 if (c > 16) {
1072 c += ('A' - 'a');
1073 }
1074 value |= (c & 0xF);
1075 if (offset % 2) {
1076 *cursor++ = (char) value;
1077 value = 0;
1078 }
1079 }
1080 } else {
1081 for (offset = 0; offset < count; offset++) {
1082 value >>= 4;
1083
1084 if (!isxdigit(UCHAR(str[offset]))) { /* INTL: digit */
1085 errorValue = str;
1086 Tcl_DecrRefCount(resultPtr);
1087 goto badValue;
1088 }
1089 c = str[offset] - '0';
1090 if (c > 9) {
1091 c += ('0' - 'A') + 10;
1092 }
1093 if (c > 16) {
1094 c += ('A' - 'a');
1095 }
1096 value |= ((c << 4) & 0xF0);
1097 if (offset % 2) {
1098 *cursor++ = UCHAR(value & 0xFF);
1099 value = 0;
1100 }
1101 }
1102 }
1103 if (offset % 2) {
1104 if (cmd == 'H') {
1105 value <<= 4;
1106 } else {
1107 value >>= 4;
1108 }
1109 *cursor++ = UCHAR(value);
1110 }
1111
1112 while (cursor < last) {
1113 *cursor++ = '\0';
1114 }
1115 break;
1116 }
1117 case 'c':
1118 case 't':
1119 case 's':
1120 case 'S':
1121 case 'n':
1122 case 'i':
1123 case 'I':
1124 case 'm':
1125 case 'w':
1126 case 'W':
1127 case 'r':
1128 case 'R':
1129 case 'd':
1130 case 'q':
1131 case 'Q':
1132 case 'f': {
1133 int listc, i;
1134 Tcl_Obj **listv;
1135
1136 if (count == BINARY_NOCOUNT) {
1137 /*
1138 * Note that we are casting away the const-ness of objv, but
1139 * this is safe since we aren't going to modify the array.
1140 */
1141
1142 listv = (Tcl_Obj **) (objv + arg);
1143 listc = 1;
1144 count = 1;
1145 } else {
1146 TclListObjGetElements(interp, objv[arg], &listc, &listv);
1147 if (count == BINARY_ALL) {
1148 count = listc;
1149 }
1150 }
1151 arg++;
1152 for (i = 0; i < count; i++) {
1153 if (FormatNumber(interp, cmd, listv[i], &cursor) != TCL_OK) {
1154 Tcl_DecrRefCount(resultPtr);
1155 return TCL_ERROR;
1156 }
1157 }
1158 break;
1159 }
1160 case 'x':
1161 if (count == BINARY_NOCOUNT) {
1162 count = 1;
1163 }
1164 memset(cursor, 0, count);
1165 cursor += count;
1166 break;
1167 case 'X':
1168 if (cursor > maxPos) {
1169 maxPos = cursor;
1170 }
1171 if (count == BINARY_NOCOUNT) {
1172 count = 1;
1173 }
1174 if ((count == BINARY_ALL) || (count > (cursor - buffer))) {
1175 cursor = buffer;
1176 } else {
1177 cursor -= count;
1178 }
1179 break;
1180 case '@':
1181 if (cursor > maxPos) {
1182 maxPos = cursor;
1183 }
1184 if (count == BINARY_ALL) {
1185 cursor = maxPos;
1186 } else {
1187 cursor = buffer + count;
1188 }
1189 break;
1190 }
1191 }
1192 Tcl_SetObjResult(interp, resultPtr);
1193 return TCL_OK;
1194
1195 badValue:
1196 Tcl_ResetResult(interp);
1197 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1198 "expected %s string but got \"%s\" instead",
1199 errorString, errorValue));
1200 return TCL_ERROR;
1201
1202 badCount:
1203 errorString = "missing count for \"@\" field specifier";
1204 goto error;
1205
1206 badIndex:
1207 errorString = "not enough arguments for all format specifiers";
1208 goto error;
1209
1210 badField:
1211 {
1212 int ch;
1213 char buf[8] = "";
1214
1215 TclUtfToUCS4(errorString, &ch);
1216 buf[TclUCS4ToUtf(ch, buf)] = '\0';
1217 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1218 "bad field specifier \"%s\"", buf));
1219 return TCL_ERROR;
1220 }
1221
1222 error:
1223 Tcl_SetObjResult(interp, Tcl_NewStringObj(errorString, -1));
1224 return TCL_ERROR;
1225 }
1226
1227 /*
1228 *----------------------------------------------------------------------
1229 *
1230 * BinaryScanCmd --
1231 *
1232 * This procedure implements the "binary scan" Tcl command.
1233 *
1234 * Results:
1235 * A standard Tcl result.
1236 *
1237 * Side effects:
1238 * See the user documentation.
1239 *
1240 *----------------------------------------------------------------------
1241 */
1242
1243 static int
1244 BinaryScanCmd(
1245 ClientData dummy, /* Not used. */
1246 Tcl_Interp *interp, /* Current interpreter. */
1247 int objc, /* Number of arguments. */
1248 Tcl_Obj *const objv[]) /* Argument objects. */
1249 {
1250 int arg; /* Index of next argument to consume. */
1251 int value = 0; /* Current integer value to be packed.
1252 * Initialized to avoid compiler warning. */
1253 char cmd; /* Current format character. */
1254 int count; /* Count associated with current format
1255 * character. */
1256 int flags; /* Format field flags */
1257 const char *format; /* Pointer to current position in format
1258 * string. */
1259 Tcl_Obj *resultPtr = NULL; /* Object holding result buffer. */
1260 unsigned char *buffer; /* Start of result buffer. */
1261 const char *errorString;
1262 const char *str;
1263 int offset, size, length, i;
1264
1265 Tcl_Obj *valuePtr, *elementPtr;
1266 Tcl_HashTable numberCacheHash;
1267 Tcl_HashTable *numberCachePtr;
1268
1269 if (objc < 3) {
1270 Tcl_WrongNumArgs(interp, 1, objv,
1271 "value formatString ?varName ...?");
1272 return TCL_ERROR;
1273 }
1274 numberCachePtr = &numberCacheHash;
1275 Tcl_InitHashTable(numberCachePtr, TCL_ONE_WORD_KEYS);
1276 buffer = Tcl_GetByteArrayFromObj(objv[1], &length);
1277 format = TclGetString(objv[2]);
1278 arg = 3;
1279 offset = 0;
1280 while (*format != '\0') {
1281 str = format;
1282 flags = 0;
1283 if (!GetFormatSpec(&format, &cmd, &count, &flags)) {
1284 goto done;
1285 }
1286 switch (cmd) {
1287 case 'a':
1288 case 'A': {
1289 unsigned char *src;
1290
1291 if (arg >= objc) {
1292 DeleteScanNumberCache(numberCachePtr);
1293 goto badIndex;
1294 }
1295 if (count == BINARY_ALL) {
1296 count = length - offset;
1297 } else {
1298 if (count == BINARY_NOCOUNT) {
1299 count = 1;
1300 }
1301 if (count > (length - offset)) {
1302 goto done;
1303 }
1304 }
1305
1306 src = buffer + offset;
1307 size = count;
1308
1309 /*
1310 * Trim trailing nulls and spaces, if necessary.
1311 */
1312
1313 if (cmd == 'A') {
1314 while (size > 0) {
1315 if (src[size - 1] != '\0' && src[size - 1] != ' ') {
1316 break;
1317 }
1318 size--;
1319 }
1320 }
1321
1322 /*
1323 * Have to do this #ifdef-fery because (as part of defining
1324 * Tcl_NewByteArrayObj) we removed the #def that hides this stuff
1325 * normally. If this code ever gets copied to another file, it
1326 * should be changed back to the simpler version.
1327 */
1328
1329 #ifdef TCL_MEM_DEBUG
1330 valuePtr = Tcl_DbNewByteArrayObj(src, size, __FILE__, __LINE__);
1331 #else
1332 valuePtr = Tcl_NewByteArrayObj(src, size);
1333 #endif /* TCL_MEM_DEBUG */
1334
1335 resultPtr = Tcl_ObjSetVar2(interp, objv[arg], NULL, valuePtr,
1336 TCL_LEAVE_ERR_MSG);
1337 arg++;
1338 if (resultPtr == NULL) {
1339 DeleteScanNumberCache(numberCachePtr);
1340 return TCL_ERROR;
1341 }
1342 offset += count;
1343 break;
1344 }
1345 case 'b':
1346 case 'B': {
1347 unsigned char *src;
1348 char *dest;
1349
1350 if (arg >= objc) {
1351 DeleteScanNumberCache(numberCachePtr);
1352 goto badIndex;
1353 }
1354 if (count == BINARY_ALL) {
1355 count = (length - offset) * 8;
1356 } else {
1357 if (count == BINARY_NOCOUNT) {
1358 count = 1;
1359 }
1360 if (count > (length - offset) * 8) {
1361 goto done;
1362 }
1363 }
1364 src = buffer + offset;
1365 TclNewObj(valuePtr);
1366 Tcl_SetObjLength(valuePtr, count);
1367 dest = TclGetString(valuePtr);
1368
1369 if (cmd == 'b') {
1370 for (i = 0; i < count; i++) {
1371 if (i % 8) {
1372 value >>= 1;
1373 } else {
1374 value = *src++;
1375 }
1376 *dest++ = (char) ((value & 1) ? '1' : '0');
1377 }
1378 } else {
1379 for (i = 0; i < count; i++) {
1380 if (i % 8) {
1381 value <<= 1;
1382 } else {
1383 value = *src++;
1384 }
1385 *dest++ = (char) ((value & 0x80) ? '1' : '0');
1386 }
1387 }
1388
1389 resultPtr = Tcl_ObjSetVar2(interp, objv[arg], NULL, valuePtr,
1390 TCL_LEAVE_ERR_MSG);
1391 arg++;
1392 if (resultPtr == NULL) {
1393 DeleteScanNumberCache(numberCachePtr);
1394 return TCL_ERROR;
1395 }
1396 offset += (count + 7) / 8;
1397 break;
1398 }
1399 case 'h':
1400 case 'H': {
1401 char *dest;
1402 unsigned char *src;
1403 static const char hexdigit[] = "0123456789abcdef";
1404
1405 if (arg >= objc) {
1406 DeleteScanNumberCache(numberCachePtr);
1407 goto badIndex;
1408 }
1409 if (count == BINARY_ALL) {
1410 count = (length - offset)*2;
1411 } else {
1412 if (count == BINARY_NOCOUNT) {
1413 count = 1;
1414 }
1415 if (count > (length - offset)*2) {
1416 goto done;
1417 }
1418 }
1419 src = buffer + offset;
1420 TclNewObj(valuePtr);
1421 Tcl_SetObjLength(valuePtr, count);
1422 dest = TclGetString(valuePtr);
1423
1424 if (cmd == 'h') {
1425 for (i = 0; i < count; i++) {
1426 if (i % 2) {
1427 value >>= 4;
1428 } else {
1429 value = *src++;
1430 }
1431 *dest++ = hexdigit[value & 0xF];
1432 }
1433 } else {
1434 for (i = 0; i < count; i++) {
1435 if (i % 2) {
1436 value <<= 4;
1437 } else {
1438 value = *src++;
1439 }
1440 *dest++ = hexdigit[(value >> 4) & 0xF];
1441 }
1442 }
1443
1444 resultPtr = Tcl_ObjSetVar2(interp, objv[arg], NULL, valuePtr,
1445 TCL_LEAVE_ERR_MSG);
1446 arg++;
1447 if (resultPtr == NULL) {
1448 DeleteScanNumberCache(numberCachePtr);
1449 return TCL_ERROR;
1450 }
1451 offset += (count + 1) / 2;
1452 break;
1453 }
1454 case 'c':
1455 size = 1;
1456 goto scanNumber;
1457 case 't':
1458 case 's':
1459 case 'S':
1460 size = 2;
1461 goto scanNumber;
1462 case 'n':
1463 case 'i':
1464 case 'I':
1465 size = 4;
1466 goto scanNumber;
1467 case 'm':
1468 case 'w':
1469 case 'W':
1470 size = 8;
1471 goto scanNumber;
1472 case 'r':
1473 case 'R':
1474 case 'f':
1475 size = sizeof(float);
1476 goto scanNumber;
1477 case 'q':
1478 case 'Q':
1479 case 'd': {
1480 unsigned char *src;
1481
1482 size = sizeof(double);
1483 /* fall through */
1484
1485 scanNumber:
1486 if (arg >= objc) {
1487 DeleteScanNumberCache(numberCachePtr);
1488 goto badIndex;
1489 }
1490 if (count == BINARY_NOCOUNT) {
1491 if (length < (size + offset)) {
1492 goto done;
1493 }
1494 valuePtr = ScanNumber(buffer+offset, cmd, flags,
1495 &numberCachePtr);
1496 offset += size;
1497 } else {
1498 if (count == BINARY_ALL) {
1499 count = (length - offset) / size;
1500 }
1501 if ((length - offset) < (count * size)) {
1502 goto done;
1503 }
1504 TclNewObj(valuePtr);
1505 src = buffer + offset;
1506 for (i = 0; i < count; i++) {
1507 elementPtr = ScanNumber(src, cmd, flags, &numberCachePtr);
1508 src += size;
1509 Tcl_ListObjAppendElement(NULL, valuePtr, elementPtr);
1510 }
1511 offset += count * size;
1512 }
1513
1514 resultPtr = Tcl_ObjSetVar2(interp, objv[arg], NULL, valuePtr,
1515 TCL_LEAVE_ERR_MSG);
1516 arg++;
1517 if (resultPtr == NULL) {
1518 DeleteScanNumberCache(numberCachePtr);
1519 return TCL_ERROR;
1520 }
1521 break;
1522 }
1523 case 'x':
1524 if (count == BINARY_NOCOUNT) {
1525 count = 1;
1526 }
1527 if ((count == BINARY_ALL) || (count > (length - offset))) {
1528 offset = length;
1529 } else {
1530 offset += count;
1531 }
1532 break;
1533 case 'X':
1534 if (count == BINARY_NOCOUNT) {
1535 count = 1;
1536 }
1537 if ((count == BINARY_ALL) || (count > offset)) {
1538 offset = 0;
1539 } else {
1540 offset -= count;
1541 }
1542 break;
1543 case '@':
1544 if (count == BINARY_NOCOUNT) {
1545 DeleteScanNumberCache(numberCachePtr);
1546 goto badCount;
1547 }
1548 if ((count == BINARY_ALL) || (count > length)) {
1549 offset = length;
1550 } else {
1551 offset = count;
1552 }
1553 break;
1554 default:
1555 DeleteScanNumberCache(numberCachePtr);
1556 errorString = str;
1557 goto badField;
1558 }
1559 }
1560
1561 /*
1562 * Set the result to the last position of the cursor.
1563 */
1564
1565 done:
1566 Tcl_SetObjResult(interp, Tcl_NewLongObj(arg - 3));
1567 DeleteScanNumberCache(numberCachePtr);
1568
1569 return TCL_OK;
1570
1571 badCount:
1572 errorString = "missing count for \"@\" field specifier";
1573 goto error;
1574
1575 badIndex:
1576 errorString = "not enough arguments for all format specifiers";
1577 goto error;
1578
1579 badField:
1580 {
1581 int ch;
1582 char buf[8] = "";
1583
1584 TclUtfToUCS4(errorString, &ch);
1585 buf[TclUCS4ToUtf(ch, buf)] = '\0';
1586 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
1587 "bad field specifier \"%s\"", buf));
1588 return TCL_ERROR;
1589 }
1590
1591 error:
1592 Tcl_SetObjResult(interp, Tcl_NewStringObj(errorString, -1));
1593 return TCL_ERROR;
1594 }
1595
1596 /*
1597 *----------------------------------------------------------------------
1598 *
1599 * GetFormatSpec --
1600 *
1601 * This function parses the format strings used in the binary format and
1602 * scan commands.
1603 *
1604 * Results:
1605 * Moves the formatPtr to the start of the next command. Returns the
1606 * current command character and count in cmdPtr and countPtr. The count
1607 * is set to BINARY_ALL if the count character was '*' or BINARY_NOCOUNT
1608 * if no count was specified. Returns 1 on success, or 0 if the string
1609 * did not have a format specifier.
1610 *
1611 * Side effects:
1612 * None.
1613 *
1614 *----------------------------------------------------------------------
1615 */
1616
1617 static int
1618 GetFormatSpec(
1619 const char **formatPtr, /* Pointer to format string. */
1620 char *cmdPtr, /* Pointer to location of command char. */
1621 int *countPtr, /* Pointer to repeat count value. */
1622 int *flagsPtr) /* Pointer to field flags */
1623 {
1624 /*
1625 * Skip any leading blanks.
1626 */
1627
1628 while (**formatPtr == ' ') {
1629 (*formatPtr)++;
1630 }
1631
1632 /*
1633 * The string was empty, except for whitespace, so fail.
1634 */
1635
1636 if (!(**formatPtr)) {
1637 return 0;
1638 }
1639
1640 /*
1641 * Extract the command character and any trailing digits or '*'.
1642 */
1643
1644 *cmdPtr = **formatPtr;
1645 (*formatPtr)++;
1646 if (**formatPtr == 'u') {
1647 (*formatPtr)++;
1648 *flagsPtr |= BINARY_UNSIGNED;
1649 }
1650 if (**formatPtr == '*') {
1651 (*formatPtr)++;
1652 *countPtr = BINARY_ALL;
1653 } else if (isdigit(UCHAR(**formatPtr))) { /* INTL: digit */
1654 unsigned long count;
1655
1656 errno = 0;
1657 count = strtoul(*formatPtr, (char **) formatPtr, 10);
1658 if (errno || (count > (unsigned long) INT_MAX)) {
1659 *countPtr = INT_MAX;
1660 } else {
1661 *countPtr = (int) count;
1662 }
1663 } else {
1664 *countPtr = BINARY_NOCOUNT;
1665 }
1666 return 1;
1667 }
1668
1669 /*
1670 *----------------------------------------------------------------------
1671 *
1672 * NeedReversing --
1673 *
1674 * This routine determines, if bytes of a number need to be re-ordered,
1675 * and returns a numeric code indicating the re-ordering to be done.
1676 * This depends on the endianness of the machine and the desired format.
1677 * It is in effect a table (whose contents depend on the endianness of
1678 * the system) describing whether a value needs reversing or not. Anyone
1679 * porting the code to a big-endian platform should take care to make
1680 * sure that they define WORDS_BIGENDIAN though this is already done by
1681 * configure for the Unix build; little-endian platforms (including
1682 * Windows) don't need to do anything.
1683 *
1684 * Results:
1685 * 0 No re-ordering needed.
1686 * 1 Reverse the bytes: 01234567 <-> 76543210 (little to big)
1687 * 2 Apply this re-ordering: 01234567 <-> 45670123 (Nokia to little)
1688 * 3 Apply this re-ordering: 01234567 <-> 32107654 (Nokia to big)
1689 *
1690 * Side effects:
1691 * None
1692 *
1693 *----------------------------------------------------------------------
1694 */
1695
1696 static int
1697 NeedReversing(
1698 int format)
1699 {
1700 switch (format) {
1701 /* native floats and doubles: never reverse */
1702 case 'd':
1703 case 'f':
1704 /* big endian ints: never reverse */
1705 case 'I':
1706 case 'S':
1707 case 'W':
1708 #ifdef WORDS_BIGENDIAN
1709 /* native ints: reverse if we're little-endian */
1710 case 'n':
1711 case 't':
1712 case 'm':
1713 /* f: reverse if we're little-endian */
1714 case 'Q':
1715 case 'R':
1716 #else /* !WORDS_BIGENDIAN */
1717 /* small endian floats: reverse if we're big-endian */
1718 case 'r':
1719 #endif /* WORDS_BIGENDIAN */
1720 return 0;
1721
1722 #ifdef WORDS_BIGENDIAN
1723 /* small endian floats: reverse if we're big-endian */
1724 case 'q':
1725 case 'r':
1726 #else /* !WORDS_BIGENDIAN */
1727 /* native ints: reverse if we're little-endian */
1728 case 'n':
1729 case 't':
1730 case 'm':
1731 /* f: reverse if we're little-endian */
1732 case 'R':
1733 #endif /* WORDS_BIGENDIAN */
1734 /* small endian ints: always reverse */
1735 case 'i':
1736 case 's':
1737 case 'w':
1738 return 1;
1739
1740 #ifndef WORDS_BIGENDIAN
1741 /*
1742 * The Q and q formats need special handling to account for the unusual
1743 * byte ordering of 8-byte floats on Nokia 770 systems, which claim to be
1744 * little-endian, but also reverse word order.
1745 */
1746
1747 case 'Q':
1748 if (TclNokia770Doubles()) {
1749 return 3;
1750 }
1751 return 1;
1752 case 'q':
1753 if (TclNokia770Doubles()) {
1754 return 2;
1755 }
1756 return 0;
1757 #endif
1758 }
1759
1760 Tcl_Panic("unexpected fallthrough");
1761 return 0;
1762 }
1763
1764 /*
1765 *----------------------------------------------------------------------
1766 *
1767 * CopyNumber --
1768 *
1769 * This routine is called by FormatNumber and ScanNumber to copy a
1770 * floating-point number. If required, bytes are reversed while copying.
1771 * The behaviour is only fully defined when used with IEEE float and
1772 * double values (guaranteed to be 4 and 8 bytes long, respectively.)
1773 *
1774 * Results:
1775 * None
1776 *
1777 * Side effects:
1778 * Copies length bytes
1779 *
1780 *----------------------------------------------------------------------
1781 */
1782
1783 static void
1784 CopyNumber(
1785 const void *from, /* source */
1786 void *to, /* destination */
1787 unsigned length, /* Number of bytes to copy */
1788 int type) /* What type of thing are we copying? */
1789 {
1790 switch (NeedReversing(type)) {
1791 case 0:
1792 memcpy(to, from, length);
1793 break;
1794 case 1: {
1795 const unsigned char *fromPtr = (const unsigned char *)from;
1796 unsigned char *toPtr = (unsigned char *)to;
1797
1798 switch (length) {
1799 case 4:
1800 toPtr[0] = fromPtr[3];
1801 toPtr[1] = fromPtr[2];
1802 toPtr[2] = fromPtr[1];
1803 toPtr[3] = fromPtr[0];
1804 break;
1805 case 8:
1806 toPtr[0] = fromPtr[7];
1807 toPtr[1] = fromPtr[6];
1808 toPtr[2] = fromPtr[5];
1809 toPtr[3] = fromPtr[4];
1810 toPtr[4] = fromPtr[3];
1811 toPtr[5] = fromPtr[2];
1812 toPtr[6] = fromPtr[1];
1813 toPtr[7] = fromPtr[0];
1814 break;
1815 }
1816 break;
1817 }
1818 case 2: {
1819 const unsigned char *fromPtr = (const unsigned char *)from;
1820 unsigned char *toPtr = (unsigned char *)to;
1821
1822 toPtr[0] = fromPtr[4];
1823 toPtr[1] = fromPtr[5];
1824 toPtr[2] = fromPtr[6];
1825 toPtr[3] = fromPtr[7];
1826 toPtr[4] = fromPtr[0];
1827 toPtr[5] = fromPtr[1];
1828 toPtr[6] = fromPtr[2];
1829 toPtr[7] = fromPtr[3];
1830 break;
1831 }
1832 case 3: {
1833 const unsigned char *fromPtr = (const unsigned char *)from;
1834 unsigned char *toPtr = (unsigned char *)to;
1835
1836 toPtr[0] = fromPtr[3];
1837 toPtr[1] = fromPtr[2];
1838 toPtr[2] = fromPtr[1];
1839 toPtr[3] = fromPtr[0];
1840 toPtr[4] = fromPtr[7];
1841 toPtr[5] = fromPtr[6];
1842 toPtr[6] = fromPtr[5];
1843 toPtr[7] = fromPtr[4];
1844 break;
1845 }
1846 }
1847 }
1848
1849 /*
1850 *----------------------------------------------------------------------
1851 *
1852 * FormatNumber --
1853 *
1854 * This routine is called by Tcl_BinaryObjCmd to format a number into a
1855 * location pointed at by cursor.
1856 *
1857 * Results:
1858 * A standard Tcl result.
1859 *
1860 * Side effects:
1861 * Moves the cursor to the next location to be written into.
1862 *
1863 *----------------------------------------------------------------------
1864 */
1865
1866 static int
1867 FormatNumber(
1868 Tcl_Interp *interp, /* Current interpreter, used to report
1869 * errors. */
1870 int type, /* Type of number to format. */
1871 Tcl_Obj *src, /* Number to format. */
1872 unsigned char **cursorPtr) /* Pointer to index into destination buffer. */
1873 {
1874 long value;
1875 double dvalue;
1876 Tcl_WideInt wvalue;
1877 float fvalue;
1878
1879 switch (type) {
1880 case 'd':
1881 case 'q':
1882 case 'Q':
1883 /*
1884 * Double-precision floating point values. Tcl_GetDoubleFromObj
1885 * returns TCL_ERROR for NaN, but we can check by comparing the
1886 * object's type pointer.
1887 */
1888
1889 if (Tcl_GetDoubleFromObj(interp, src, &dvalue) != TCL_OK) {
1890 if (src->typePtr != &tclDoubleType) {
1891 return TCL_ERROR;
1892 }
1893 dvalue = src->internalRep.doubleValue;
1894 }
1895 CopyNumber(&dvalue, *cursorPtr, sizeof(double), type);
1896 *cursorPtr += sizeof(double);
1897 return TCL_OK;
1898
1899 case 'f':
1900 case 'r':
1901 case 'R':
1902 /*
1903 * Single-precision floating point values. Tcl_GetDoubleFromObj
1904 * returns TCL_ERROR for NaN, but we can check by comparing the
1905 * object's type pointer.
1906 */
1907
1908 if (Tcl_GetDoubleFromObj(interp, src, &dvalue) != TCL_OK) {
1909 if (src->typePtr != &tclDoubleType) {
1910 return TCL_ERROR;
1911 }
1912 dvalue = src->internalRep.doubleValue;
1913 }
1914
1915 /*
1916 * Because some compilers will generate floating point exceptions on
1917 * an overflow cast (e.g. Borland), we restrict the values to the
1918 * valid range for float.
1919 */
1920
1921 if (fabs(dvalue) > (double) FLT_MAX) {
1922 fvalue = (dvalue >= 0.0) ? FLT_MAX : -FLT_MAX;
1923 } else {
1924 fvalue = (float) dvalue;
1925 }
1926 CopyNumber(&fvalue, *cursorPtr, sizeof(float), type);
1927 *cursorPtr += sizeof(float);
1928 return TCL_OK;
1929
1930 /*
1931 * 64-bit integer values.
1932 */
1933 case 'w':
1934 case 'W':
1935 case 'm':
1936 if (Tcl_GetWideIntFromObj(interp, src, &wvalue) != TCL_OK) {
1937 return TCL_ERROR;
1938 }
1939 if (NeedReversing(type)) {
1940 *(*cursorPtr)++ = UCHAR(wvalue);
1941 *(*cursorPtr)++ = UCHAR(wvalue >> 8);
1942 *(*cursorPtr)++ = UCHAR(wvalue >> 16);
1943 *(*cursorPtr)++ = UCHAR(wvalue >> 24);
1944 *(*cursorPtr)++ = UCHAR(wvalue >> 32);
1945 *(*cursorPtr)++ = UCHAR(wvalue >> 40);
1946 *(*cursorPtr)++ = UCHAR(wvalue >> 48);
1947 *(*cursorPtr)++ = UCHAR(wvalue >> 56);
1948 } else {
1949 *(*cursorPtr)++ = UCHAR(wvalue >> 56);
1950 *(*cursorPtr)++ = UCHAR(wvalue >> 48);
1951 *(*cursorPtr)++ = UCHAR(wvalue >> 40);
1952 *(*cursorPtr)++ = UCHAR(wvalue >> 32);
1953 *(*cursorPtr)++ = UCHAR(wvalue >> 24);
1954 *(*cursorPtr)++ = UCHAR(wvalue >> 16);
1955 *(*cursorPtr)++ = UCHAR(wvalue >> 8);
1956 *(*cursorPtr)++ = UCHAR(wvalue);
1957 }
1958 return TCL_OK;
1959
1960 /*
1961 * 32-bit integer values.
1962 */
1963 case 'i':
1964 case 'I':
1965 case 'n':
1966 if (TclGetLongFromObj(interp, src, &value) != TCL_OK) {
1967 return TCL_ERROR;
1968 }
1969 if (NeedReversing(type)) {
1970 *(*cursorPtr)++ = UCHAR(value);
1971 *(*cursorPtr)++ = UCHAR(value >> 8);
1972 *(*cursorPtr)++ = UCHAR(value >> 16);
1973 *(*cursorPtr)++ = UCHAR(value >> 24);
1974 } else {
1975 *(*cursorPtr)++ = UCHAR(value >> 24);
1976 *(*cursorPtr)++ = UCHAR(value >> 16);
1977 *(*cursorPtr)++ = UCHAR(value >> 8);
1978 *(*cursorPtr)++ = UCHAR(value);
1979 }
1980 return TCL_OK;
1981
1982 /*
1983 * 16-bit integer values.
1984 */
1985 case 's':
1986 case 'S':
1987 case 't':
1988 if (TclGetLongFromObj(interp, src, &value) != TCL_OK) {
1989 return TCL_ERROR;
1990 }
1991 if (NeedReversing(type)) {
1992 *(*cursorPtr)++ = UCHAR(value);
1993 *(*cursorPtr)++ = UCHAR(value >> 8);
1994 } else {
1995 *(*cursorPtr)++ = UCHAR(value >> 8);
1996 *(*cursorPtr)++ = UCHAR(value);
1997 }
1998 return TCL_OK;
1999
2000 /*
2001 * 8-bit integer values.
2002 */
2003 case 'c':
2004 if (TclGetLongFromObj(interp, src, &value) != TCL_OK) {
2005 return TCL_ERROR;
2006 }
2007 *(*cursorPtr)++ = UCHAR(value);
2008 return TCL_OK;
2009
2010 default:
2011 Tcl_Panic("unexpected fallthrough");
2012 return TCL_ERROR;
2013 }
2014 }
2015
2016 /*
2017 *----------------------------------------------------------------------
2018 *
2019 * ScanNumber --
2020 *
2021 * This routine is called by Tcl_BinaryObjCmd to scan a number out of a
2022 * buffer.
2023 *
2024 * Results:
2025 * Returns a newly created object containing the scanned number. This
2026 * object has a ref count of zero.
2027 *
2028 * Side effects:
2029 * Might reuse an object in the number cache, place a new object in the
2030 * cache, or delete the cache and set the reference to it (itself passed
2031 * in by reference) to NULL.
2032 *
2033 *----------------------------------------------------------------------
2034 */
2035
2036 static Tcl_Obj *
2037 ScanNumber(
2038 unsigned char *buffer, /* Buffer to scan number from. */
2039 int type, /* Format character from "binary scan" */
2040 int flags, /* Format field flags */
2041 Tcl_HashTable **numberCachePtrPtr)
2042 /* Place to look for cache of scanned value
2043 * objects, or NULL if too many different
2044 * numbers have been scanned. */
2045 {
2046 long value;
2047 float fvalue;
2048 double dvalue;
2049 Tcl_WideUInt uwvalue;
2050
2051 /*
2052 * We cannot rely on the compiler to properly sign extend integer values
2053 * when we cast from smaller values to larger values because we don't know
2054 * the exact size of the integer types. So, we have to handle sign
2055 * extension explicitly by checking the high bit and padding with 1's as
2056 * needed. This practice is disabled if the BINARY_UNSIGNED flag is set.
2057 */
2058
2059 switch (type) {
2060 case 'c':
2061 /*
2062 * Characters need special handling. We want to produce a signed
2063 * result, but on some platforms (such as AIX) chars are unsigned. To
2064 * deal with this, check for a value that should be negative but
2065 * isn't.
2066 */
2067
2068 value = buffer[0];
2069 if (!(flags & BINARY_UNSIGNED)) {
2070 if (value & 0x80) {
2071 value |= -0x100;
2072 }
2073 }
2074 goto returnNumericObject;
2075
2076 /*
2077 * 16-bit numeric values. We need the sign extension trick (see above)
2078 * here as well.
2079 */
2080
2081 case 's':
2082 case 'S':
2083 case 't':
2084 if (NeedReversing(type)) {
2085 value = (long) (buffer[0] + (buffer[1] << 8));
2086 } else {
2087 value = (long) (buffer[1] + (buffer[0] << 8));
2088 }
2089 if (!(flags & BINARY_UNSIGNED)) {
2090 if (value & 0x8000) {
2091 value |= -0x10000;
2092 }
2093 }
2094 goto returnNumericObject;
2095
2096 /*
2097 * 32-bit numeric values.
2098 */
2099
2100 case 'i':
2101 case 'I':
2102 case 'n':
2103 if (NeedReversing(type)) {
2104 value = (long) (buffer[0]
2105 + (buffer[1] << 8)
2106 + (buffer[2] << 16)
2107 + (((unsigned long)buffer[3]) << 24));
2108 } else {
2109 value = (long) (buffer[3]
2110 + (buffer[2] << 8)
2111 + (buffer[1] << 16)
2112 + (((unsigned long) buffer[0]) << 24));
2113 }
2114
2115 /*
2116 * Check to see if the value was sign extended properly on systems
2117 * where an int is more than 32-bits.
2118 *
2119 * We avoid caching unsigned integers as we cannot distinguish between
2120 * 32bit signed and unsigned in the hash (short and char are ok).
2121 */
2122
2123 if (flags & BINARY_UNSIGNED) {
2124 return Tcl_NewWideIntObj((Tcl_WideInt)(unsigned long)value);
2125 }
2126 if ((value & (((unsigned) 1) << 31)) && (value > 0)) {
2127 value -= (((unsigned) 1) << 31);
2128 value -= (((unsigned) 1) << 31);
2129 }
2130
2131 returnNumericObject:
2132 if (*numberCachePtrPtr == NULL) {
2133 return Tcl_NewLongObj(value);
2134 } else {
2135 Tcl_HashTable *tablePtr = *numberCachePtrPtr;
2136 Tcl_HashEntry *hPtr;
2137 int isNew;
2138
2139 hPtr = Tcl_CreateHashEntry(tablePtr, INT2PTR(value), &isNew);
2140 if (!isNew) {
2141 return (Tcl_Obj *)Tcl_GetHashValue(hPtr);
2142 }
2143 if (tablePtr->numEntries <= BINARY_SCAN_MAX_CACHE) {
2144 Tcl_Obj *objPtr = Tcl_NewLongObj(value);
2145
2146 Tcl_IncrRefCount(objPtr);
2147 Tcl_SetHashValue(hPtr, objPtr);
2148 return objPtr;
2149 }
2150
2151 /*
2152 * We've overflowed the cache! Someone's parsing a LOT of varied
2153 * binary data in a single call! Bail out by switching back to the
2154 * old behaviour for the rest of the scan.
2155 *
2156 * Note that anyone just using the 'c' conversion (for bytes)
2157 * cannot trigger this.
2158 */
2159
2160 DeleteScanNumberCache(tablePtr);
2161 *numberCachePtrPtr = NULL;
2162 return Tcl_NewLongObj(value);
2163 }
2164
2165 /*
2166 * Do not cache wide (64-bit) values; they are already too large to
2167 * use as keys.
2168 */
2169
2170 case 'w':
2171 case 'W':
2172 case 'm':
2173 if (NeedReversing(type)) {
2174 uwvalue = ((Tcl_WideUInt) buffer[0])
2175 | (((Tcl_WideUInt) buffer[1]) << 8)
2176 | (((Tcl_WideUInt) buffer[2]) << 16)
2177 | (((Tcl_WideUInt) buffer[3]) << 24)
2178 | (((Tcl_WideUInt) buffer[4]) << 32)
2179 | (((Tcl_WideUInt) buffer[5]) << 40)
2180 | (((Tcl_WideUInt) buffer[6]) << 48)
2181 | (((Tcl_WideUInt) buffer[7]) << 56);
2182 } else {
2183 uwvalue = ((Tcl_WideUInt) buffer[7])
2184 | (((Tcl_WideUInt) buffer[6]) << 8)
2185 | (((Tcl_WideUInt) buffer[5]) << 16)
2186 | (((Tcl_WideUInt) buffer[4]) << 24)
2187 | (((Tcl_WideUInt) buffer[3]) << 32)
2188 | (((Tcl_WideUInt) buffer[2]) << 40)
2189 | (((Tcl_WideUInt) buffer[1]) << 48)
2190 | (((Tcl_WideUInt) buffer[0]) << 56);
2191 }
2192 if (flags & BINARY_UNSIGNED) {
2193 Tcl_Obj *bigObj = NULL;
2194 mp_int big;
2195
2196 TclBNInitBignumFromWideUInt(&big, uwvalue);
2197 bigObj = Tcl_NewBignumObj(&big);
2198 return bigObj;
2199 }
2200 return Tcl_NewWideIntObj((Tcl_WideInt)uwvalue);
2201
2202 /*
2203 * Do not cache double values; they are already too large to use as
2204 * keys and the values stored are utterly incompatible with the
2205 * integer part of the cache.
2206 */
2207
2208 /*
2209 * 32-bit IEEE single-precision floating point.
2210 */
2211
2212 case 'f':
2213 case 'R':
2214 case 'r':
2215 CopyNumber(buffer, &fvalue, sizeof(float), type);
2216 return Tcl_NewDoubleObj(fvalue);
2217
2218 /*
2219 * 64-bit IEEE double-precision floating point.
2220 */
2221
2222 case 'd':
2223 case 'Q':
2224 case 'q':
2225 CopyNumber(buffer, &dvalue, sizeof(double), type);
2226 return Tcl_NewDoubleObj(dvalue);
2227 }
2228 return NULL;
2229 }
2230
2231 /*
2232 *----------------------------------------------------------------------
2233 *
2234 * DeleteScanNumberCache --
2235 *
2236 * Deletes the hash table acting as a scan number cache.
2237 *
2238 * Results:
2239 * None
2240 *
2241 * Side effects:
2242 * Decrements the reference counts of the objects in the cache.
2243 *
2244 *----------------------------------------------------------------------
2245 */
2246
2247 static void
2248 DeleteScanNumberCache(
2249 Tcl_HashTable *numberCachePtr)
2250 /* Pointer to the hash table, or NULL (when
2251 * the cache has already been deleted due to
2252 * overflow.) */
2253 {
2254 Tcl_HashEntry *hEntry;
2255 Tcl_HashSearch search;
2256
2257 if (numberCachePtr == NULL) {
2258 return;
2259 }
2260
2261 hEntry = Tcl_FirstHashEntry(numberCachePtr, &search);
2262 while (hEntry != NULL) {
2263 Tcl_Obj *value = (Tcl_Obj *)Tcl_GetHashValue(hEntry);
2264
2265 if (value != NULL) {
2266 Tcl_DecrRefCount(value);
2267 }
2268 hEntry = Tcl_NextHashEntry(&search);
2269 }
2270 Tcl_DeleteHashTable(numberCachePtr);
2271 }
2272
2273 /*
2274 * ----------------------------------------------------------------------
2275 *
2276 * NOTES --
2277 *
2278 * Some measurements show that it is faster to use a table to to perform
2279 * uuencode and base64 value encoding than to calculate the output (at
2280 * least on intel P4 arch).
2281 *
2282 * Conversely using a lookup table for the decoding is slower than just
2283 * calculating the values. We therefore use the fastest of each method.
2284 *
2285 * Presumably this has to do with the size of the tables. The base64
2286 * decode table is 255 bytes while the encode table is only 65 bytes. The
2287 * choice likely depends on CPU memory cache sizes.
2288 */
2289
2290 /*
2291 *----------------------------------------------------------------------
2292 *
2293 * BinaryEncodeHex --
2294 *
2295 * Implement the [binary encode hex] binary encoding. clientData must be
2296 * a table to convert values to hexadecimal digits.
2297 *
2298 * Results:
2299 * Interp result set to an encoded byte array object
2300 *
2301 * Side effects:
2302 * None
2303 *
2304 *----------------------------------------------------------------------
2305 */
2306
2307 static int
2308 BinaryEncodeHex(
2309 ClientData clientData,
2310 Tcl_Interp *interp,
2311 int objc,
2312 Tcl_Obj *const objv[])
2313 {
2314 Tcl_Obj *resultObj = NULL;
2315 unsigned char *data = NULL;
2316 unsigned char *cursor = NULL;
2317 int offset = 0, count = 0;
2318
2319 if (objc != 2) {
2320 Tcl_WrongNumArgs(interp, 1, objv, "data");
2321 return TCL_ERROR;
2322 }
2323
2324 TclNewObj(resultObj);
2325 data = Tcl_GetByteArrayFromObj(objv[1], &count);
2326 cursor = Tcl_SetByteArrayLength(resultObj, count * 2);
2327 for (offset = 0; offset < count; ++offset) {
2328 *cursor++ = HexDigits[(data[offset] >> 4) & 0x0F];
2329 *cursor++ = HexDigits[data[offset] & 0x0F];
2330 }
2331 Tcl_SetObjResult(interp, resultObj);
2332 return TCL_OK;
2333 }
2334
2335 /*
2336 *----------------------------------------------------------------------
2337 *
2338 * BinaryDecodeHex --
2339 *
2340 * Implement the [binary decode hex] binary encoding.
2341 *
2342 * Results:
2343 * Interp result set to an decoded byte array object
2344 *
2345 * Side effects:
2346 * None
2347 *
2348 *----------------------------------------------------------------------
2349 */
2350
2351 static int
2352 BinaryDecodeHex(
2353 ClientData clientData,
2354 Tcl_Interp *interp,
2355 int objc,
2356 Tcl_Obj *const objv[])
2357 {
2358 Tcl_Obj *resultObj = NULL;
2359 unsigned char *data, *datastart, *dataend;
2360 unsigned char *begin, *cursor, c;
2361 int i, index, value, pure, strict = 0;
2362 int size, cut = 0, count = 0;
2363 Tcl_UniChar ch = 0;
2364 enum {OPT_STRICT };
2365 static const char *const optStrings[] = { "-strict", NULL };
2366
2367 if (objc < 2 || objc > 3) {
2368 Tcl_WrongNumArgs(interp, 1, objv, "?options? data");
2369 return TCL_ERROR;
2370 }
2371 for (i = 1; i < objc - 1; ++i) {
2372 if (Tcl_GetIndexFromObj(interp, objv[i], optStrings, "option",
2373 TCL_EXACT, &index) != TCL_OK) {
2374 return TCL_ERROR;
2375 }
2376 switch (index) {
2377 case OPT_STRICT:
2378 strict = 1;
2379 break;
2380 }
2381 }
2382
2383 TclNewObj(resultObj);
2384 pure = TclIsPureByteArray(objv[objc - 1]);
2385 datastart = data = pure ? Tcl_GetByteArrayFromObj(objv[objc - 1], &count)
2386 : (unsigned char *) TclGetStringFromObj(objv[objc - 1], &count);
2387 dataend = data + count;
2388 size = (count + 1) / 2;
2389 begin = cursor = Tcl_SetByteArrayLength(resultObj, size);
2390 while (data < dataend) {
2391 value = 0;
2392 for (i = 0 ; i < 2 ; i++) {
2393 if (data >= dataend) {
2394 value <<= 4;
2395 break;
2396 }
2397
2398 c = *data++;
2399 if (!isxdigit((int) c)) {
2400 if (strict || !TclIsSpaceProc(c)) {
2401 goto badChar;
2402 }
2403 i--;
2404 continue;
2405 }
2406
2407 value <<= 4;
2408 c -= '0';
2409 if (c > 9) {
2410 c += ('0' - 'A') + 10;
2411 }
2412 if (c > 16) {
2413 c += ('A' - 'a');
2414 }
2415 value |= c & 0xF;
2416 }
2417 if (i < 2) {
2418 cut++;
2419 }
2420 *cursor++ = UCHAR(value);
2421 value = 0;
2422 }
2423 if (cut > size) {
2424 cut = size;
2425 }
2426 Tcl_SetByteArrayLength(resultObj, cursor - begin - cut);
2427 Tcl_SetObjResult(interp, resultObj);
2428 return TCL_OK;
2429
2430 badChar:
2431 if (pure) {
2432 ch = c;
2433 } else {
2434 TclUtfToUniChar((const char *)(data - 1), &ch);
2435 }
2436 TclDecrRefCount(resultObj);
2437 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2438 "invalid hexadecimal digit \"%c\" at position %d",
2439 ch, (int) (data - datastart - 1)));
2440 Tcl_SetErrorCode(interp, "TCL", "BINARY", "DECODE", "INVALID", (char *)NULL);
2441 return TCL_ERROR;
2442 }
2443
2444 /*
2445 *----------------------------------------------------------------------
2446 *
2447 * BinaryEncode64 --
2448 *
2449 * This procedure implements the "binary encode base64" Tcl command.
2450 *
2451 * Results:
2452 * The base64 encoded value prescribed by the input arguments.
2453 *
2454 *----------------------------------------------------------------------
2455 */
2456
2457 #define OUTPUT(c) \
2458 do { \
2459 *cursor++ = (c); \
2460 outindex++; \
2461 if (maxlen > 0 && cursor != limit) { \
2462 if (outindex == maxlen) { \
2463 memcpy(cursor, wrapchar, wrapcharlen); \
2464 cursor += wrapcharlen; \
2465 outindex = 0; \
2466 } \
2467 } \
2468 if (cursor > limit) { \
2469 Tcl_Panic("limit hit"); \
2470 } \
2471 } while (0)
2472
2473 static int
2474 BinaryEncode64(
2475 ClientData clientData,
2476 Tcl_Interp *interp,
2477 int objc,
2478 Tcl_Obj *const objv[])
2479 {
2480 Tcl_Obj *resultObj;
2481 unsigned char *data, *limit;
2482 int maxlen = 0;
2483 const char *wrapchar = "\n";
2484 int wrapcharlen = 1;
2485 int index, purewrap = 1;
2486 int i, offset, size, outindex = 0, count = 0;
2487 enum { OPT_MAXLEN, OPT_WRAPCHAR };
2488 static const char *const optStrings[] = { "-maxlen", "-wrapchar", NULL };
2489
2490 if (objc < 2 || objc % 2 != 0) {
2491 Tcl_WrongNumArgs(interp, 1, objv,
2492 "?-maxlen len? ?-wrapchar char? data");
2493 return TCL_ERROR;
2494 }
2495 for (i = 1; i < objc - 1; i += 2) {
2496 if (Tcl_GetIndexFromObj(interp, objv[i], optStrings, "option",
2497 TCL_EXACT, &index) != TCL_OK) {
2498 return TCL_ERROR;
2499 }
2500 switch (index) {
2501 case OPT_MAXLEN:
2502 if (Tcl_GetIntFromObj(interp, objv[i + 1], &maxlen) != TCL_OK) {
2503 return TCL_ERROR;
2504 }
2505 if (maxlen < 0) {
2506 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2507 "line length out of range", -1));
2508 Tcl_SetErrorCode(interp, "TCL", "BINARY", "ENCODE",
2509 "LINE_LENGTH", (char *)NULL);
2510 return TCL_ERROR;
2511 }
2512 break;
2513 case OPT_WRAPCHAR:
2514 purewrap = TclIsPureByteArray(objv[i + 1]);
2515 if (purewrap) {
2516 wrapchar = (const char *) Tcl_GetByteArrayFromObj(
2517 objv[i + 1], &wrapcharlen);
2518 } else {
2519 wrapchar = TclGetStringFromObj(objv[i + 1], &wrapcharlen);
2520 }
2521 break;
2522 }
2523 }
2524 if (wrapcharlen == 0) {
2525 maxlen = 0;
2526 }
2527
2528 TclNewObj(resultObj);
2529 data = Tcl_GetByteArrayFromObj(objv[objc - 1], &count);
2530 if (count > 0) {
2531 unsigned char *cursor = NULL;
2532
2533 size = (((count * 4) / 3) + 3) & ~3; /* ensure 4 byte chunks */
2534 if (maxlen > 0 && size > maxlen) {
2535 int adjusted = size + (wrapcharlen * (size / maxlen));
2536
2537 if (size % maxlen == 0) {
2538 adjusted -= wrapcharlen;
2539 }
2540 size = adjusted;
2541
2542 if (purewrap == 0) {
2543 /* Wrapchar is (possibly) non-byte, so build result as
2544 * general string, not bytearray */
2545 Tcl_SetObjLength(resultObj, size);
2546 cursor = (unsigned char *) TclGetString(resultObj);
2547 }
2548 }
2549 if (cursor == NULL) {
2550 cursor = Tcl_SetByteArrayLength(resultObj, size);
2551 }
2552 limit = cursor + size;
2553 for (offset = 0; offset < count; offset += 3) {
2554 unsigned char d[3] = {0, 0, 0};
2555
2556 for (i = 0; i < 3 && offset + i < count; ++i) {
2557 d[i] = data[offset + i];
2558 }
2559 OUTPUT(B64Digits[d[0] >> 2]);
2560 OUTPUT(B64Digits[((d[0] & 0x03) << 4) | (d[1] >> 4)]);
2561 if (offset + 1 < count) {
2562 OUTPUT(B64Digits[((d[1] & 0x0F) << 2) | (d[2] >> 6)]);
2563 } else {
2564 OUTPUT(B64Digits[64]);
2565 }
2566 if (offset+2 < count) {
2567 OUTPUT(B64Digits[d[2] & 0x3F]);
2568 } else {
2569 OUTPUT(B64Digits[64]);
2570 }
2571 }
2572 }
2573 Tcl_SetObjResult(interp, resultObj);
2574 return TCL_OK;
2575 }
2576 #undef OUTPUT
2577
2578 /*
2579 *----------------------------------------------------------------------
2580 *
2581 * BinaryEncodeUu --
2582 *
2583 * This implements the uuencode binary encoding. Input is broken into 6
2584 * bit chunks and a lookup table is used to turn these values into output
2585 * characters. This differs from the generic code above in that line
2586 * lengths are also encoded.
2587 *
2588 * Results:
2589 * Interp result set to an encoded byte array object
2590 *
2591 * Side effects:
2592 * None
2593 *
2594 *----------------------------------------------------------------------
2595 */
2596
2597 static int
2598 BinaryEncodeUu(
2599 ClientData clientData,
2600 Tcl_Interp *interp,
2601 int objc,
2602 Tcl_Obj *const objv[])
2603 {
2604 Tcl_Obj *resultObj;
2605 unsigned char *data, *start, *cursor;
2606 int i, bits, index;
2607 unsigned int n;
2608 int lineLength = 61;
2609 const unsigned char SingleNewline[] = { UCHAR('\n') };
2610 const unsigned char *wrapchar = SingleNewline;
2611 int j, rawLength, offset, count, wrapcharlen = sizeof(SingleNewline);
2612 enum { OPT_MAXLEN, OPT_WRAPCHAR };
2613 static const char *const optStrings[] = { "-maxlen", "-wrapchar", NULL };
2614
2615 if (objc < 2 || objc % 2 != 0) {
2616 Tcl_WrongNumArgs(interp, 1, objv,
2617 "?-maxlen len? ?-wrapchar char? data");
2618 return TCL_ERROR;
2619 }
2620 for (i = 1; i < objc - 1; i += 2) {
2621 if (Tcl_GetIndexFromObj(interp, objv[i], optStrings, "option",
2622 TCL_EXACT, &index) != TCL_OK) {
2623 return TCL_ERROR;
2624 }
2625 switch (index) {
2626 case OPT_MAXLEN:
2627 if (Tcl_GetIntFromObj(interp, objv[i + 1],
2628 &lineLength) != TCL_OK) {
2629 return TCL_ERROR;
2630 }
2631 if (lineLength < 5 || lineLength > 85) {
2632 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2633 "line length out of range", -1));
2634 Tcl_SetErrorCode(interp, "TCL", "BINARY", "ENCODE",
2635 "LINE_LENGTH", (char *)NULL);
2636 return TCL_ERROR;
2637 }
2638 lineLength = ((lineLength - 1) & -4) + 1; /* 5, 9, 13 ... */
2639 break;
2640 case OPT_WRAPCHAR:
2641 wrapchar = (const unsigned char *) TclGetStringFromObj(
2642 objv[i + 1], &wrapcharlen);
2643 {
2644 const unsigned char *p = wrapchar;
2645 int numBytes = wrapcharlen;
2646
2647 while (numBytes) {
2648 switch (*p) {
2649 case '\t':
2650 case '\v':
2651 case '\f':
2652 case '\r':
2653 p++; numBytes--;
2654 continue;
2655 case '\n':
2656 numBytes--;
2657 break;
2658 default:
2659 badwrap:
2660 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2661 "invalid wrapchar; will defeat decoding",
2662 -1));
2663 Tcl_SetErrorCode(interp, "TCL", "BINARY",
2664 "ENCODE", "WRAPCHAR", (char *)NULL);
2665 return TCL_ERROR;
2666 }
2667 }
2668 if (numBytes) {
2669 goto badwrap;
2670 }
2671 }
2672 break;
2673 }
2674 }
2675
2676 /*
2677 * Allocate the buffer. This is a little bit too long, but is "good
2678 * enough".
2679 */
2680
2681 TclNewObj(resultObj);
2682 offset = 0;
2683 data = Tcl_GetByteArrayFromObj(objv[objc - 1], &count);
2684 rawLength = (lineLength - 1) * 3 / 4;
2685 start = cursor = Tcl_SetByteArrayLength(resultObj,
2686 (lineLength + wrapcharlen) *
2687 ((count + (rawLength - 1)) / rawLength));
2688 n = bits = 0;
2689
2690 /*
2691 * Encode the data. Each output line first has the length of raw data
2692 * encoded by the output line described in it by one encoded byte, then
2693 * the encoded data follows (encoding each 6 bits as one character).
2694 * Encoded lines are always terminated by a newline.
2695 */
2696
2697 while (offset < count) {
2698 int lineLen = count - offset;
2699
2700 if (lineLen > rawLength) {
2701 lineLen = rawLength;
2702 }
2703 *cursor++ = UueDigits[lineLen];
2704 for (i = 0 ; i < lineLen ; i++) {
2705 n <<= 8;
2706 n |= data[offset++];
2707 for (bits += 8; bits > 6 ; bits -= 6) {
2708 *cursor++ = UueDigits[(n >> (bits - 6)) & 0x3F];
2709 }
2710 }
2711 if (bits > 0) {
2712 n <<= 8;
2713 *cursor++ = UueDigits[(n >> (bits + 2)) & 0x3F];
2714 bits = 0;
2715 }
2716 for (j = 0 ; j < wrapcharlen ; ++j) {
2717 *cursor++ = wrapchar[j];
2718 }
2719 }
2720
2721 /*
2722 * Fix the length of the output bytearray.
2723 */
2724
2725 Tcl_SetByteArrayLength(resultObj, cursor - start);
2726 Tcl_SetObjResult(interp, resultObj);
2727 return TCL_OK;
2728 }
2729
2730 /*
2731 *----------------------------------------------------------------------
2732 *
2733 * BinaryDecodeUu --
2734 *
2735 * Decode a uuencoded string.
2736 *
2737 * Results:
2738 * Interp result set to an byte array object
2739 *
2740 * Side effects:
2741 * None
2742 *
2743 *----------------------------------------------------------------------
2744 */
2745
2746 static int
2747 BinaryDecodeUu(
2748 ClientData clientData,
2749 Tcl_Interp *interp,
2750 int objc,
2751 Tcl_Obj *const objv[])
2752 {
2753 Tcl_Obj *resultObj = NULL;
2754 unsigned char *data, *datastart, *dataend;
2755 unsigned char *begin, *cursor;
2756 int i, index, pure, strict = 0, lineLen;
2757 int size, count = 0;
2758 unsigned char c;
2759 Tcl_UniChar ch = 0;
2760 enum { OPT_STRICT };
2761 static const char *const optStrings[] = { "-strict", NULL };
2762
2763 if (objc < 2 || objc > 3) {
2764 Tcl_WrongNumArgs(interp, 1, objv, "?options? data");
2765 return TCL_ERROR;
2766 }
2767 for (i = 1; i < objc - 1; ++i) {
2768 if (Tcl_GetIndexFromObj(interp, objv[i], optStrings, "option",
2769 TCL_EXACT, &index) != TCL_OK) {
2770 return TCL_ERROR;
2771 }
2772 switch (index) {
2773 case OPT_STRICT:
2774 strict = 1;
2775 break;
2776 }
2777 }
2778
2779 TclNewObj(resultObj);
2780 pure = TclIsPureByteArray(objv[objc - 1]);
2781 datastart = data = pure ? Tcl_GetByteArrayFromObj(objv[objc - 1], &count)
2782 : (unsigned char *) TclGetStringFromObj(objv[objc - 1], &count);
2783 dataend = data + count;
2784 size = ((count + 3) & ~3) * 3 / 4;
2785 begin = cursor = Tcl_SetByteArrayLength(resultObj, size);
2786 lineLen = -1;
2787
2788 /*
2789 * The decoding loop. First, we get the length of line (strictly, the
2790 * number of data bytes we expect to generate from the line) we're
2791 * processing this time round if it is not already known (i.e., when the
2792 * lineLen variable is set to the magic value, -1).
2793 */
2794
2795 while (data < dataend) {
2796 char d[4] = {0, 0, 0, 0};
2797
2798 if (lineLen < 0) {
2799 c = *data++;
2800 if (c < 32 || c > 96) {
2801 if (strict || !TclIsSpaceProc(c)) {
2802 goto badUu;
2803 }
2804 i--;
2805 continue;
2806 }
2807 lineLen = (c - 32) & 0x3F;
2808 }
2809
2810 /*
2811 * Now we read a four-character grouping.
2812 */
2813
2814 for (i = 0 ; i < 4 ; i++) {
2815 if (data < dataend) {
2816 d[i] = c = *data++;
2817 if (c < 32 || c > 96) {
2818 if (strict) {
2819 if (!TclIsSpaceProc(c)) {
2820 goto badUu;
2821 } else if (c == '\n') {
2822 goto shortUu;
2823 }
2824 }
2825 i--;
2826 continue;
2827 }
2828 }
2829 }
2830
2831 /*
2832 * Translate that grouping into (up to) three binary bytes output.
2833 */
2834
2835 if (lineLen > 0) {
2836 *cursor++ = (((d[0] - 0x20) & 0x3F) << 2)
2837 | (((d[1] - 0x20) & 0x3F) >> 4);
2838 if (--lineLen > 0) {
2839 *cursor++ = (((d[1] - 0x20) & 0x3F) << 4)
2840 | (((d[2] - 0x20) & 0x3F) >> 2);
2841 if (--lineLen > 0) {
2842 *cursor++ = (((d[2] - 0x20) & 0x3F) << 6)
2843 | (((d[3] - 0x20) & 0x3F));
2844 lineLen--;
2845 }
2846 }
2847 }
2848
2849 /*
2850 * If we've reached the end of the line, skip until we process a
2851 * newline.
2852 */
2853
2854 if (lineLen == 0 && data < dataend) {
2855 lineLen = -1;
2856 do {
2857 c = *data++;
2858 if (c == '\n') {
2859 break;
2860 } else if (c >= 32 && c <= 96) {
2861 data--;
2862 break;
2863 } else if (strict || !TclIsSpaceProc(c)) {
2864 goto badUu;
2865 }
2866 } while (data < dataend);
2867 }
2868 }
2869
2870 /*
2871 * Sanity check, clean up and finish.
2872 */
2873
2874 if (lineLen > 0 && strict) {
2875 goto shortUu;
2876 }
2877 Tcl_SetByteArrayLength(resultObj, cursor - begin);
2878 Tcl_SetObjResult(interp, resultObj);
2879 return TCL_OK;
2880
2881 shortUu:
2882 Tcl_SetObjResult(interp, Tcl_ObjPrintf("short uuencode data"));
2883 Tcl_SetErrorCode(interp, "TCL", "BINARY", "DECODE", "SHORT", (char *)NULL);
2884 TclDecrRefCount(resultObj);
2885 return TCL_ERROR;
2886
2887 badUu:
2888 if (pure) {
2889 ch = c;
2890 } else {
2891 TclUtfToUniChar((const char *)(data - 1), &ch);
2892 }
2893 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2894 "invalid uuencode character \"%c\" at position %d",
2895 ch, (int) (data - datastart - 1)));
2896 Tcl_SetErrorCode(interp, "TCL", "BINARY", "DECODE", "INVALID", (char *)NULL);
2897 TclDecrRefCount(resultObj);
2898 return TCL_ERROR;
2899 }
2900
2901 /*
2902 *----------------------------------------------------------------------
2903 *
2904 * BinaryDecode64 --
2905 *
2906 * Decode a base64 encoded string.
2907 *
2908 * Results:
2909 * Interp result set to an byte array object
2910 *
2911 * Side effects:
2912 * None
2913 *
2914 *----------------------------------------------------------------------
2915 */
2916
2917 static int
2918 BinaryDecode64(
2919 ClientData clientData,
2920 Tcl_Interp *interp,
2921 int objc,
2922 Tcl_Obj *const objv[])
2923 {
2924 Tcl_Obj *resultObj = NULL;
2925 unsigned char *data, *datastart, *dataend, c = '\0';
2926 unsigned char *begin = NULL;
2927 unsigned char *cursor = NULL;
2928 int pure, strict = 0;
2929 int i, index, cut = 0;
2930 int size, count = 0;
2931 Tcl_UniChar ch = 0;
2932 enum { OPT_STRICT };
2933 static const char *const optStrings[] = { "-strict", NULL };
2934
2935 if (objc < 2 || objc > 3) {
2936 Tcl_WrongNumArgs(interp, 1, objv, "?options? data");
2937 return TCL_ERROR;
2938 }
2939 for (i = 1; i < objc - 1; ++i) {
2940 if (Tcl_GetIndexFromObj(interp, objv[i], optStrings, "option",
2941 TCL_EXACT, &index) != TCL_OK) {
2942 return TCL_ERROR;
2943 }
2944 switch (index) {
2945 case OPT_STRICT:
2946 strict = 1;
2947 break;
2948 }
2949 }
2950
2951 TclNewObj(resultObj);
2952 pure = TclIsPureByteArray(objv[objc - 1]);
2953 datastart = data = pure ? Tcl_GetByteArrayFromObj(objv[objc - 1], &count)
2954 : (unsigned char *) TclGetStringFromObj(objv[objc - 1], &count);
2955 dataend = data + count;
2956 size = ((count + 3) & ~3) * 3 / 4;
2957 begin = cursor = Tcl_SetByteArrayLength(resultObj, size);
2958 while (data < dataend) {
2959 unsigned long value = 0;
2960
2961 /*
2962 * Decode the current block. Each base64 block consists of four input
2963 * characters A-Z, a-z, 0-9, +, or /. Each character supplies six bits
2964 * of output data, so each block's output is 24 bits (three bytes) in
2965 * length. The final block can be shorter by one or two bytes, denoted
2966 * by the input ending with one or two ='s, respectively.
2967 */
2968
2969 for (i = 0; i < 4; i++) {
2970 /*
2971 * Get the next input character. At end of input, pad with at most
2972 * two ='s. If more than two ='s would be needed, instead discard
2973 * the block read thus far.
2974 */
2975
2976 if (data < dataend) {
2977 c = *data++;
2978 } else if (i > 1) {
2979 c = '=';
2980 } else {
2981 if (strict && i <= 1) {
2982 /*
2983 * Single resp. unfulfilled char (each 4th next single
2984 * char) is rather bad64 error case in strict mode.
2985 */
2986
2987 goto bad64;
2988 }
2989 cut += 3;
2990 break;
2991 }
2992
2993 /*
2994 * Load the character into the block value. Handle ='s specially
2995 * because they're only valid as the last character or two of the
2996 * final block of input. Unless strict mode is enabled, skip any
2997 * input whitespace characters.
2998 */
2999
3000 if (cut) {
3001 if (c == '=' && i > 1) {
3002 value <<= 6;
3003 cut++;
3004 } else if (!strict) {
3005 i--;
3006 } else {
3007 goto bad64;
3008 }
3009 } else if (c >= 'A' && c <= 'Z') {
3010 value = (value << 6) | ((c - 'A') & 0x3F);
3011 } else if (c >= 'a' && c <= 'z') {
3012 value = (value << 6) | ((c - 'a' + 26) & 0x3F);
3013 } else if (c >= '0' && c <= '9') {
3014 value = (value << 6) | ((c - '0' + 52) & 0x3F);
3015 } else if (c == '+') {
3016 value = (value << 6) | 0x3E;
3017 } else if (c == '/') {
3018 value = (value << 6) | 0x3F;
3019 } else if (c == '=' && (!strict || i > 1)) {
3020 /*
3021 * "=" and "a=" is rather bad64 error case in strict mode.
3022 */
3023
3024 value <<= 6;
3025 if (i) {
3026 cut++;
3027 }
3028 } else if (strict) {
3029 goto bad64;
3030 } else {
3031 i--;
3032 }
3033 }
3034 *cursor++ = UCHAR((value >> 16) & 0xFF);
3035 *cursor++ = UCHAR((value >> 8) & 0xFF);
3036 *cursor++ = UCHAR(value & 0xFF);
3037
3038 /*
3039 * Since = is only valid within the final block, if it was encountered
3040 * but there are still more input characters, confirm that strict mode
3041 * is off and all subsequent characters are whitespace.
3042 */
3043
3044 if (cut && data < dataend) {
3045 if (strict) {
3046 goto bad64;
3047 }
3048 }
3049 }
3050 Tcl_SetByteArrayLength(resultObj, cursor - begin - cut);
3051 Tcl_SetObjResult(interp, resultObj);
3052 return TCL_OK;
3053
3054 bad64:
3055 if (pure) {
3056 ch = c;
3057 } else {
3058 /* The decoder is byte-oriented. If we saw a byte that's not a
3059 * valid member of the base64 alphabet, it could be the lead byte
3060 * of a multi-byte character. */
3061
3062 /* Safe because we know data is NUL-terminated */
3063 TclUtfToUniChar((const char *)(data - 1), &ch);
3064 }
3065
3066 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3067 "invalid base64 character \"%c\" at position %d", ch,
3068 (int) (data - datastart - 1)));
3069 Tcl_SetErrorCode(interp, "TCL", "BINARY", "DECODE", "INVALID", (char *)NULL);
3070 TclDecrRefCount(resultObj);
3071 return TCL_ERROR;
3072 }
3073
3074 /*
3075 * Local Variables:
3076 * mode: c
3077 * c-basic-offset: 4
3078 * fill-column: 78
3079 * End:
3080 */