Debian Codegraph @

terps/tads/tads3/vmpack.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header$";
4 #endif
5
6 /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */
7 /*
8 Name
9 vmpack.cpp - binary data stream pack/unpack
10 Function
11
12 Notes
13
14 Modified
15 10/01/10 MJRoberts - Creation
16 */
17
18 #include <float.h>
19 #include <math.h>
20 #include <limits.h>
21
22 #include "t3std.h"
23 #include "vmtype.h"
24 #include "vmpack.h"
25 #include "vmdatasrc.h"
26 #include "vmstack.h"
27 #include "vmrun.h"
28 #include "vmstr.h"
29 #include "vmlst.h"
30 #include "vmbignum.h"
31 #include "vmbytarr.h"
32 #include "utf8.h"
33 #include "charmap.h"
34
35
36 /* ------------------------------------------------------------------------ */
37 /*
38 * Type code classifiers
39 */
40
41 /*
42 * Is the type code valid?
43 */
44 static inline int is_valid_type(wchar_t c)
45 {
46 return c <= 127 && strchr("aAbuUwWhHcCsSlLqQkfdxX@\"{", (char)c) != 0;
47 }
48
49
50 /*
51 * Is the type repeatable? A repeatable type is a fixed-length type like L
52 * or C. String types are not repeatable; they instead treat a count as a
53 * length for the string.
54 */
55 static inline int is_repeatable(wchar_t c)
56 {
57 /* it's repeatable if it's not one of the string types */
58 return strchr("aAbuUwWhHxX@", (char)c) == 0;
59 }
60
61 /*
62 * Is this a varying-length item?
63 */
64 static inline int is_varying_length(wchar_t c)
65 {
66 return strchr("aAbuUwWhH", (char)c) != 0;
67 }
68
69 /*
70 * Get the character padding for a type. A, U, and W use space padding;
71 * everything else uses Nul padding.
72 */
73 static inline char get_padding_char(wchar_t c)
74 {
75 return strchr("AUW", (char)c) != 0 ? ' ' : 0;
76 }
77
78 /*
79 * Is this a type that consumes an argument?
80 */
81 static inline int type_consumes_arg(wchar_t c)
82 {
83 return strchr("xX@\"{", (char)c) == 0;
84 }
85
86
87
88 /* ------------------------------------------------------------------------ */
89 /*
90 * string parser position
91 */
92 struct CVmPackPos
93 {
94 CVmPackPos(const char *p, size_t len)
95 : p((char *)p), len(len), idx(1)
96 { }
97
98 CVmPackPos(const CVmPackPos *pos)
99 : p(pos->p.getptr()), len(pos->len), idx(pos->idx)
100 { }
101
102 CVmPackPos()
103 : p(), len(0), idx(0)
104 { }
105
106 /* set to another position */
107 void set(const CVmPackPos *pos)
108 {
109 p.set(&pos->p);
110 len = pos->len;
111 idx = pos->idx;
112 }
113
114 /* is another character available? */
115 int more()
116 {
117 /* get the current character (skipping spaces) */
118 getch();
119
120 /* indicate whether or not we have more in the buffer */
121 return len != 0;
122 }
123
124 /* get the current charater, without skipping spaces */
125 wchar_t getch_raw()
126 {
127 /* if there's a character left, return it */
128 return len != 0 ? p.getch() : 0;
129 }
130
131 /* get the current character, skipping spaces */
132 wchar_t getch()
133 {
134 /* skip spaces */
135 while (len != 0 && is_space(p.getch()))
136 {
137 ++idx;
138 p.inc(&len);
139 }
140
141 /* return the current character */
142 return getch_raw();
143 }
144
145 /* skip the current character */
146 void inc()
147 {
148 if (len != 0)
149 {
150 p.inc(&len);
151 ++idx;
152 }
153 }
154
155 /* get and skip the current character, skipping whitespace */
156 wchar_t nextch()
157 {
158 /* skip spaces */
159 while (len != 0 && is_space(p.getch()))
160 {
161 p.inc(&len);
162 ++idx;
163 }
164
165 /* if there's anything left, get and skip a character */
166 if (len != 0)
167 {
168 /* we have a character available - get the current character */
169 wchar_t ch = p.getch();
170
171 /* skip it */
172 p.inc(&len);
173 ++idx;
174
175 /* return the last character */
176 return ch;
177 }
178 else
179 {
180 /* no more characters available - return nul */
181 return 0;
182 }
183 }
184
185 /* parse an integer value */
186 int parse_int()
187 {
188 /* remember the starting location, for error reporting */
189 int start_idx = idx;
190
191 /* parse digits until we find something else */
192 int acc;
193 wchar_t c;
194 for (acc = 0 ; is_digit(c = getch()) ; inc())
195 {
196 /* add the digit into the accumulator */
197 acc *= 10;
198 acc += value_of_digit(c);
199
200 /* if this overflows an int, it's an error */
201 if (acc < 0)
202 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, start_idx);
203 }
204
205 /* return the result */
206 return acc;
207 }
208
209 /* get the current character index (1-based, for reporting to the user) */
210 int index() const { return idx; }
211
212 /* current pointer and remaining length */
213 utf8_ptr p;
214 size_t len;
215
216 /* current character index from the beginning of the string */
217 int idx;
218 };
219
220
221 /* ------------------------------------------------------------------------ */
222 /*
223 * Special repeat counts
224 */
225 const int ITER_NONE = -1; /* no repeat count specified */
226 const int ITER_STAR = -2; /* star '*' as the repeat count */
227
228
229 /* ------------------------------------------------------------------------ */
230 /*
231 * type code descriptor - this captures the type information for a single
232 * type code entry, including prefix and postfix flags
233 */
234 struct CVmPackType
235 {
236 CVmPackType()
237 {
238 type_code = 0;
239 big_endian = FALSE;
240 count = ITER_NONE;
241 count_as_type = 0;
242 count_in_bytes = FALSE;
243 up_to_count = FALSE;
244 bang = FALSE;
245 tilde = FALSE;
246 pct = FALSE;
247 fmtidx = 0;
248 null_term = FALSE;
249 qu = FALSE;
250 }
251
252 CVmPackType(const CVmPackGroup *g);
253
254 /* type code character */
255 wchar_t type_code;
256
257 /*
258 * for type codes '"' and '{', the literal text segment, as a pointer
259 * into the original format string buffer
260 */
261 CVmPackPos lit;
262
263 /* is it big-endian? */
264 int big_endian;
265
266 /*
267 * repeat count - this is the number of repetitions specified in the
268 * repeat count suffix, or a special ITER_xxx value
269 */
270 int count;
271
272 /* is the repeat count in bytes (:b suffix)? */
273 int count_in_bytes;
274
275 /*
276 * Repeat count as a type code. If the :X modifier if used, the X is
277 * another type code, and the repeat count is taken as the size of that
278 * type. This stores the type code in this case. We also set 'count'
279 * to the size of the type, so this is just preserving the extra
280 * information about the source of the size.
281 */
282 wchar_t count_as_type;
283
284 /*
285 * Should we treat the count as an upper bound? This is set if we
286 * combine '*' with a number, as in "H30*" - this means pack/unpack up
287 * to 30 items, but stop if we run out of source material first.
288 */
289 int up_to_count;
290
291 /* is there a '!' qualifier? */
292 int bang;
293
294 /* is there a '~' qualifier? */
295 int tilde;
296
297 /* is there a '%' qualifier? */
298 int pct;
299
300 /* is there a '?' qualifier? */
301 int qu;
302
303 /* is it null-terminated? */
304 int null_term;
305
306 /* format string index */
307 int fmtidx;
308
309 /* get the count - returns 1 as the implied count if none was specified */
310 int get_count() const { return has_count() ? count : 1; }
311
312 /* is there an explicit count specified? */
313 int has_count() const { return count >= 0; }
314 };
315
316
317 /* ------------------------------------------------------------------------ */
318 /*
319 * Pack string group. This represents a ( ) group within the string. The
320 * overall string is the root group. Each parenthesized group has its own
321 * set of modifiers, a repeat count, and establishes a starting byte offset
322 * for the "@" operator.
323 */
324 struct CVmPackGroup
325 {
326 /* set up the defaults for the root group */
327 CVmPackGroup(CVmPackPos *pos, CVmDataSource *ds)
328 : start(pos)
329 {
330 this->ds = ds;
331 parent = 0;
332 big_endian = FALSE;
333 tilde = FALSE;
334 pct = FALSE;
335 stream_ofs = ds->get_pos();
336 cur_iter = 1;
337 num_iters = 1;
338 up_to_iters = FALSE;
339 close_paren = 0;
340 }
341
342 /* set up a new nested group */
343 CVmPackGroup(CVmPackGroup *parent, wchar_t open_paren,
344 CVmPackPos *pos, const CVmPackType *t)
345 : parent(parent), start(pos)
346 {
347 ds = parent->ds;
348 stream_ofs = ds->get_pos();
349 cur_iter = 1;
350 big_endian = t->big_endian;
351 tilde = t->tilde;
352 pct = t->pct;
353 num_iters = t->count;
354 up_to_iters = t->up_to_count;
355 close_paren = (open_paren == '(' ? ')' :
356 open_paren == '[' ? ']' :
357 open_paren == '{' ? '}' : 0);
358 }
359
360 /* parent group */
361 CVmPackGroup *parent;
362
363 /* the paren type that closes the group */
364 wchar_t close_paren;
365
366 /*
367 * Default endian-ness within this group. The root group is
368 * little-endian by default, and each nested group inherits the
369 * endian-ness of its containing group.
370 */
371 int big_endian;
372
373 /*
374 * Default 'tilde' (~) modifier mode within this group. The root group
375 * has this turned off by default, and each nested group inherits its
376 * containing group's status.
377 */
378 int tilde;
379
380 /*
381 * Default 'percent' (%) modifier mode within this group. This is
382 * inherited like the endian-ness and tilde modifiers.
383 */
384 int pct;
385
386 /*
387 * Group start position in template string. This is the position of
388 * the first character after the open paren of the group.
389 */
390 CVmPackPos start;
391
392 /* data stream */
393 CVmDataSource *ds;
394
395 /*
396 * Group starting offset in the data stream. Each iteration of a group
397 * resets the zero point for '@' codes within the group.
398 */
399 long stream_ofs;
400
401 /* get the stream offset of the outermost parent */
402 long root_stream_ofs() const
403 {
404 return (parent != 0 ? parent->root_stream_ofs() : stream_ofs);
405 }
406
407 /* current iteration for this group */
408 int cur_iter;
409
410 /* total number of iterations for this group */
411 int num_iters;
412
413 /* is this an "up to" iteration count (e.g., 30*)? */
414 int up_to_iters;
415 };
416
417
418 /* ------------------------------------------------------------------------ */
419 /*
420 * CVmPackType implementation
421 */
422
423 CVmPackType::CVmPackType(const CVmPackGroup *g)
424 {
425 /* clear the type code and count */
426 type_code = 0;
427 count = ITER_NONE;
428 count_as_type = 0;
429 count_in_bytes = FALSE;
430 bang = FALSE;
431 qu = FALSE;
432 null_term = FALSE;
433
434 /* inherit group attributes */
435 big_endian = g->big_endian;
436 tilde = g->tilde;
437 pct = g->pct;
438 }
439
440
441 /* ------------------------------------------------------------------------ */
442 /*
443 * Packing argument list. There are two kinds of argument list: function
444 * arguments on the stack, or a list-like object.
445 */
446 struct CVmPackArgs
447 {
448 /* are there more arguments? */
449 virtual int more() = 0;
450
451 /* number of remaining arguments */
452 virtual int nrem() = 0;
453
454 /* get the current argument */
455 virtual vm_val_t *get(vm_val_t *val) = 0;
456
457 /* advance to the next argument */
458 virtual void next() = 0;
459 };
460
461 /*
462 * StackArgs represents arguments directly from a function/method call
463 * frame on the stack
464 */
465 struct StackArgs: CVmPackArgs
466 {
467 StackArgs(VMG_ int first_arg, int argc)
468 {
469 this->stk = G_stk;
470 this->curarg = first_arg;
471 this->lastarg = first_arg + argc - 1;
472 }
473
474 virtual int more() { return curarg <= lastarg; }
475 virtual int nrem() { return curarg <= lastarg ? lastarg - curarg + 1 : 0; }
476 virtual vm_val_t *get(vm_val_t *val)
477 {
478 if (curarg <= lastarg)
479 *val = *stk->get(curarg);
480 else
481 val->set_nil();
482 return val;
483 }
484 virtual void next() { ++curarg; }
485
486 CVmStack *stk;
487 int curarg;
488 int lastarg;
489 };
490
491 /*
492 * ListArgs represents arguments contained in a list. For a repeated item,
493 * the corresponding argument can be a list, in which case the repetitions
494 * are taken from the list:
495 *
496 * packBytes('a10 c5', 'hello', [1, 2, 3, 4, 5]);
497 */
498 struct ListArgs: CVmPackArgs
499 {
500 ListArgs(VMG_ vm_val_t *lst) { set(vmg_ lst); }
501
502 void set(VMG_ vm_val_t *lst)
503 {
504 this->vmg = VMGLOB_ADDR;
505 this->lst = *lst;
506 this->idx = 1;
507 this->len = lst->ll_length(vmg0_);
508 }
509
510 virtual int more() { return idx <= (len >= 0 ? len : 1); }
511 virtual int nrem()
512 {
513 int last = (len >= 0 ? len : 1);
514 return idx <= last ? last - idx + 1 : 0;
515 }
516 virtual vm_val_t *get(vm_val_t *val)
517 {
518 if (len < 0 && idx == 1)
519 {
520 /*
521 * we don't have a list, so pretend the value was wrapped in a
522 * single-element list by returning it at index 1
523 */
524 *val = lst;
525 }
526 else if (idx <= len)
527 {
528 /* we have a valid list and a valid index - get the element */
529 VMGLOB_PTR(vmg);
530 lst.ll_index(vmg_ val, idx);
531 }
532 else
533 {
534 /* we're past the end of the list - return nil */
535 val->set_nil();
536 }
537 return val;
538 }
539 virtual void next() { ++idx; }
540
541 /* get the effective count - the number of items we'll return */
542 int effective_count() { return len < 0 ? 1 : len; }
543
544 vm_globals *vmg;
545 vm_val_t lst;
546 int idx;
547 int len;
548 };
549
550 /*
551 * A single argument. This encapsulates an argument value that we've
552 * already resolved and represents it as an argument list with one element.
553 */
554 struct SingleArg: CVmPackArgs
555 {
556 SingleArg(const vm_val_t *val)
557 {
558 this->val = *val;
559 idx = 0;
560 }
561 SingleArg(long l)
562 {
563 val.set_int(l);
564 idx = 0;
565 }
566 SingleArg()
567 {
568 val.set_nil();
569 idx = 0;
570 }
571
572 virtual int more() { return idx == 0; }
573 virtual int nrem() { return idx == 0 ? 1 : 0; }
574 virtual vm_val_t *get(vm_val_t *val)
575 {
576 if (idx == 0)
577 *val = this->val;
578 else
579 val->set_nil();
580 return val;
581 }
582 virtual void next() { ++idx; }
583
584 vm_val_t val;
585 int idx;
586 };
587
588 /* ------------------------------------------------------------------------ */
589 /*
590 * Pack data from stack arguments into the given data stream
591 */
592 void CVmPack::pack(VMG_ int arg_index, int argc, CVmDataSource *dst)
593 {
594 /* the first argument is the format string - retrieve it */
595 const char *fmt = G_stk->get(arg_index)->get_as_string(vmg0_);
596 if (fmt == 0)
597 err_throw(VMERR_STRING_VAL_REQD);
598
599 /* get the format string length and buffer pointer */
600 size_t fmtlen = vmb_get_len(fmt);
601 fmt += VMB_LEN;
602
603 /* pack the root group */
604 CVmPackPos p(fmt, fmtlen);
605 CVmPackGroup root(&p, dst);
606 StackArgs args(vmg_ arg_index + 1, argc - 1);
607 pack_group(vmg_ &p, &args, &root, FALSE);
608
609 /* make sure we exhausted the string */
610 if (p.more())
611 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p.index());
612
613 /*
614 * if we didn't consume all of the arguments, it means that the format
615 * string didn't have enough entries for the supplied arguments - flag
616 * an error
617 */
618 if (args.more())
619 err_throw_a(VMERR_PACK_ARGC_MISMATCH, 1, ERR_TYPE_INT, (int)fmtlen+1);
620 }
621
622 /*
623 * Pack a group
624 */
625 void CVmPack::pack_group(VMG_ CVmPackPos *p, CVmPackArgs *args_main,
626 CVmPackGroup *group, int list_per_iter)
627 {
628 /* assume we're unpacking from the main argument list */
629 CVmPackArgs *args = args_main;
630
631 /*
632 * if there's a list per group iteration, the next argument should be a
633 * list from which we'll take arguments for this single iteration
634 */
635 vm_val_t listval;
636 ListArgs listargs(vmg_ args->get(&listval));
637 int more = args->more();
638 if (list_per_iter)
639 {
640 /* pull out and switch to the sublist for the first iteration */
641 more = args_main->more();
642 args = &listargs;
643 args_main->next();
644 }
645
646 /*
647 * if this is an up-to count, and the source list is empty, packing
648 * zero iterations is valid
649 */
650 if ((group->num_iters == ITER_STAR || group->up_to_iters) && !more)
651 {
652 /* skip the group in the source */
653 p->set(&group->start);
654 skip_group(p, group->close_paren);
655
656 /* we're done */
657 return;
658 }
659
660 /* run through the format list */
661 while (p->more())
662 {
663 /* check for group entry/exit */
664 wchar_t c = p->getch();
665 if (c == '(' || c == '[')
666 {
667 /* start of a group - pack the sub-group */
668 pack_subgroup(vmg_ p, args, group, 0);
669 }
670 else if (c == group->close_paren)
671 {
672 /*
673 * if we're reading arguments from a separate sublist per
674 * iteration of the group, move on to the next sublist
675 */
676 int more = args->more();
677 if (list_per_iter)
678 {
679 /* switch to the next sublist from the main arguments */
680 more = args_main->more();
681 listargs.set(vmg_ args_main->get(&listval));
682 args_main->next();
683 }
684
685 /*
686 * Determine if we're done. If the group has a '*' repeat
687 * count, we're done when we're out of arguments. If it has an
688 * up-to count, we're done if we're either out of arguments or
689 * at the iteration count limit. Otherwise, we're done when
690 * we've reached the iteration count limit.
691 */
692 if ((group->num_iters == ITER_STAR
693 ? !more
694 : group->cur_iter >= group->num_iters)
695 || (group->up_to_iters && !more))
696 {
697 /*
698 * if this is an up-to count, make sure we consumed all
699 * arguments
700 */
701 if (group->up_to_iters)
702 {
703 if (list_per_iter)
704 for ( ; args_main->more() ; args_main->next()) ;
705 else
706 for ( ; args->more() ; args->next()) ;
707 }
708
709 /* done */
710 return;
711 }
712
713 /*
714 * We're going back for another iteration of the group.
715 * Increment the iteration count, and go back to the start of
716 * the group in the template string.
717 */
718 group->cur_iter++;
719 group->stream_ofs = group->ds->get_pos();
720 p->set(&group->start);
721 }
722 else
723 {
724 /*
725 * It's not a group, so it must be a single item. Parse the
726 * item definition.
727 */
728 CVmPackType t;
729 parse_type(p, &t, group);
730
731 /* check to see if this is a length prefix to the next item */
732 if (p->getch() == '/')
733 {
734 /* skip the '/' */
735 p->inc();
736
737 /* check for a group */
738 if ((c = p->getch()) == '(' || c == '[')
739 {
740 /* go pack the subgroup with the prefix count */
741 pack_subgroup(vmg_ p, args, group, &t);
742 }
743 else
744 {
745 /*
746 * It's not a group, so it must be a single item.
747 * Parse the item definition.
748 */
749 CVmPackType t2;
750 parse_type(p, &t2, group);
751
752 /* pack the item with the count prefix */
753 pack_item(vmg_ group, args, &t2, &t);
754 }
755 }
756 else
757 {
758 /* there's no count prefix - go pack the single item */
759 pack_item(vmg_ group, args, &t, 0);
760 }
761 }
762 }
763 }
764
765 /*
766 * Pack a subgroup
767 */
768 void CVmPack::pack_subgroup(VMG_ CVmPackPos *p, CVmPackArgs *args,
769 CVmPackGroup *group, CVmPackType *prefix_count)
770 {
771 /* get the output stream */
772 CVmDataSource *dst = group->ds;
773
774 /* parse the group modifiers */
775 CVmPackType gt(group);
776 parse_group_mods(p, &gt);
777
778 /* note the open paren */
779 wchar_t paren = p->getch();
780
781 /* set up a child group definition reflecting the modifiers */
782 p->inc();
783 CVmPackGroup child(group, paren, p, &gt);
784
785 /* set up a list argument reader, in case we have a list for the group */
786 vm_val_t arg;
787 ListArgs la(vmg_ args->get(&arg));
788
789 /*
790 * Set up the child argument list. If the open paren for the list in
791 * the template is '[', the arguments come from a list; otherwise they
792 * come from the main argument list.
793 */
794 CVmPackArgs *child_args = args;
795 int list_per_iter = FALSE;
796 if (paren == '[')
797 {
798 /* [] group - pack from a list or a set of lists */
799 if (gt.bang)
800 {
801 /* ! modifier - each iteration is a separate sublist */
802 list_per_iter = TRUE;
803 }
804 else
805 {
806 /* "[ ]" group - the whole group comes from a single sublist */
807 child_args = &la;
808 args->next();
809 }
810 }
811
812 /* check for a prefix count */
813 long prefix_pos = 0;
814 if (prefix_count != 0)
815 {
816 /* remember the location of the prefix */
817 prefix_pos = dst->get_pos();
818
819 /* pack a zero count as a placeholder */
820 SingleArg count((long)0);
821 pack_one_item(vmg_ group, &count, prefix_count, 0);
822
823 /* the prefix count overrides any suffix count with '*' */
824 child.num_iters = ITER_STAR;
825 }
826
827 /* recursively pack the child group */
828 pack_group(vmg_ p, child_args, &child, list_per_iter);
829
830 /* make sure we stopped at the close paren */
831 if (p->nextch() != child.close_paren)
832 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index());
833
834 /*
835 * if there was a prefix count, go back and patch it with the actual
836 * iteration count
837 */
838 if (prefix_count != 0)
839 {
840 /* save the end-of-group position, and seek back to the count */
841 long endpos = dst->get_pos();
842 dst->seek(prefix_pos, OSFSK_SET);
843
844 /* it's an error if the prefix count is a variable-length item */
845 if (prefix_count->type_code == 'k'
846 || (is_varying_length(prefix_count->type_code)
847 && prefix_count->count == ITER_STAR))
848 err_throw_a(VMERR_PACK_ARG_MISMATCH, 1, ERR_TYPE_INT,
849 prefix_count->fmtidx);
850
851 /* write the count */
852 SingleArg count(child.cur_iter);
853 pack_one_item(vmg_ group, &count, prefix_count, 0);
854
855 /* seek back to the end of the group */
856 dst->seek(endpos, OSFSK_SET);
857 }
858
859 /* skip any modifiers after the group */
860 parse_mods(p, &gt);
861 }
862
863
864 /* ------------------------------------------------------------------------ */
865 /*
866 * Write padding bytes. We write alternating ch1 and ch2 bytes to fill out
867 * the byte count.
868 */
869 void CVmPack::write_padding(CVmDataSource *dst, char ch1, char ch2, long cnt)
870 {
871 /* set up a buffer full of the padding bytes */
872 char buf[256];
873 for (size_t i = 0 ; i < sizeof(buf) ; buf[i++] = ch1, buf[i++] = ch2) ;
874
875 /* keep going until we satisfy the request */
876 while (cnt > 0)
877 {
878 /* write out one buffer-full, or the remaining amount if less */
879 size_t cur = (cnt > (long)sizeof(buf) ? sizeof(buf) : (size_t)cnt);
880 if (dst->write(buf, cur))
881 err_throw(VMERR_WRITE_FILE);
882
883 /* deduct this from the remaining request */
884 cnt -= cur;
885 }
886 }
887 void CVmPack::write_padding(CVmDataSource *dst, char ch, long cnt)
888 {
889 write_padding(dst, ch, ch, cnt);
890 }
891
892 /* ------------------------------------------------------------------------ */
893 /*
894 * get an integer value, enforcing the given limits
895 */
896 static long intval(VMG_ const vm_val_t *val, long minval, long maxval,
897 int pct, unsigned long mask)
898 {
899 /* get the value */
900 long l;
901 switch (val->typ)
902 {
903 case VM_NIL:
904 /* use 0 for nil */
905 l = 0;
906 break;
907
908 case VM_INT:
909 /* regular integer */
910 l = val->val.intval;
911 break;
912
913 case VM_OBJ:
914 /*
915 * convert BigNumber to integer explicitly; use the type cast for
916 * other types
917 */
918 if (CVmObjBigNum::is_bignum_obj(vmg_ val->val.obj))
919 {
920 /* explicitly cast the BigNumber so that we can catch overflows */
921 int ov;
922 if (minval < 0)
923 {
924 l = ((CVmObjBigNum *)vm_objp(vmg_ val->val.obj))
925 ->convert_to_int(ov);
926 }
927 else
928 {
929 l = (long)((CVmObjBigNum *)vm_objp(vmg_ val->val.obj))
930 ->convert_to_uint(ov);
931 }
932
933 /* check for overflow */
934 if (ov && !pct)
935 err_throw(VMERR_NUM_OVERFLOW);;
936
937 /* done */
938 break;
939 }
940 /* FALL THROUGH to default */
941
942 default:
943 /* use the generic type cast */
944 l = val->cast_to_int(vmg0_);
945 break;
946 }
947
948 /* if the '%' flag is set, truncate the value, otherwise check the range */
949 if (pct)
950 {
951 /* % modifier - truncate the value to fit the type */
952 l &= mask;
953 }
954 else
955 {
956 /* no % modifier - enforce the range */
957 if (l < minval || l > maxval)
958 err_throw(VMERR_NUM_OVERFLOW);
959 }
960
961 /* return the value */
962 return l;
963 }
964
965 /*
966 * integer decomposition - get the low-order byte and shift
967 */
968 static inline char lsb(long &l, int is_signed)
969 {
970 /* note the sign */
971 int neg = l < 0;
972
973 /* the return value is the low-order byte */
974 char ret = (char)(l & 0xff);
975
976 /* shift the value to remove the low-order byte */
977 l >>= 8;
978
979 /* mask off the high byte */
980 l &= 0x00ffffff;
981
982 /* if it's a signed negative value, put 1 bits in the high byte */
983 if (is_signed && neg)
984 l |= 0xff000000;
985
986 /* return the low byte */
987 return ret;
988 }
989
990 /*
991 * reverse the byte order of a buffer
992 */
993 static void reverse_bytes(char *buf, size_t len)
994 {
995 /*
996 * Run through the buffer from opposite ends, swapping each byte pair.
997 * Stop when our left index crosses our right index. If the buffer
998 * length is even, the two indices will pass each other; if the length
999 * is even, they'll both land on the middle byte of the buffer at the
1000 * same time. Simply keep going as long as the left index is less than
1001 * the right index.
1002 */
1003 int i, j;
1004 for (i = 0, j = len - 1 ; i < j ; ++i, --j)
1005 {
1006 /* swap the current high/low pair */
1007 char tmp = buf[i];
1008 buf[i] = buf[j];
1009 buf[j] = tmp;
1010 }
1011 }
1012
1013
1014 /* ------------------------------------------------------------------------ */
1015 /*
1016 * String source for packing. We can pack strings and ByteArrays into
1017 * character fields; this class is an abstraction for the different types
1018 * of sources.
1019 */
1020 class CharFieldSource
1021 {
1022 public:
1023 virtual ~CharFieldSource() { }
1024
1025 /* create a concrete CharFieldSource for a value */
1026 static CharFieldSource *create(VMG_ const vm_val_t *val, vm_val_t *newval);
1027
1028 /* get the array length to use for the given field type */
1029 virtual int arraylen(CVmPackType *t) = 0;
1030
1031 /* is another character available? */
1032 virtual int more() = 0;
1033
1034 /* get the next character */
1035 virtual wchar_t getch() = 0;
1036 };
1037
1038 /* string source */
1039 class CharFieldSourceString: public CharFieldSource
1040 {
1041 public:
1042 CharFieldSourceString(const char *src, size_t len)
1043 : p((char *)src), len(len)
1044 { }
1045
1046 virtual int more() { return len != 0; }
1047 virtual wchar_t getch()
1048 {
1049 if (len != 0)
1050 {
1051 wchar_t ch = p.getch();
1052 p.inc(&len);
1053 return ch;
1054 }
1055 else
1056 return 0;
1057 }
1058
1059 virtual int arraylen(CVmPackType *t)
1060 {
1061 switch (t->type_code)
1062 {
1063 case 'a':
1064 case 'A':
1065 case 'b':
1066 /* the length is in bytes, and we write one byte per character */
1067 return p.len(len);
1068
1069 case 'w':
1070 case 'W':
1071 /*
1072 * the default length is in characters; if counting in bytes,
1073 * we need two bytes per character
1074 */
1075 return (t->count_in_bytes ? 2 : 1) * p.len(len);
1076
1077 case 'h':
1078 case 'H':
1079 /*
1080 * the length is in source nibbles, one nibble per character;
1081 * in bytes, we need half as many bytes as characters, rounded
1082 * up
1083 */
1084 return t->count_in_bytes ? (p.len(len)+1)/2 : p.len(len);
1085
1086 case 'u':
1087 case 'U':
1088 /*
1089 * the length is in bytes, in UTF-8 format; this is the same
1090 * format as our underlying string, so we can simply return its
1091 * byte length
1092 */
1093 return len;
1094
1095 default:
1096 return 0;
1097 }
1098 }
1099
1100 protected:
1101 /* utf8 pointer and remaining byte length */
1102 utf8_ptr p;
1103 size_t len;
1104 };
1105
1106 /* ByteArray source */
1107 class CharFieldSourceByteArray: public CharFieldSource
1108 {
1109 public:
1110 CharFieldSourceByteArray(VMG_ vm_obj_id_t id)
1111 {
1112 arr = (CVmObjByteArray *)vm_objp(vmg_ id);
1113 idx = 0;
1114 len = arr->get_element_count();
1115 }
1116
1117 virtual int more() { return idx < len; }
1118 virtual wchar_t getch() { return idx < len ? arr->get_element(++idx) : 0; }
1119
1120 virtual int arraylen(CVmPackType *t)
1121 {
1122 switch (t->type_code)
1123 {
1124 case 'a':
1125 case 'A':
1126 case 'b':
1127 /*
1128 * the length is in bytes, and we write one byte per character;
1129 * we treat each byte in the array as a Latin-1 character, so
1130 * this is the same as our array length
1131 */
1132 return (int)len;
1133
1134 case 'w':
1135 case 'W':
1136 /*
1137 * The length is in characters, or two bytes per character. We
1138 * treat our bytes as latin-1 characters, so the character
1139 * count is the saqme as the array length.
1140 */
1141 return (int)(t->count_in_bytes ? len*2 : len);
1142
1143 case 'h':
1144 case 'H':
1145 /*
1146 * one character per array element, or one byte per pair of
1147 * array elements
1148 */
1149 return (int)(t->count_in_bytes ? (len+1)/2 : len);
1150
1151 case 'u':
1152 case 'U':
1153 /*
1154 * The length is in bytes, in UTF-8 format. We treat our array
1155 * elements as Latin-1 characters. In UTF-8, characters in the
1156 * range 0-127 take one byte, and 128-255 take two bytes. Run
1157 * through our array and add up the required lengths.
1158 */
1159 {
1160 int ret;
1161 unsigned long i;
1162 for (ret = 0, i = 1 ; i <= len ; ++i)
1163 ret += arr->get_element(i) < 128 ? 1 : 2;
1164
1165 /* return the length */
1166 return ret;
1167 }
1168
1169 default:
1170 return 0;
1171 }
1172 }
1173
1174 protected:
1175 /* ByteArray object */
1176 CVmObjByteArray *arr;
1177
1178 /* current byte index */
1179 unsigned long idx;
1180
1181 /* length of the array */
1182 unsigned long len;
1183 };
1184
1185 /* create an appropriate CharFieldSource subclass for a given value */
1186 CharFieldSource *CharFieldSource::create(
1187 VMG_ const vm_val_t *val, vm_val_t *newval)
1188 {
1189 /* presume we won't create a new value */
1190 newval->set_nil();
1191
1192 /* check to see if it's a ByteArray */
1193 if (val->typ == VM_OBJ
1194 && CVmObjByteArray::is_byte_array(vmg_ val->val.obj))
1195 return new CharFieldSourceByteArray(vmg_ val->val.obj);
1196
1197 /* it's not another acceptable type, so it has to be a string */
1198 const char *str = val->cast_to_string(vmg_ newval);
1199 return new CharFieldSourceString(str + VMB_LEN, vmb_get_len(str));
1200 }
1201
1202
1203 /* ------------------------------------------------------------------------ */
1204 /*
1205 * String character-to-byte converters. Each one of these has a singleton
1206 * instance that we use in the item packer. These objects have no state
1207 * (they're really just a convenient way to write function vectors, via
1208 * their virtual methods), so the static singletons are inherently
1209 * thread-safe.
1210 */
1211 class CharConv
1212 {
1213 public:
1214 /* convert one character from source to packed format */
1215 virtual void putch(char *&buf, wchar_t ch, int idx, int pct) = 0;
1216
1217 /*
1218 * Close out a packed string. This is required for formats that write
1219 * multiple source characters per byte, such as 'hH', to make sure we
1220 * write out any partially built last byte. Formats that write one or
1221 * more complete bytes per source character need do nothing here.
1222 */
1223 virtual void putch_end(char *&buf, int idx) { }
1224
1225 /* write a null terminator */
1226 virtual void null_term(CVmDataSource *dst)
1227 {
1228 if (dst->write("\0", 1))
1229 err_throw(VMERR_WRITE_FILE);
1230 }
1231
1232 /*
1233 * Get the field width in bytes for the given descriptor. If the
1234 * descriptor's repeat count is explicitly stated in bytes, this simply
1235 * returns the repeat count. Otherwise, we translate the repeat count
1236 * to a byte count according to the underlying character encoding.
1237 */
1238 int get_byte_count(const CVmPackType *t)
1239 { return t->count_in_bytes ? t->get_count() : count_to_bytes(t); }
1240
1241 /* translate a repeat count to a byte length; assume 1-to-1 by default */
1242 virtual int count_to_bytes(const CVmPackType *t)
1243 { return t->get_count(); }
1244
1245 /* translate a byte length to a repeat count; assume 1-to-1 by default */
1246 virtual long bytes_to_count(long bytes)
1247 { return bytes; }
1248
1249 /* write space or nul padding - by default, write single-byte padding */
1250 virtual void pad(CVmDataSource *dst, char ch, long str_bytes,
1251 const CVmPackType *t)
1252 {
1253 CVmPack::write_padding(dst, ch, get_byte_count(t) - str_bytes);
1254 }
1255
1256 /* unpack file data */
1257 virtual void unpack(VMG_ vm_val_t *val, CVmDataSource *src, int cnt,
1258 char pad)
1259 {
1260 /* if the requested length is zero, return an empty string */
1261 if (cnt == 0)
1262 {
1263 val->set_obj(CVmObjString::create(vmg_ FALSE, 0));
1264 return;
1265 }
1266
1267 /*
1268 * By default, we return a string. Set up a wide character buffer
1269 * to hold the input.
1270 */
1271 wchar_t *wbuf = new wchar_t[cnt];
1272 if (wbuf == 0)
1273 err_throw(VMERR_OUT_OF_MEMORY);
1274
1275 err_try
1276 {
1277 /* read the data */
1278 read(wbuf, src, cnt);
1279
1280 /* remove padding characters from the end of the string */
1281 for ( ; cnt > 0 && wbuf[cnt-1] == pad ; --cnt) ;
1282
1283 /* create the string */
1284 val->set_obj(CVmObjString::create(vmg_ FALSE, wbuf, cnt));
1285 }
1286 err_finally
1287 {
1288 delete [] wbuf;
1289 }
1290 err_end;
1291 }
1292
1293 /* unpack file data for a varying-length field with null termination */
1294 void unpackz(VMG_ vm_val_t *val, CVmDataSource *src)
1295 {
1296 /* set up a string with an initial guess at the size */
1297 val->set_obj(CVmObjString::create(vmg_ FALSE, 256));
1298 CVmObjString *str = (CVmObjString *)vm_objp(vmg_ val->val.obj);
1299 G_stk->push(val);
1300
1301 /* read characters until we reach the null terminator */
1302 char *dst = str->cons_get_buf();
1303 for (;;)
1304 {
1305 /* read a character */
1306 wchar_t ch = readch(src);
1307
1308 /* if it's the null character, we're done */
1309 if (ch == 0)
1310 break;
1311
1312 /* append it to the string */
1313 dst = str->cons_append(vmg_ dst, ch, 256);
1314 }
1315
1316 /* set the final size of the string */
1317 str->cons_shrink_buffer(vmg_ dst);
1318 }
1319
1320 /* read a single character */
1321 virtual wchar_t readch(CVmDataSource *src)
1322 {
1323 /* read a byte into our buffer */
1324 char buf[1];
1325 if (src->read(buf, 1))
1326 err_throw(VMERR_READ_FILE);
1327
1328 /* return the character */
1329 return buf[0];
1330 }
1331
1332 /* get the character converter for a given type code */
1333 static CharConv *conv_for_type(const CVmPackType *t);
1334
1335 protected:
1336 /* read from the data source, converting to wide characters */
1337 virtual void read(wchar_t *buf, CVmDataSource *src, int cnt) = 0;
1338 };
1339
1340 /*
1341 * Latin-1 converter, for 'a' and 'A' formats
1342 */
1343 class CharConvLatin1: public CharConv
1344 {
1345 public:
1346 virtual void putch(char *&buf, wchar_t ch, int idx, int pct)
1347 {
1348 /* latin-1 - store the character if it's in range, '?' otherwise */
1349 *buf++ = (ch <= 255 ? (char)ch : pct ? (char)ch & 0xff : '?');
1350 }
1351
1352 virtual void read(wchar_t *buf, CVmDataSource *src, int cnt)
1353 {
1354 /* read the latin-1 character bytes into the buffer */
1355 if (src->read(buf, cnt))
1356 err_throw(VMERR_READ_FILE);
1357
1358 /*
1359 * The file characters are bytes, but we want wide characters. The
1360 * bytewise read packed the Latin-1 byte representations into the
1361 * lower half of the buffer. Run through the buffer from the end,
1362 * expanding each byte into a wide character. This is trivial for
1363 * Latin-1 since a Latin-1 code point is identical to the
1364 * corresponding Unicode code point.
1365 */
1366 for (int i = cnt - 1 ; i >= 0 ; --i)
1367 buf[i] = (wchar_t)(((unsigned char *)buf)[i]);
1368 }
1369 };
1370 static CharConvLatin1 s_CharConvLatin1;
1371
1372 /*
1373 * Byte converter, for 'b' format
1374 */
1375 class CharConvByte: public CharConv
1376 {
1377 virtual void putch(char *&buf, wchar_t ch, int idx, int pct)
1378 {
1379 /* raw bytes - make sure the byte is in range */
1380 if (ch > 255)
1381 {
1382 /* % modifier -> truncate to byte, otherwise it's an error */
1383 if (pct)
1384 ch &= 0xff;
1385 else
1386 err_throw(VMERR_NUM_OVERFLOW);
1387 }
1388
1389 /* store it */
1390 *buf++ = (char)ch;
1391 }
1392
1393 /* unpack file data */
1394 virtual void unpack(VMG_ vm_val_t *val, CVmDataSource *src, int cnt,
1395 char pad)
1396 {
1397 /*
1398 * For the byte type, we unpack into a ByteArray object rather than
1399 * a string, and we leave any padding intact. Create a byte array
1400 * with the required size (and push it for gc protection).
1401 */
1402 val->set_obj(CVmObjByteArray::create(vmg_ FALSE, cnt));
1403 CVmObjByteArray *arr = (CVmObjByteArray *)vm_objp(vmg_ val->val.obj);
1404 G_stk->push(val);
1405
1406 /* read the data (don't save undo, since it's a new object) */
1407 if ((int)arr->read_from_file(
1408 vmg_ val->val.obj, src, 1, cnt, FALSE) != cnt)
1409 err_throw(VMERR_READ_FILE);
1410
1411 /* done with the gc protection */
1412 G_stk->discard();
1413 }
1414
1415 /* we don't need to read characters, since we unpack into a byte array */
1416 virtual void read(wchar_t *, CVmDataSource *, int) { }
1417 };
1418 static CharConvByte s_CharConvByte;
1419
1420 /*
1421 * UTF8 converter, for 'u' and 'U' formats
1422 */
1423 class CharConvUTF8: public CharConv
1424 {
1425 public:
1426 virtual void putch(char *&buf, wchar_t ch, int idx, int pct)
1427 {
1428 /* utf8 - store the utf8 sequence for the character */
1429 buf += utf8_ptr::s_putch(buf, ch);
1430 }
1431
1432 /* read a single character */
1433 virtual wchar_t readch(CVmDataSource *src)
1434 {
1435 /* read the first byte */
1436 char buf[10];
1437 if (src->read(buf, 1))
1438 err_throw(VMERR_READ_FILE);
1439
1440 /* figure how many more bytes we have to read */
1441 size_t len = utf8_ptr::s_charsize(buf[0]);
1442 if (len > sizeof(buf))
1443 len = sizeof(buf);
1444
1445 /* read the rest of the bytes */
1446 if (len > 1 && src->read(buf+1, len-1))
1447 err_throw(VMERR_READ_FILE);
1448
1449 /* return the translated character */
1450 return utf8_ptr::s_getch(buf);
1451 }
1452
1453 /* unpack file data */
1454 virtual void unpack(VMG_ vm_val_t *val, CVmDataSource *src, int cnt,
1455 char pad)
1456 {
1457 /*
1458 * For UTF-8, we can simply read the bytes directly into a string
1459 * buffer. Allocate the string at the required byte size, and push
1460 * for gc protection.
1461 */
1462 val->set_obj(CVmObjString::create(vmg_ FALSE, cnt));
1463 CVmObjString *str = (CVmObjString *)vm_objp(vmg_ val->val.obj);
1464 G_stk->push(val);
1465
1466 /* if the read count is non-zero, read the data */
1467 if (cnt != 0)
1468 {
1469 /* read the data directly into the string buffer */
1470 if (src->read(str->cons_get_buf(), cnt))
1471 err_throw(VMERR_READ_FILE);
1472
1473 /* validate the UTF-8 */
1474 CCharmapToUni::validate(str->cons_get_buf(), cnt);
1475
1476 /* remove trailing padding */
1477 utf8_ptr p(str->cons_get_buf() + cnt);
1478 for (size_t rem = 0 ; (int)rem < cnt ; )
1479 {
1480 /*
1481 * move to the previous character; if it's not the padding
1482 * character, we're done
1483 */
1484 p.dec(&rem);
1485 if (p.getch() != pad)
1486 {
1487 p.inc(&rem);
1488 break;
1489 }
1490 }
1491
1492 /* set the string length to the length without the padding */
1493 str->cons_shrink_buffer(vmg_ p.getptr());
1494 }
1495
1496 /* done with the gc protection */
1497 G_stk->discard();
1498 }
1499
1500 /* we don't need a low-level wchar_t reader */
1501 virtual void read(wchar_t *, CVmDataSource *, int) { }
1502 };
1503 static CharConvUTF8 s_CharConvUTF8;
1504
1505 /*
1506 * Base class for UCS2 converters, for 'w' and 'W' formats
1507 */
1508 class CharConvUCS2: public CharConv
1509 {
1510 public:
1511 virtual void read(wchar_t *buf, CVmDataSource *src, int cnt)
1512 {
1513 /*
1514 * Read the wide characters (two bytes each). The local wchar_t
1515 * type could be bigger than two bytes, but can't be less, so we
1516 * can be sure we have enough space for the file read.
1517 */
1518 if (src->read(buf, cnt*2))
1519 err_throw(VMERR_READ_FILE);
1520
1521 /*
1522 * Convert each character from little-endian to local byte order.
1523 * The local wchar_t type could be bigger than two bytes, so work
1524 * from the end of the buffer downwards - this will ensure we won't
1525 * overwrite bytes before we translate them.
1526 */
1527 for (int i = cnt - 1 ; i > 0 ; --i)
1528 buf[i] = file_to_machine((unsigned char *)buf + i*2);
1529 }
1530
1531 /* UCS-2 nulls are two bytes, like every other wide character */
1532 virtual void null_term(CVmDataSource *dst)
1533 {
1534 if (dst->write("\0\0", 2))
1535 err_throw(VMERR_WRITE_FILE);
1536 }
1537
1538 /* read a single character */
1539 virtual wchar_t readch(CVmDataSource *src)
1540 {
1541 /* read a two-byte character into our buffer */
1542 unsigned char buf[2];
1543 if (src->read(buf, 2))
1544 err_throw(VMERR_READ_FILE);
1545
1546 /* return the character */
1547 return file_to_machine(buf);
1548 }
1549
1550 /*
1551 * the wide-char formats treat the repeat count as a character count,
1552 * so the byte count is double the repeat count
1553 */
1554 virtual int count_to_bytes(const CVmPackType *t)
1555 { return t->get_count() * 2; }
1556
1557 virtual long bytes_to_count(long bytes)
1558 { return (bytes + 1) / 2; }
1559
1560 protected:
1561 /* convert a wchar_t from file byte order to local machine byte order */
1562 virtual wchar_t file_to_machine(const unsigned char *ch) = 0;
1563 };
1564
1565 /*
1566 * Little-endian UCS2 converter, for 'w' and 'W' formats
1567 */
1568 class CharConvUCS2L: public CharConvUCS2
1569 {
1570 public:
1571 virtual void putch(char *&buf, wchar_t ch, int idx, int pct)
1572 {
1573 /* UCS-2 little-endian - store the low byte first */
1574 *buf++ = (char)(ch & 0xff);
1575 *buf++ = (char)((ch >> 8) & 0xff);
1576 }
1577
1578 virtual void pad(CVmDataSource *dst, char ch, long str_bytes,
1579 const CVmPackType *t)
1580 { CVmPack::write_padding(dst, ch, 0, get_byte_count(t) - str_bytes); }
1581
1582 virtual wchar_t file_to_machine(const unsigned char *p)
1583 {
1584 return (wchar_t)p[0] + (((wchar_t)p[1]) << 8);
1585 }
1586 };
1587 static CharConvUCS2L s_CharConvUCS2L;
1588
1589 /*
1590 * Big-endian UCS2 converter, for 'w' and 'W' formats
1591 */
1592 class CharConvUCS2B: public CharConvUCS2
1593 {
1594 public:
1595 virtual void putch(char *&buf, wchar_t ch, int idx, int pct)
1596 {
1597 /* UCS2 big-endian - store the high byte first */
1598 *buf++ = (char)((ch >> 8) & 0xff);
1599 *buf++ = (char)(ch & 0xff);
1600 }
1601
1602 virtual void pad(CVmDataSource *dst, char ch, long str_bytes,
1603 const CVmPackType *t)
1604 { CVmPack::write_padding(dst, 0, ch, get_byte_count(t) - str_bytes); }
1605
1606 virtual wchar_t file_to_machine(const unsigned char *p)
1607 {
1608 return (wchar_t)p[1] + (((wchar_t)p[0]) << 8);
1609 }
1610 };
1611 static CharConvUCS2B s_CharConvUCS2B;
1612
1613 /*
1614 * Hex string converter, for 'h' and 'H' foramts
1615 */
1616 class CharConvHex: public CharConv
1617 {
1618 public:
1619 virtual void read(wchar_t *buf, CVmDataSource *src, int cnt)
1620 {
1621 /*
1622 * Read the packed bytes. We need half a byte per hex nibble,
1623 * rounding up if we want an odd number of nibbles.
1624 */
1625 if (src->read(buf, (cnt+1)/2))
1626 err_throw(VMERR_READ_FILE);
1627
1628 /*
1629 * Convert each byte into a pair of hex nibbles. Since the
1630 * unpacked representation is larger than the bytes that we read,
1631 * work from the top end of the buffer backwards.
1632 */
1633 for (int i = cnt - 1 ; i >= 0 ; --i)
1634 {
1635 unsigned char *p = ((unsigned char *)buf) + i/2;
1636 buf[i] = int_to_xdigit(byte_to_nibble(*p, i & 1));
1637 }
1638 }
1639
1640 virtual void putch(char *&buf, wchar_t ch, int idx, int pct)
1641 {
1642 /* get the nibble value from the character */
1643 int d = is_xdigit(ch) ? value_of_xdigit(ch) : 0;
1644 int n = nibble_to_byte(d, idx & 1);
1645
1646 /*
1647 * if this is an even index, it's the first nibble of the byte, so
1648 * set the whole byte to the nibble value; if it's an odd index,
1649 * it's the second nibble for the byte, so OR it into the byte and
1650 * increment the output pointer
1651 */
1652 if (idx & 1)
1653 *buf++ |= (char)n;
1654 else
1655 *buf = (char)n;
1656 }
1657
1658 virtual void putch_end(char *&buf, int idx)
1659 {
1660 /*
1661 * If we wrote an odd number of source characters, we've only
1662 * written a partial last byte.
1663 */
1664 if (idx & 1)
1665 ++buf;
1666 }
1667
1668 /*
1669 * The repeat count for this format is in nibbles of the unpacked hex
1670 * string, which corresponds to half-bytes in the packed stream. Round
1671 * up if it's odd.
1672 */
1673 virtual int count_to_bytes(const CVmPackType *t)
1674 { return (t->get_count() + 1)/2; }
1675
1676 virtual long bytes_to_count(long bytes)
1677 { return bytes * 2; }
1678
1679 protected:
1680 /*
1681 * Extract a hex nibble from a byte. 'idx' is zero for the first
1682 * nibble of a pair, 1 for the second nibble of a pair, in unpacked
1683 * string order.
1684 */
1685 virtual int byte_to_nibble(int b, int idx) = 0;
1686
1687 /* convert a nibble value to a byte value */
1688 virtual int nibble_to_byte(int n, int idx) = 0;
1689 };
1690
1691 /*
1692 * Hex string converter, low nibble first, for 'h' format
1693 */
1694 class CharConvHexL: public CharConvHex
1695 {
1696 public:
1697 virtual int byte_to_nibble(int b, int idx)
1698 { return (idx ? (b >> 4) : b) & 0x0F; }
1699
1700 virtual int nibble_to_byte(int b, int idx)
1701 { return (idx ? (b << 4) & 0xF0 : b & 0x0F); }
1702 };
1703 static CharConvHexL s_CharConvHexL;
1704
1705 /*
1706 * Hex string converter, high nibble first, for 'H' format
1707 */
1708 class CharConvHexB: public CharConvHex
1709 {
1710 public:
1711 virtual int byte_to_nibble(int b, int idx)
1712 { return (idx ? b : (b >> 4)) & 0x0F; }
1713
1714 virtual int nibble_to_byte(int b, int idx)
1715 { return (idx ? b & 0x0F : (b << 4) & 0xF0); }
1716 };
1717 static CharConvHexB s_CharConvHexB;
1718
1719 /*
1720 * Get the converter for a given type code
1721 */
1722 CharConv *CharConv::conv_for_type(const CVmPackType *t)
1723 {
1724 switch (t->type_code)
1725 {
1726 case 'a':
1727 case 'A':
1728 return &s_CharConvLatin1;
1729
1730 case 'b':
1731 return &s_CharConvByte;
1732
1733 case 'u':
1734 case 'U':
1735 return &s_CharConvUTF8;
1736
1737 case 'w':
1738 case 'W':
1739 if (t->big_endian)
1740 return &s_CharConvUCS2B;
1741 else
1742 return &s_CharConvUCS2L;
1743
1744 case 'h':
1745 return &s_CharConvHexL;
1746
1747 case 'H':
1748 return &s_CharConvHexB;
1749
1750 default:
1751 /* it's not a string type */
1752 return 0;
1753 }
1754 }
1755
1756
1757 /* ------------------------------------------------------------------------ */
1758 /*
1759 * Write the bytes for a numeric value
1760 */
1761 static void write_num_bytes(class CVmDataSource *dst,
1762 char *buf, const CVmPackType *t, size_t len)
1763 {
1764 /*
1765 * we always prepare our buffers in our standard little-endian byte
1766 * order, so if the type has a big-endian flag, we need to reverse the
1767 * byte order
1768 */
1769 if (len > 1 && t->big_endian)
1770 reverse_bytes(buf, len);
1771
1772 /* write the bytes */
1773 if (dst->write(buf, len))
1774 err_throw(VMERR_WRITE_FILE);
1775 }
1776
1777 /*
1778 * Encode a BER compressed unsigned integer value. This format stores an
1779 * unsigned integer as a series of bytes representing base-128 digits. The
1780 * most significant digit is always stored first (there's no little-endian
1781 * variant of this format). Each byte except the last has its high bit
1782 * (0x80) set, to indicate that more bytes follow. We can store integers
1783 * or BigNumber values in this format.
1784 */
1785 static void encode_ber(char *buf, size_t &blen, uint32_t l)
1786 {
1787 /* nothing in the buffer yet */
1788 blen = 0;
1789
1790 /* if it's zero, the result is trivial */
1791 if (l == 0)
1792 {
1793 buf[blen++] = 0;
1794 return;
1795 }
1796
1797 /* generate the bytes of the absolute value */
1798 int shift, mask;
1799 for (shift = 28, mask = 0x08 ; shift >= 0 ; shift -= 7, mask = 0x7f)
1800 {
1801 /* get the next most significant 128-based "digit" */
1802 char b = (char)((l >> shift) & mask);
1803
1804 /* if it's significant (non-zero or not the first digit), write it */
1805 if (b != 0 || blen != 0)
1806 buf[blen++] = b;
1807 }
1808
1809 /* set the high bit in every byte except the last */
1810 for (size_t i = 0 ; i < blen - 1 ; ++i)
1811 buf[i] |= 0x80;
1812 }
1813
1814 /*
1815 * Decode a BER-encoded integer.
1816 */
1817 static int32_t decode_ber(const char *buf, size_t len)
1818 {
1819 /* decode the bytes, starting from the least significant */
1820 size_t i = len;
1821 int shift = 0;
1822 int32_t val = 0;
1823 do
1824 {
1825 val += buf[--i] << shift;
1826 shift += 7;
1827 }
1828 while (i != 0);
1829
1830 /* return the result */
1831 return val;
1832 }
1833
1834 /* ------------------------------------------------------------------------ */
1835 /*
1836 * Pack an item or iterated list of items
1837 */
1838 void CVmPack::pack_item(VMG_ CVmPackGroup *group, CVmPackArgs *args,
1839 CVmPackType *t, CVmPackType *prefix_count)
1840 {
1841 /*
1842 * Retrieve the current argument, to test if it's a list. Note that if
1843 * we're out of arguments, it's no problem - get() will fill in val
1844 * with nil, and the is_listlike test on nil will return false.
1845 */
1846 vm_val_t val;
1847 args->get(&val);
1848
1849 /*
1850 * Note if we have an iterated repeat count. The repeat count is the
1851 * number of times to repeat the field type with subsequent arguments,
1852 * except for the string types and xX@.
1853 */
1854 int repeatable = is_repeatable(t->type_code);
1855
1856 /* if we have a count prefix, the item count is implicitly '*' */
1857 int count = t->count;
1858 if (prefix_count != 0)
1859 count = ITER_STAR;
1860
1861 /* check to see if we have a list-like argument */
1862 if (val.is_listlike(vmg0_))
1863 {
1864 /* it's a list - set up a list argument reader */
1865 ListArgs lst(vmg_ &val);
1866
1867 /* if we have a type that consumes arguments, consume the list */
1868 if (type_consumes_arg((char)t->type_code))
1869 args->next();
1870
1871 /* if there's a prefix count, pack it based on the list length */
1872 if (prefix_count != 0)
1873 {
1874 /* pack the length of the list as the count */
1875 SingleArg cnt(lst.len);
1876 pack_one_item(vmg_ group, &cnt, prefix_count, 0);
1877 }
1878
1879 /*
1880 * Figure the number of list items to pack. If we have an explicit
1881 * numeric repeat count, loop exactly that many times. If we no
1882 * repeat count, loop once. If we have '*' as the repeat count, or
1883 * a prefix count, loop over the list length.
1884 */
1885 int iters = (count == ITER_STAR ? lst.len :
1886 count < 1 ? 1 :
1887 count);
1888
1889 /* if this is an up-to count, limit it to the list length */
1890 if (t->up_to_count && iters > lst.len)
1891 iters = lst.len;
1892
1893 /* iterate over the list */
1894 for (int i = 0 ; i < iters ; ++i)
1895 pack_one_item(vmg_ group, &lst, t, 0);
1896 }
1897 else if (repeatable && (count == ITER_STAR || count > 1))
1898 {
1899 /*
1900 * We have '*' as the repeat count, which means that we repeat this
1901 * item for the remaining arguments at this level.
1902 */
1903 if (prefix_count != 0)
1904 {
1905 /* write the number of remaining arguments */
1906 SingleArg cntarg(args->nrem());
1907 pack_one_item(vmg_ group, &cntarg, prefix_count, 0);
1908 }
1909
1910 /* pack items until we're out of arguments or reach the repeat count */
1911 int n;
1912 for (n = 0 ; count == ITER_STAR ? args->more() : n < count ; ++n)
1913 {
1914 /* if this is an up-to count and we're out of arguments, stop */
1915 if (t->up_to_count && !args->more())
1916 break;
1917
1918 /* pack the item */
1919 pack_one_item(vmg_ group, args, t, 0);
1920 }
1921
1922 /* if it's an up-to count, consume the rest of the arguments */
1923 if (t->up_to_count)
1924 for ( ; args->more() ; args->next()) ;
1925 }
1926 else
1927 {
1928 /*
1929 * Either there's no prefix count at all, in which case we're
1930 * writing a singleton; or there's a prefix count for a string
1931 * value, in which case the prefix is the string length. In either
1932 * case, we have a single item to write rather than an iterated
1933 * list.
1934 */
1935 pack_one_item(vmg_ group, args, t, prefix_count);
1936 }
1937 }
1938
1939 /*
1940 * Figure the padding for alignment to a given size boundary
1941 */
1942 static int alignment_padding(const CVmPackType *t, const CVmPackGroup *group,
1943 int dir)
1944 {
1945 /* get the alignment size; if one or less, add no padding */
1946 int c = t->count;
1947 if (c <= 1)
1948 return 0;
1949
1950 /* get the current offset from the root starting position */
1951 long ofs = group->ds->get_pos() - group->root_stream_ofs();
1952
1953 /* if we're already at a multiple of the size, no padding is needed */
1954 if (ofs % c == 0)
1955 return 0;
1956
1957 /* figure padding in the desired direction */
1958 if (dir > 0)
1959 {
1960 /* forward padding - pad to the next multiple of 'c' */
1961 return c - (int)(ofs % c);
1962 }
1963 else
1964 {
1965 /* reverse padding - pad to the previous multiple of 'c' */
1966 return -(int)(ofs % c);
1967 }
1968 }
1969
1970 /*
1971 * Pack a single item
1972 */
1973 void CVmPack::pack_one_item(VMG_ CVmPackGroup *group, CVmPackArgs *args,
1974 CVmPackType *t, CVmPackType *prefix_count)
1975 {
1976 vm_val_t val, cval;
1977 int len;
1978 char buf[256];
1979 CVmDataSource *dst = group->ds;
1980
1981 /* check for non-argument codes */
1982 switch (t->type_code)
1983 {
1984 case 'x':
1985 /* Nul byte(s) */
1986 if (t->bang)
1987 write_padding(dst, '\0', alignment_padding(t, group, 1));
1988 else
1989 write_padding(dst, '\0', t->get_count());
1990 return;
1991
1992 case 'X':
1993 /* back up by 'count' bytes */
1994 if (t->bang)
1995 dst->seek(alignment_padding(t, group, -1), OSFSK_CUR);
1996 else
1997 dst->seek(-t->get_count(), OSFSK_CUR);
1998 return;
1999
2000 case '"':
2001 /* literal bytes */
2002 len = 0;
2003 for (CVmPackPos p(&t->lit) ; p.len != 0 ; p.inc())
2004 {
2005 /* get the next character */
2006 wchar_t ch = p.getch_raw();
2007
2008 /* if it's a quote, it must be stuttered, so skip one more */
2009 if (ch == '"')
2010 p.inc();
2011
2012 /* if it's outside the 0-255 range, it's an error */
2013 if (ch > 255)
2014 err_throw(VMERR_NUM_OVERFLOW);
2015
2016 /* write the charater */
2017 buf[len++] = (char)ch;
2018
2019 /* flush the buffer if it's full */
2020 if (len == sizeof(buf))
2021 {
2022 dst->write(buf, len);
2023 len = 0;
2024 }
2025 }
2026
2027 /* write the final buffer */
2028 if (len != 0)
2029 dst->write(buf, len);
2030
2031 /* done */
2032 return;
2033
2034 case '{':
2035 /* in-line hex bytes */
2036 len = 0;
2037 for (CVmPackPos p(&t->lit) ; p.more() ; )
2038 {
2039 /* get the next two hex digits */
2040 int b = (value_of_xdigit(p.nextch()) << 4);
2041 b += value_of_xdigit(p.nextch());
2042
2043 /* add it to the buffer */
2044 buf[len++] = (char)b;
2045
2046 /* flush the buffer if it's full */
2047 if (len == sizeof(buf))
2048 {
2049 dst->write(buf, len);
2050 len = 0;
2051 }
2052 }
2053
2054 /* write the final buffer */
2055 if (len != 0)
2056 dst->write(buf, len);
2057
2058 /* done */
2059 return;
2060
2061 case '@':
2062 /* Nul-fill to the absolute position; @? does nothing on packing */
2063 if (!t->qu)
2064 {
2065 /*
2066 * Figure the seek position as an offset from the current file
2067 * position. If there's a !, it's relative to the start of the
2068 * whole string, otherwise relative to the start of the current
2069 * group.
2070 */
2071 long l = (t->bang ? group->root_stream_ofs() : group->stream_ofs)
2072 + t->get_count() - dst->get_pos();
2073
2074 /* if positive, write Nul bytes; if negative, back up */
2075 if (l > 0)
2076 write_padding(dst, '\0', l);
2077 else if (l < 0)
2078 dst->seek(l, OSFSK_CUR);
2079 }
2080 return;
2081 }
2082
2083 /* note if it's upper or lower case */
2084 int lc = is_lower(t->type_code);
2085
2086 /* retrieve and consume the next argument */
2087 args->get(&val);
2088 args->next();
2089
2090 /* check for a character string conversion */
2091 CharConv *cvtchar = CharConv::conv_for_type(t);
2092 if (cvtchar != 0)
2093 {
2094 /* create the field data source based on the object type */
2095 CharFieldSource *src = CharFieldSource::create(vmg_ &val, &cval);
2096
2097 err_try
2098 {
2099 /* push any new value created by the cast, for gc protection */
2100 G_stk->push(&cval);
2101
2102 /* if there's an prefix count, write the string length */
2103 if (prefix_count != 0)
2104 {
2105 /* write the string length */
2106 SingleArg alen(src->arraylen(t));
2107 pack_one_item(vmg_ group, &alen, prefix_count, 0);
2108 }
2109
2110 /*
2111 * Figure the byte length of the write. The mapping between
2112 * the repeat count and the byte length varies by format, so
2113 * ask the format handler. If we have a prefix count or a '*'
2114 * repeat count, though, we simply write the exact length of
2115 * the string.
2116 */
2117 int nbytes;
2118 if (prefix_count != 0
2119 || t->count == ITER_STAR
2120 || (t->count == ITER_NONE && t->null_term))
2121 {
2122 /* prefix count, *, or null-term - use the actual length */
2123 nbytes = ITER_STAR;
2124 }
2125 else
2126 {
2127 /* specific count - translate characters to bytes */
2128 nbytes = cvtchar->get_byte_count(t);
2129 }
2130
2131 /* convert the string to the specified representation */
2132 long tot;
2133 char *p;
2134 int srcidx;
2135 for (tot = 0, srcidx = 0, p = buf ; src->more() ; )
2136 {
2137 /*
2138 * If there's not room for another character in the buffer,
2139 * flush the buffer. To make things easy, we assume the
2140 * conversion will require the most space of any of our
2141 * conversions, which is three bytes for some utf8
2142 * characters.
2143 */
2144 if (p - buf > sizeof(buf) - 3)
2145 {
2146 /* flush the buffer */
2147 if (dst->write(buf, p - buf))
2148 err_throw(VMERR_WRITE_FILE);
2149
2150 /* start over at the beginning of the buffer */
2151 p = buf;
2152 }
2153
2154 /* add the next character */
2155 char *prvp = p;
2156 cvtchar->putch(p, src->getch(), srcidx++, t->pct);
2157
2158 /* add this to the running total */
2159 tot += p - prvp;
2160
2161 /*
2162 * If this would push us over the repeat count, back out
2163 * this character.
2164 */
2165 if (nbytes > 0 && tot > nbytes)
2166 {
2167 /* back it out and stop adding */
2168 tot -= p - prvp;
2169 p = prvp;
2170 break;
2171 }
2172 }
2173
2174 /* close out the buffer */
2175 cvtchar->putch_end(p, srcidx);
2176
2177 /* if there's anything in the buffer, flush it */
2178 if (p > buf && dst->write(buf, p - buf))
2179 err_throw(VMERR_WRITE_FILE);
2180
2181 /*
2182 * If we have a repeat count, and we didn't reach the maximum
2183 * length, add the padding. Skip this if it's an up-to count,
2184 * since an up-to count only packs up to the actual length if
2185 * that's less than the count limit.
2186 */
2187 if (tot < nbytes && !t->up_to_count)
2188 {
2189 /*
2190 * figure the padding - use space padding for A, U, and W,
2191 * and nul padding for everything else
2192 */
2193 char pad = get_padding_char(t->type_code);
2194
2195 /* write it out */
2196 cvtchar->pad(dst, pad, tot, t);
2197 }
2198
2199 /* if it's null-terminated, write the null character */
2200 if (t->null_term)
2201 cvtchar->null_term(dst);
2202
2203 /* discard the gc protection */
2204 G_stk->discard();
2205 }
2206 err_finally
2207 {
2208 /* delete the field data source object */
2209 delete src;
2210 }
2211 err_end;
2212
2213 /* done */
2214 return;
2215 }
2216
2217 /* it's not a character string type; check other types */
2218 switch (t->type_code)
2219 {
2220 case 'c':
2221 /* signed byte */
2222 buf[0] = (char)intval(vmg_ &val, -128, 127, t->pct, 0xff);
2223 write_num_bytes(dst, buf, t, 1);
2224 break;
2225
2226 case 'C':
2227 /* unsigned byte */
2228 buf[0] = (char)intval(vmg_ &val, 0, 255, t->pct, 0xff);
2229 write_num_bytes(dst, buf, t, 1);
2230 break;
2231
2232 case 's':
2233 /* signed short (16 bits) */
2234 oswp2s(buf, intval(vmg_ &val, -32768, 32767, t->pct, 0xffff));
2235 write_num_bytes(dst, buf, t, 2);
2236 break;
2237
2238 case 'S':
2239 /* unsigned short (16 bits) */
2240 oswp2(buf, intval(vmg_ &val, 0, 65535, t->pct, 0xffff));
2241 write_num_bytes(dst, buf, t, 2);
2242 break;
2243
2244 case 'l':
2245 /* signed long (32 bits) */
2246 oswp4s(buf, intval(vmg_ &val, -2147483647-1, 2147483647,
2247 t->pct, 0xffffffff));
2248 write_num_bytes(dst, buf, t, 4);
2249 break;
2250
2251 case 'L':
2252 /*
2253 * Unsigned long (32 bits). TADS doesn't have unsigned longs as a
2254 * VM datatype, but a BigNumber can hold a value above LONG_MAX.
2255 * So if we have a BigNumber or a string, get the BigNumber value
2256 * and see if it fits in a 32-bit unsigned long. Otherwise, it has
2257 * to be a positive integer.
2258 */
2259 if ((val.typ == VM_OBJ
2260 && CVmObjBigNum::is_bignum_obj(vmg_ val.val.obj))
2261 || val.get_as_string(vmg0_) != 0)
2262 {
2263 /* cast it to a BigNumber */
2264 CVmObjBigNum::cast_to_bignum(vmg_ &cval, &val);
2265
2266 /* convert to ulong */
2267 int ov;
2268 unsigned long l = ((CVmObjBigNum *)vm_objp(vmg_ cval.val.obj))
2269 ->convert_to_uint(ov);
2270
2271 /* make sure it fits in a 32-bit long (unless '%' is set) */
2272 if (ov || l > 4294967295U)
2273 {
2274 if (t->pct)
2275 l &= 0xffffffff;
2276 else
2277 err_throw(VMERR_NUM_OVERFLOW);
2278 }
2279
2280 /* save it */
2281 oswp4(buf, l);
2282 write_num_bytes(dst, buf, t, 4);
2283 }
2284 else
2285 {
2286 /*
2287 * It's not a BigNumber, so just cast to int. Since TADS
2288 * doesn't have an unsigned 32-bit type, we have to limit the
2289 * range to positive integers.
2290 */
2291 oswp4(buf, intval(vmg_ &val, 0, 2147483647, t->pct, 0xffffffff));
2292 write_num_bytes(dst, buf, t, 4);
2293 }
2294 break;
2295
2296 case 'q':
2297 case 'Q':
2298 /*
2299 * Long-long (64-bit) types. We can source these values from
2300 * integers or BigNumber values.
2301 */
2302 if (val.typ == VM_INT)
2303 {
2304 /*
2305 * Integer value. Write the low-order 32 bits, and sign-extend
2306 * into the high-order 32 bits. The sign extension is all zero
2307 * bits for a positive or zero value, and all 1 bits (0xff
2308 * bytes) for a negative value. An unsigned value is
2309 * inherently non-negative, so the 1-bit extension applies only
2310 * to negative signed values.
2311 */
2312 unsigned char sign_ext = 0;
2313 if (lc)
2314 {
2315 /* signed - write the low-order 32 bits, little-endian */
2316 oswp4s(buf, val.val.intval);
2317
2318 /* if it's negative, sign-extend with 0xff bytes */
2319 if (val.val.intval < 0)
2320 sign_ext = 0xff;
2321 }
2322 else
2323 {
2324 /* unsigned - make sure it's not negative */
2325 if (val.val.intval < 0 && !t->pct)
2326 err_throw(VMERR_NUM_OVERFLOW);
2327
2328 /* write the low-order 32-bits, little-endian, unsigned */
2329 oswp4(buf, val.val.intval);
2330 }
2331
2332 /* sign-extend or zero-extend into the high-order 32 bits */
2333 memset(buf + 4, sign_ext, 4);
2334 }
2335 else if (val.typ == VM_NIL)
2336 {
2337 /* nil - write 0 */
2338 memset(buf, 0, 8);
2339 }
2340 else
2341 {
2342 /* it's not an int, so cast it to BigNumber */
2343 CVmObjBigNum::cast_to_bignum(vmg_ &cval, &val);
2344
2345 /* write the 8-byte portable little-endian value */
2346 int ov;
2347 if (lc)
2348 ((CVmObjBigNum * )vm_objp(vmg_ cval.val.obj))->wp8s(buf, ov);
2349 else
2350 ((CVmObjBigNum * )vm_objp(vmg_ cval.val.obj))->wp8(buf, ov);
2351
2352 /* check for overflow */
2353 if (ov && !t->pct)
2354 err_throw(VMERR_NUM_OVERFLOW);
2355 }
2356
2357 /* write the buffer */
2358 write_num_bytes(dst, buf, t, 8);
2359 break;
2360
2361 case 'k':
2362 {
2363 /* BER compressed integer */
2364 size_t blen = 0;
2365 if (val.typ == VM_INT)
2366 {
2367 /* make sure it's positive, or that 'pct' is set */
2368 long l = val.val.intval;
2369 if (l < 0)
2370 {
2371 /*
2372 * if % is set, use the absolute value; otherwise it's
2373 * an error
2374 */
2375 if (t->pct)
2376 l = -l;
2377 else
2378 err_throw(VMERR_NUM_OVERFLOW);
2379 }
2380
2381 /* encode the value */
2382 encode_ber(buf, blen, l);
2383 }
2384 else if (val.typ == VM_NIL)
2385 {
2386 /* encode 0 */
2387 buf[blen++] = 0;
2388 }
2389 else
2390 {
2391 /* it's not an int, so cast it to BigNumber */
2392 CVmObjBigNum::cast_to_bignum(vmg_ &cval, &val);
2393
2394 /* encode the BigNumber in BER format */
2395 int ov;
2396 ((CVmObjBigNum *)vm_objp(vmg_ cval.val.obj))->encode_ber(
2397 buf, sizeof(buf), blen, ov);
2398
2399 /* check for overflow */
2400 if (ov && !t->pct)
2401 err_throw(VMERR_NUM_OVERFLOW);
2402 }
2403
2404 /* write the buffer */
2405 if (dst->write(buf, blen))
2406 err_throw(VMERR_WRITE_FILE);
2407 }
2408 break;
2409
2410 case 'f':
2411 len = 4;
2412 goto float_fmt;
2413
2414 case 'd':
2415 len = 8;
2416
2417 float_fmt:
2418 /* float/double - cast to BigNumber */
2419 if (val.typ == VM_NIL)
2420 {
2421 /* nil - return as zero, which is all 0 bits in all formats */
2422 memset(buf, 0, len);
2423 }
2424 else
2425 {
2426 /* cast the value to BigNumber */
2427 CVmObjBigNum::cast_to_bignum(vmg_ &cval, &val);
2428 G_stk->push(&cval);
2429
2430 /* convert to the 32-bit or 64-bit IEEE 754-2008 format */
2431 int ov;
2432 ((CVmObjBigNum *)vm_objp(vmg_ cval.val.obj))
2433 ->convert_to_ieee754(vmg_ buf, len*8, ov);
2434
2435 /* check for overflow */
2436 if (ov && !t->pct)
2437 err_throw(VMERR_NUM_OVERFLOW);
2438
2439 /* discard the gc protection */
2440 G_stk->discard();
2441 }
2442
2443 /* write out the result */
2444 write_num_bytes(dst, buf, t, len);
2445 break;
2446 }
2447 }
2448
2449 /* ------------------------------------------------------------------------ */
2450 /*
2451 * Unpack data from the given stream into a list
2452 */
2453 void CVmPack::unpack(VMG_ vm_val_t *retval, const char *fmt, size_t fmtlen,
2454 CVmDataSource *src)
2455 {
2456 /*
2457 * Set up a list for the return value. We don't know how many elements
2458 * we'll need, so allocate an initial chunk now and expand later as
2459 * needed. (We can't necessarily know the return size even by
2460 * pre-parsing the format string, since it could have variable-size
2461 * items with array counts.)
2462 */
2463 retval->set_obj(CVmObjList::create(vmg_ FALSE, 10));
2464 CVmObjList *retlst = (CVmObjList *)vm_objp(vmg_ retval->val.obj);
2465
2466 /*
2467 * since we're going to build the list iteratively, clear it out, so
2468 * that it doesn't contain any uninitialized elements that the garbage
2469 * collector might encounter
2470 */
2471 retlst->cons_clear();
2472
2473 /* save it on the stack for gc protection */
2474 G_stk->push(retval);
2475
2476 /* we don't have any elements in our list yet */
2477 int retcnt = 0;
2478
2479 /* unpack the root group */
2480 CVmPackPos p(fmt, fmtlen);
2481 CVmPackGroup root(&p, src);
2482 unpack_group(vmg_ &p, retlst, &retcnt, &root, FALSE);
2483
2484 /* make sure we made it all the way through the format string */
2485 if (p.more())
2486 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p.index());
2487
2488 /* set the return list's final length */
2489 retlst->cons_set_len(retcnt);
2490
2491 /* discard the gc protection */
2492 G_stk->discard();
2493 }
2494
2495 /*
2496 * Unpack a group
2497 */
2498 void CVmPack::unpack_group(VMG_ CVmPackPos *p,
2499 CVmObjList *retlst_par, int *retcnt_par,
2500 CVmPackGroup *group, int list_per_iter)
2501 {
2502 /* get the data source */
2503 CVmDataSource *src = group->ds;
2504
2505 /*
2506 * If the group has an "up to" count (e.g., "30*"), check to see if
2507 * we're already at EOF, and if so don't unpack anything - an iteration
2508 * count of zero is valid for an up-to count.
2509 */
2510 if ((group->num_iters == ITER_STAR || group->up_to_iters)
2511 && src->get_pos() >= src->get_size())
2512 {
2513 /* skip the group in the source */
2514 p->set(&group->start);
2515 skip_group(p, group->close_paren);
2516
2517 /* we're done */
2518 return;
2519 }
2520
2521 /* assume we'll unpack directly into the parent list */
2522 CVmObjList *retlst = retlst_par;
2523 int *retcnt = retcnt_par;
2524
2525 /*
2526 * if we're unpacking into a per-instance sublist, create the sublist
2527 * for the first iteration, and set this as the output list instead of
2528 * unpacking directly into the parent list
2529 */
2530 int grpcnt = 0;
2531 if (list_per_iter)
2532 {
2533 retlst = create_group_sublist(vmg_ retlst_par, retcnt_par);
2534 retcnt = &grpcnt;
2535 }
2536
2537 /* run through the format list */
2538 while (p->more())
2539 {
2540 /* check for group entry/exit and repeat counts */
2541 wchar_t c = p->getch();
2542 if (c == '(' || c == '[')
2543 {
2544 /* start of a group - unpack the sub-group */
2545 unpack_subgroup(vmg_ p, retlst, *retcnt, group, 0);
2546 }
2547 else if (c == group->close_paren)
2548 {
2549 /* end of group - count the completed iteration */
2550 group->cur_iter++;
2551
2552 /*
2553 * if we're unpacking into a per-iteration sublist, note the
2554 * final group count in the sublist
2555 */
2556 if (list_per_iter)
2557 retlst->cons_set_len(*retcnt);
2558
2559 /*
2560 * We're done with the group if (a) we have a '*' iteration
2561 * count, and we're at end of file, or (b) we've reached the
2562 * desired iteration count. If done, simply return to the
2563 * enclosing group.
2564 */
2565 if (group->num_iters == ITER_STAR
2566 ? src->get_pos() >= src->get_size()
2567 : group->cur_iter > group->num_iters)
2568 return;
2569
2570 /*
2571 * if we have an 'up to' iteration count, stop if we're at EOF
2572 * even if we haven't exhausted the numeric iteration count
2573 */
2574 if (group->up_to_iters && src->get_pos() >= src->get_size())
2575 return;
2576
2577 /* return to the start of the group template for the next round */
2578 p->set(&group->start);
2579 group->stream_ofs = group->ds->get_pos();
2580
2581 /*
2582 * If we're unpacking into a sublist per iteration, create the
2583 * new sublist for the new iteration.
2584 */
2585 if (list_per_iter)
2586 {
2587 retlst = create_group_sublist(vmg_ retlst_par, retcnt_par);
2588 grpcnt = 0;
2589 }
2590 }
2591 else if (c == '/')
2592 {
2593 /*
2594 * Repeat count prefix. Remove the preceding return list
2595 * element and interpret it as an integer. Make sure there
2596 * actually is an item in the list - it's an error if not.
2597 */
2598 if (retcnt == 0)
2599 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index());
2600
2601 /* remove the item and cast it to integer */
2602 vm_val_t cntval;
2603 retlst->get_element(--(*retcnt), &cntval);
2604 int cnt = (int)cntval.cast_to_int(vmg0_);
2605
2606 /* skip the '/' and check what follows */
2607 p->inc();
2608 if ((c = p->getch()) == '(' || c == '[')
2609 {
2610 /* it's a group - unpack the group with the count */
2611 unpack_subgroup(vmg_ p, retlst, *retcnt, group, &cnt);
2612 }
2613 else
2614 {
2615 /* it's a single item - unpack the repeated items */
2616 unpack_iter_item(vmg_ p, retlst, *retcnt, group, &cnt);
2617 }
2618 }
2619 else
2620 {
2621 /* it's a regular item, possibly iterated - unpack it */
2622 unpack_iter_item(vmg_ p, retlst, *retcnt, group, 0);
2623 }
2624 }
2625 }
2626
2627 /*
2628 * Unpack a subgroup
2629 */
2630 void CVmPack::unpack_subgroup(VMG_ CVmPackPos *p,
2631 CVmObjList *retlst, int &retcnt,
2632 CVmPackGroup *group, const int *prefix_count)
2633 {
2634 /* group - parse the group modifiers */
2635 CVmPackType gt(group);
2636 parse_group_mods(p, &gt);
2637
2638 /* note the open paren type */
2639 wchar_t paren = p->getch();
2640
2641 /* skip the paren and set up the child group */
2642 p->inc();
2643 CVmPackGroup child(group, paren, p, &gt);
2644
2645 /* if there's a prefix count, it overrides the suffix count */
2646 if (prefix_count != 0)
2647 child.num_iters = *prefix_count;
2648
2649 /*
2650 * If the group started with '[', it means that it's to be unpacked
2651 * into a list. Otherwise, it's unpacked directly into the enclosing
2652 * list. Create a new list if necessary.
2653 */
2654 if (paren == '[')
2655 {
2656 /*
2657 * if there's a '!' modifier, we unpack each iteration into a
2658 * separate list; otherwise we unpack the whole group into a single
2659 * list
2660 */
2661 if (gt.bang)
2662 {
2663 /*
2664 * unpack into individual per-iteration sublists, each of which
2665 * goes into the main list
2666 */
2667 unpack_group(vmg_ p, retlst, &retcnt, &child, TRUE);
2668 }
2669 else
2670 {
2671 /* create the result list for the whole group */
2672 CVmObjList *grplst = create_group_sublist(vmg_ retlst, &retcnt);
2673 int grpcnt = 0;
2674
2675 /* unpack into the sublist */
2676 unpack_group(vmg_ p, grplst, &grpcnt, &child, FALSE);
2677
2678 /* set the final number of elements in the list */
2679 grplst->cons_set_len(grpcnt);
2680 }
2681 }
2682 else
2683 {
2684 /* no sublist - unpack into the main list */
2685 unpack_group(vmg_ p, retlst, &retcnt, &child, FALSE);
2686 }
2687
2688 /* make sure we stopped at the close paren */
2689 if (p->nextch() != child.close_paren)
2690 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index());
2691
2692 /* skip any modifiers for the group */
2693 parse_mods(p, &gt);
2694 }
2695
2696 /*
2697 * Create a sublist for unpacking a "[ ]" group
2698 */
2699 CVmObjList *CVmPack::create_group_sublist(
2700 VMG_ CVmObjList *parent_list, int *parent_cnt)
2701 {
2702 /* create the new sublist */
2703 vm_val_t ele;
2704 ele.set_obj(CVmObjList::create(vmg_ FALSE, 10));
2705 CVmObjList *sublst = (CVmObjList *)vm_objp(vmg_ ele.val.obj);
2706
2707 /* clear it, since we'll be filling it in iteratively */
2708 sublst->cons_clear();
2709
2710 /*
2711 * Add it to the parent list. The parent list is on the stack (or in a
2712 * list that's on the stack, or in a list that's in a list on the
2713 * stack, etc) - that will protect the new list from premature garbage
2714 * collection.
2715 */
2716 parent_list->cons_ensure_space(vmg_ *parent_cnt, 10);
2717 parent_list->cons_set_element((*parent_cnt)++, &ele);
2718
2719 /* return the sublist */
2720 return sublst;
2721 }
2722
2723
2724 /* ------------------------------------------------------------------------ */
2725 /*
2726 * Unpack an iterated item
2727 */
2728 void CVmPack::unpack_iter_item(VMG_ CVmPackPos *p,
2729 CVmObjList *retlst, int &retcnt,
2730 CVmPackGroup *group, const int *prefix_count)
2731 {
2732 int len;
2733
2734 /* parse the template item */
2735 CVmPackType t;
2736 parse_type(p, &t, group);
2737
2738 /* get the data source */
2739 CVmDataSource *src = group->ds;
2740
2741 /* check for non-value types and string types */
2742 int is_string_type = FALSE;
2743 switch (t.type_code)
2744 {
2745 case 'x':
2746 /* Nul bytes: on input, just skip bytes */
2747 if (t.bang)
2748 src->seek(alignment_padding(&t, group, 1), OSFSK_CUR);
2749 else
2750 src->seek(t.get_count(), OSFSK_CUR);
2751 return;
2752
2753 case 'X':
2754 /* back up by 'count' bytes */
2755 if (t.bang)
2756 src->seek(alignment_padding(&t, group, -1), OSFSK_CUR);
2757 else
2758 src->seek(-t.get_count(), OSFSK_CUR);
2759 return;
2760
2761 case '"':
2762 /* count the characters in the string */
2763 len = 0;
2764 for (CVmPackPos p(&t.lit) ; p.len != 0 ; p.inc(), ++len)
2765 {
2766 /* if this is a quote, it must be stuttered, so skip it */
2767 if (p.getch_raw() == '"')
2768 p.inc();
2769 }
2770
2771 /* skip the bytes, and we're done */
2772 src->seek(len * t.get_count(), OSFSK_CUR);
2773 return;
2774
2775 case '{':
2776 /* count the hex digit pairs */
2777 len = 0;
2778 for (CVmPackPos p(&t.lit) ; p.more() ; ++len, p.inc(), p.inc()) ;
2779
2780 /* skip the bytes, and we're done */
2781 src->seek(len * t.get_count(), OSFSK_CUR);
2782 return;
2783
2784 case '@':
2785 /* seek to position or retrieve current position */
2786 if (t.qu)
2787 {
2788 /* @? retrieves the current position as an output value */
2789 unpack_into_list(vmg_ retlst, retcnt, src, &t, group);
2790 }
2791 else
2792 {
2793 /*
2794 * Absolute positioning: seek to the starting position plus the
2795 * specified offset. The starting position is the current
2796 * group's starting position, or the whole string's start if
2797 * the ! qualifier is present.
2798 */
2799 src->seek((t.bang ? group->root_stream_ofs() : group->stream_ofs)
2800 + t.get_count() - src->get_pos(),
2801 OSFSK_CUR);
2802 }
2803 return;
2804
2805 case 'a':
2806 case 'A':
2807 case 'b':
2808 case 'u':
2809 case 'U':
2810 case 'w':
2811 case 'W':
2812 case 'h':
2813 case 'H':
2814 /* make a note that this is a string type */
2815 is_string_type = TRUE;
2816 break;
2817 }
2818
2819 /*
2820 * We have a regular unpacking type (not one of the special positioning
2821 * codes). If there's a prefix count, it overrides any count specified
2822 * in the type.
2823 */
2824 if (prefix_count != 0)
2825 t.count = *prefix_count;
2826
2827 /*
2828 * If it's a string type, the repeat count specifies the length of the
2829 * string in the file (in bytes, characters, nibbles, or other units
2830 * that vary by template type). Otherwise, the repeat count is the
2831 * number of copies of the item to unpack.
2832 */
2833 if (is_string_type)
2834 {
2835 /*
2836 * It's a string type. The count doesn't specify the number of
2837 * strings to write, but rather specifies the number of bytes to
2838 * read into one string.
2839 */
2840 unpack_into_list(vmg_ retlst, retcnt, src, &t, group);
2841 }
2842 else if (t.count == ITER_STAR)
2843 {
2844 /* unpack this item repeatedly until we run out of source */
2845 long src_size = src->get_size();
2846 while (src->get_pos() < src_size)
2847 unpack_into_list(vmg_ retlst, retcnt, src, &t, group);
2848 }
2849 else if (t.up_to_count)
2850 {
2851 /*
2852 * unpack this item the number of times given by the repeat count,
2853 * but stop if we reach EOF first
2854 */
2855 long src_size = src->get_size();
2856 for (int i = 0 ; i < t.get_count() && src->get_pos() < src_size ; ++i)
2857 unpack_into_list(vmg_ retlst, retcnt, src, &t, group);
2858 }
2859 else
2860 {
2861 /* unpack this item the number of times given by the repeat count */
2862 for (int i = 0 ; i < t.get_count() ; ++i)
2863 unpack_into_list(vmg_ retlst, retcnt, src, &t, group);
2864 }
2865 }
2866
2867 /*
2868 * Unpack an item and add it to the list
2869 */
2870 void CVmPack::unpack_into_list(VMG_ CVmObjList *retlst, int &retcnt,
2871 CVmDataSource *src, const CVmPackType *t,
2872 const CVmPackGroup *group)
2873 {
2874 /* unpack the item */
2875 vm_val_t ele;
2876 unpack_item(vmg_ &ele, src, t, group);
2877
2878 /* add it to the list */
2879 retlst->cons_ensure_space(vmg_ retcnt, 10);
2880 retlst->cons_set_element(retcnt++, &ele);
2881 }
2882
2883 /* ------------------------------------------------------------------------ */
2884 /*
2885 * Read a numeric (int/float/double) buffer, normalizing into little-endian
2886 * order.
2887 */
2888 static void read_num_bytes(char *buf, CVmDataSource *src, size_t len,
2889 const CVmPackType *t)
2890 {
2891 /* read the bytes */
2892 if (src->read(buf, len))
2893 err_throw(VMERR_READ_FILE);
2894
2895 /*
2896 * if the source is in big-endian order, swap the bytes to get our
2897 * standard little-endian order
2898 */
2899 if (len > 1 && t->big_endian)
2900 reverse_bytes(buf, len);
2901 }
2902
2903
2904 /* ------------------------------------------------------------------------ */
2905 /*
2906 * Unpack one item
2907 */
2908 void CVmPack::unpack_item(VMG_ vm_val_t *val,
2909 CVmDataSource *src, const CVmPackType *t,
2910 const CVmPackGroup *group)
2911 {
2912 /* check for a character conversion */
2913 CharConv *cvtchar = CharConv::conv_for_type(t);
2914 if (cvtchar != 0 && t->null_term && t->count <= 0)
2915 {
2916 /*
2917 * It's a null-terminated string type without a fixed field width.
2918 * Use the special unpacking method for this type.
2919 */
2920 cvtchar->unpackz(vmg_ val, src);
2921
2922 /* done */
2923 return;
2924 }
2925 if (cvtchar != 0)
2926 {
2927 /* character string - the repeat count is the length */
2928 int count = t->get_count();
2929
2930 /* if the count is in bytes, convert it */
2931 if (t->count_in_bytes)
2932 count = cvtchar->bytes_to_count(count);
2933
2934 /* if the character count is zero, return an empty string */
2935 if (count == 0)
2936 {
2937 val->set_obj(CVmObjString::create(vmg_ FALSE, 0));
2938 return;
2939 }
2940
2941 /* if it's '*', we read the rest of the data source */
2942 if (t->count == ITER_STAR || t->up_to_count)
2943 {
2944 /*
2945 * get the remaining length, and convert it to a repeat count
2946 * appropriate to the string conversion type
2947 */
2948 long l = cvtchar->bytes_to_count(src->get_size() - src->get_pos());
2949
2950 /* use 'l' as a maximum for 'n*', or the actual count for '*' */
2951 if (t->count == ITER_STAR)
2952 {
2953 /*
2954 * '*' means read the whole rest of the file - that's a
2955 * long value, so cast it to int, making sure we don't
2956 * overflow
2957 */
2958 count = (int)l;
2959 if (l > INT_MAX)
2960 err_throw(VMERR_NUM_OVERFLOW);
2961 }
2962 else
2963 {
2964 /*
2965 * 'n*' means read up to n, stopping at EOF, so stop at 'l'
2966 * if it's less than the specified count
2967 */
2968 if (l < count)
2969 count = (int)l;
2970 }
2971 }
2972
2973 /* figure the padding type */
2974 char pad = get_padding_char(t->type_code);
2975
2976 /* unpack the string */
2977 cvtchar->unpack(vmg_ val, src, count, pad);
2978
2979 /* check for null termination */
2980 if (t->null_term)
2981 {
2982 /* skip the null, which is tacked on after the fixed length */
2983 cvtchar->readch(src);
2984
2985 /* terminate the string at the first null, if present */
2986 if (val->typ == VM_OBJ
2987 && CVmObjString::is_string_obj(vmg_ val->val.obj))
2988 {
2989 /* get the string */
2990 CVmObjString *str = (CVmObjString *)vm_objp(vmg_ val->val.obj);
2991
2992 /* scan for a null byte */
2993 char *nul = (char *)memchr(
2994 str->cons_get_buf(), 0, str->cons_get_len());
2995
2996 /* if we found a null byte, terminate the string there */
2997 if (nul != 0)
2998 str->cons_shrink_buffer(vmg_ nul);
2999 }
3000 }
3001
3002 /* done */
3003 return;
3004 }
3005
3006 /* it's not a string; check the numeric types */
3007 char buf[256];
3008 switch (t->type_code)
3009 {
3010 case '@':
3011 /*
3012 * @? retrieves the current position, relative to the current group
3013 * or, if ! is specified, relative to the start of the string
3014 */
3015 val->set_int(src->get_pos() -
3016 (t->bang ? group->root_stream_ofs() : group->stream_ofs));
3017 break;
3018
3019 case 'c':
3020 /* signed byte */
3021 read_num_bytes(buf, src, 1, t);
3022 val->set_int((char)buf[0]);
3023 break;
3024
3025 case 'C':
3026 /* unsigned byte */
3027 read_num_bytes(buf, src, 1, t);
3028 val->set_int((unsigned char)buf[0]);
3029 break;
3030
3031 case 's':
3032 /* signed 16-bit short */
3033 read_num_bytes(buf, src, 2, t);
3034 val->set_int(osrp2s(buf));
3035 break;
3036
3037 case 'S':
3038 /* unsigned 16-bit short */
3039 read_num_bytes(buf, src, 2, t);
3040 val->set_int((unsigned short)osrp2(buf));
3041 break;
3042
3043 case 'l':
3044 /* signed 32-bit long */
3045 read_num_bytes(buf, src, 4, t);
3046 val->set_int(osrp4s(buf));
3047 break;
3048
3049 case 'L':
3050 /*
3051 * Unsigned 32-bit long. The VM_INT type is a signed long, so we
3052 * can't use this to represent the full range of unsigned longs.
3053 * Instead, use BigNumber. Note that we could check the file value
3054 * and use VM_INT if the value actually fits (i.e., it's less than
3055 * 0x7fffffff); this might be desirable in some cases because
3056 * VM_INT is much more efficient than BigNumber. However, since
3057 * the caller is asking for type 'L', they're clearly expecting the
3058 * full unsigned 32-bit range, which might mean they plan to do
3059 * further arithmetic on the value we read, in which case they'd
3060 * expect this arithmetic to be safe on unsigned 32-bit values.
3061 * The only way we can guarantee this is to use a BigNumber for the
3062 * value regardless of whether or not it fits in a VM_INT.
3063 *
3064 * If the ~ qualifier is set, unpack into an int if the value fits
3065 * in a signed 32-bit int.
3066 */
3067 {
3068 read_num_bytes(buf, src, 4, t);
3069 unsigned long lu = osrp4(buf);
3070 if (t->tilde && lu <= 0x7fffffff)
3071 val->set_int((long)lu);
3072 else
3073 val->set_obj(CVmObjBigNum::createu(vmg_ FALSE, lu, 10));
3074 }
3075 break;
3076
3077 case 'q':
3078 /*
3079 * "Long long" 64-bit integer, signed. There's no VM_xxx primitive
3080 * type that can handle a value this large, so use BigNumber. Read
3081 * the 8-byte file value.
3082 *
3083 * If the ~ qualifier is set, and the high part of the value is all
3084 * zeros or all '1' bits, return it as an integer. Note that the
3085 * buffer is in our standard osrp8 format, which is little-endian
3086 * 2's complement, so we can inspect the byte values portably.
3087 */
3088 read_num_bytes(buf, src, 8, t);
3089 if (t->tilde
3090 && ((memcmp(buf+4, "\0\0\0\0", 4) == 0
3091 && (buf[3] & 0x80) == 0)
3092 || (memcmp(buf+4, "\377\377\377\377", 4) == 0
3093 && (buf[3] & 0x80) != 0)))
3094 val->set_int(osrp4s(buf));
3095 else
3096 val->set_obj(CVmObjBigNum::create_rp8s(vmg_ FALSE, buf));
3097 break;
3098
3099 case 'Q':
3100 /*
3101 * "Long long" 64-bit integer, unsigned. Unpack as a BigNumber,
3102 * unless the ~ qualifier is set and the value will fit in an int.
3103 */
3104 read_num_bytes(buf, src, 8, t);
3105 if (t->tilde
3106 && memcmp(buf+4, "\0\0\0\0", 4) == 0
3107 && (buf[3] & 0x80) == 0)
3108 val->set_int(osrp4s(buf));
3109 else
3110 val->set_obj(CVmObjBigNum::create_rp8(vmg_ FALSE, buf));
3111 break;
3112
3113 case 'k':
3114 /*
3115 * BER compressed unsigned integer. This is a sequence of 7-bit,
3116 * base-128 "digits", most significant digit first. The high bit
3117 * (0x80) is set on each digit except the last, which tells us
3118 * where the value ends. Read bytes one at a time until we reach
3119 * the last byte or run out of buffer space.
3120 */
3121 {
3122 size_t i;
3123 for (i = 0 ; ; )
3124 {
3125 /* if we're out of buffer space, throw an error */
3126 if (i >= sizeof(buf))
3127 err_throw(VMERR_NUM_OVERFLOW);
3128
3129 /* read the next byte */
3130 if (src->read(buf + i, 1))
3131 err_throw(VMERR_READ_FILE);
3132
3133 /* if the high bit isn't set, this is the last byte */
3134 if ((buf[i++] & 0x80) == 0)
3135 break;
3136
3137 /* keep just the low-order 7 bits of the value */
3138 buf[i-1] &= 0x7F;
3139 }
3140
3141 /*
3142 * If the value is 31 bits or fewer, return it as an integer.
3143 * Otherwise, return it as a BigNumber. 31 bits fits in 4
3144 * bytes (7*4=28) plus 3 bits of the MSB, so if we have more
3145 * than 5 bytes, or any of bits 4-8 of the MSB are set, we need
3146 * a BigNumber. (Why 31 bits and not 32? Because BER values
3147 * are unsigned, and our int32 type is signed, meaning it only
3148 * holds 31 bits for a positive value.)
3149 */
3150 if (i < 5 || (i == 5 && (buf[0] & 0xF8) == 0))
3151 {
3152 /* it fits in a 32-bit integer - decode it */
3153 val->set_int(decode_ber(buf, i));
3154 }
3155 else
3156 {
3157 /* more than 31 bits - decode into a BigNumber */
3158 val->set_obj(CVmObjBigNum::create_from_ber(vmg_ FALSE, buf, i));
3159 }
3160 }
3161 break;
3162
3163 case 'f':
3164 /*
3165 * Float - read the 32-bit float value, and return it as a
3166 * BigNumber value. Our standard IEEE 754-2008 32-bit format
3167 * represents 7.22 decimal digits of precision, so keep 8 digits.
3168 */
3169 read_num_bytes(buf, src, 4, t);
3170 val->set_obj(CVmObjBigNum::create_from_ieee754(vmg_ FALSE, buf, 32));
3171 break;
3172
3173 case 'd':
3174 /*
3175 * Double - read the 64-bit double value, and return it as a
3176 * BigNumber value. Our standard IEEE 754-2008 64-bit format
3177 * represents 15.95 decimal digits of precision.
3178 */
3179 read_num_bytes(buf, src, 8, t);
3180 val->set_obj(CVmObjBigNum::create_from_ieee754(vmg_ FALSE, buf, 64));
3181 break;
3182 }
3183 }
3184
3185 /* ------------------------------------------------------------------------ */
3186 /*
3187 * Parse a type code
3188 */
3189 void CVmPack::parse_type(CVmPackPos *p, CVmPackType *info,
3190 const CVmPackGroup *group)
3191 {
3192 /* get the type code */
3193 wchar_t c = p->nextch();
3194 if (!is_valid_type(c))
3195 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index() - 1);
3196
3197 /* set the format string index */
3198 info->fmtidx = p->index() - 1;
3199
3200 /* this is the type code - save it */
3201 info->type_code = c;
3202
3203 /*
3204 * if it's a quote, parse the characters to the next quote; if it's an
3205 * open brace, parse the hex digits to the close brace
3206 */
3207 if (c == '"')
3208 {
3209 /* note the start of the literal section */
3210 info->lit.set(p);
3211
3212 /* scan for the closing quote */
3213 for ( ; ; p->inc())
3214 {
3215 /* if at end of string, it's an error */
3216 if (!p->more())
3217 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index());
3218
3219 /* check for the close quote */
3220 if (p->getch() == '"')
3221 {
3222 /* this might be it - note the length if so */
3223 size_t len = info->lit.len - p->len;
3224
3225 /* skip it */
3226 p->inc();
3227
3228 /* if it's not a stuttered quote, it's really the end */
3229 if (p->getch() != '"')
3230 {
3231 info->lit.len = len;
3232 break;
3233 }
3234 }
3235 }
3236 }
3237 else if (c == '{')
3238 {
3239 /* note the start of the literal section */
3240 info->lit.set(p);
3241
3242 /* scan for the closing brace - only hex digits are allowed */
3243 for ( ; ; p->inc())
3244 {
3245 /* if at end of string, it's an error */
3246 if (!p->more())
3247 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index());
3248
3249 /* make sure it's a hex digit or close brace */
3250 if (p->getch() == '}')
3251 {
3252 /* it's the close brace - note it, skip it, and we're done */
3253 info->lit.len -= p->len;
3254 p->inc();
3255 break;
3256 }
3257 else if (!is_xdigit(p->getch()))
3258 err_throw_a(VMERR_PACK_PARSE, ERR_TYPE_INT, p->index());
3259 }
3260 }
3261
3262 /* set the default modifiers */
3263 info->big_endian = group->big_endian;
3264 info->tilde = group->tilde;
3265 info->pct = group->pct;
3266 info->count = ITER_NONE;
3267 info->count_as_type = 0;
3268 info->count_in_bytes = FALSE;
3269 info->bang = info->qu = FALSE;
3270 info->null_term = FALSE;
3271
3272 /* check for modifiers */
3273 parse_mods(p, info);
3274 }
3275
3276 /*
3277 * Parse group modifiers. Call this at the open parenthesis of a group to
3278 * find the matching close paren and parse the suffix qualifiers.
3279 */
3280 void CVmPack::parse_group_mods(const CVmPackPos *p, CVmPackType *gt)
3281 {
3282 /* set up a copy of the pointer, so we don't alter the original */
3283 CVmPackPos p2(p);
3284
3285 /* parse and skip the group and modifiers */
3286 skip_group_mods(&p2, gt);
3287 }
3288
3289 /*
3290 * Parse and skip a group and its modifiers. Call this at the open paren
3291 * of a group to find the matching close paren and parse past the suffix
3292 * qualifiers. This leaves 'p' positioned after the group's qualifiers.
3293 */
3294 void CVmPack::skip_group_mods(CVmPackPos *p, CVmPackType *gt)
3295 {
3296 /* note the close paren type we're looking for */
3297 wchar_t c = p->getch();
3298 wchar_t close_paren = (c == '(' ? ')' :
3299 c == '[' ? ']' :
3300 c == '{' ? '}' :
3301 0);
3302
3303 /* skip to the close paren */
3304 p->inc();
3305 skip_group(p, close_paren);
3306
3307 /* skip the close paren */
3308 p->inc();
3309
3310 /* parse the group modifiers */
3311 parse_mods(p, gt);
3312 }
3313
3314 /*
3315 * Skip to the close paren of a group. Call this at the character after
3316 * the open paren; we'll read ahead until we find the close paren, and
3317 * return positioned at the paren.
3318 */
3319 void CVmPack::skip_group(CVmPackPos *p, wchar_t close_paren)
3320 {
3321 /* scan ahead to the matching close paren */
3322 int depth = 1;
3323 for (p->inc() ; p->more() ; p->inc())
3324 {
3325 /* note any further nesting */
3326 wchar_t c = p->getch();
3327 switch (c)
3328 {
3329 case '(':
3330 case '[':
3331 case '{':
3332 depth++;
3333 break;
3334
3335 case ')':
3336 case ']':
3337 case '}':
3338 depth--;
3339 break;
3340 }
3341
3342 /*
3343 * if this is our close paren, and we're not in nested parens or
3344 * other brackets, we're done
3345 */
3346 if (c == close_paren && depth == 0)
3347 break;
3348 }
3349
3350 /* make sure we found the matching close paren */
3351 if (!p->more())
3352 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index());
3353 }
3354
3355 /*
3356 * Figure the '*' repeat count value for a given type code
3357 */
3358 static int star_to_count(wchar_t type_code)
3359 {
3360 switch (type_code)
3361 {
3362 case 'x':
3363 case 'X':
3364 case '@':
3365 return 0;
3366
3367 default:
3368 return ITER_STAR;
3369 }
3370 }
3371
3372 /*
3373 * Parse modifiers
3374 */
3375 void CVmPack::parse_mods(CVmPackPos *p, CVmPackType *t)
3376 {
3377 /* keep going until we stop finding modifiers */
3378 while (p->more())
3379 {
3380 /* get the next character */
3381 wchar_t c = p->getch();
3382
3383 /* check what we have */
3384 if (c == '<')
3385 {
3386 /* little-endian flag - note it and skip it */
3387 t->big_endian = FALSE;
3388 p->inc();
3389 }
3390 else if (c == '>')
3391 {
3392 /* big-endian flag - note it and skip it */
3393 t->big_endian = TRUE;
3394 p->inc();
3395 }
3396 else if (c == '0')
3397 {
3398 /* this can only be used with certain string types */
3399 if (strchr("auwhH", (char)t->type_code) == 0)
3400 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index());
3401
3402 /* null-termination */
3403 t->null_term = TRUE;
3404 p->inc();
3405 }
3406 else if (is_digit(c))
3407 {
3408 /*
3409 * if we already have a '*', the combination of a numeric count
3410 * and a '*' makes it an up-to count
3411 */
3412 if (t->count == ITER_STAR)
3413 t->up_to_count = TRUE;
3414
3415 /* it's a digit, so this is a simple numeric repeat count */
3416 int count_idx = p->index();
3417 t->count = p->parse_int();
3418 t->count_as_type = 0;
3419
3420 /* enforce a minimum value of 1 for most types, 0 for @ */
3421 int minval = (t->type_code == '@' ? 0 : 1);
3422 if (t->count < minval)
3423 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, count_idx);
3424 }
3425 else if (c == ':')
3426 {
3427 /* repeat count as type - get and remember the type code */
3428 p->inc();
3429 c = p->nextch();
3430
3431 /* validate the type code and get its size */
3432 switch (c)
3433 {
3434 case 'a':
3435 case 'A':
3436 case 'b':
3437 case 'u':
3438 case 'U':
3439 case 'h':
3440 case 'H':
3441 case 'k':
3442 t->count_as_type = c;
3443 t->count = 1;
3444
3445 case 'w':
3446 case 'W':
3447 t->count_as_type = c;
3448 t->count = 2;
3449 break;
3450
3451 case 'c':
3452 case 'C':
3453 t->count_as_type = c;
3454 t->count = 1;
3455 break;
3456
3457 case 's':
3458 case 'S':
3459 t->count_as_type = c;
3460 t->count = 2;
3461 break;
3462
3463 case 'l':
3464 case 'L':
3465 case 'f':
3466 t->count_as_type = c;
3467 t->count = 4;
3468 break;
3469
3470 case 'q':
3471 case 'Q':
3472 case 'd':
3473 t->count_as_type = c;
3474 t->count = 8;
3475 break;
3476
3477 default:
3478 /* invalid type */
3479 err_throw_a(VMERR_PACK_PARSE, 1, ERR_TYPE_INT, p->index());
3480 }
3481 }
3482 else if (c == '*')
3483 {
3484 /*
3485 * if we already have a numeric count, this makes it an up-to
3486 * count
3487 */
3488 if (t->count >= 0)
3489 {
3490 /* mark it as an up-to count, but leave the count intact */
3491 t->up_to_count = TRUE;
3492 }
3493 else
3494 {
3495 /* there's no count yet, so it's an indefinite counter type */
3496 t->count = star_to_count(t->type_code);
3497 t->count_as_type = 0;
3498 }
3499
3500 /* skip the '*' */
3501 p->inc();
3502 }
3503 else if (c == '!')
3504 {
3505 /*
3506 * ! means "count in bytes" for string types wWhH; for other
3507 * types just record the !
3508 */
3509 if (t->type_code != 0 && strchr("wWhH", (char)t->type_code) != 0)
3510 t->count_in_bytes = TRUE;
3511 else
3512 t->bang = TRUE;
3513 p->inc();
3514 }
3515 else if (c == '~')
3516 {
3517 /* note the ~ qualifier */
3518 t->tilde = TRUE;
3519 p->inc();
3520 }
3521 else if (c == '?')
3522 {
3523 /* note the ? qualifier */
3524 t->qu = TRUE;
3525 p->inc();
3526 }
3527 else if (c == '%')
3528 {
3529 /* note the % qualifier */
3530 t->pct = TRUE;
3531 p->inc();
3532 }
3533 else
3534 {
3535 /* it's not a modifier character, so we're done */
3536 break;
3537 }
3538 }
3539 }