Debian Codegraph @

terps/tads/tads3/vmbytarr.cpp

raw symbols SCIP
1 /*
2 * Copyright (c) 2001, 2002 Michael J. Roberts. All Rights Reserved.
3 *
4 * Please see the accompanying license file, LICENSE.TXT, for information
5 * on using and copying this software.
6 */
7 /*
8 Name
9 vmbytarr.cpp - TADS 3 ByteArray intrinsic class
10 Function
11
12 Notes
13
14 Modified
15 06/05/01 MJRoberts - Creation
16 */
17
18 #include <stdlib.h>
19 #include <assert.h>
20 #include "vmtype.h"
21 #include "vmobj.h"
22 #include "vmglob.h"
23 #include "vmbytarr.h"
24 #include "vmbif.h"
25 #include "vmfile.h"
26 #include "vmerrnum.h"
27 #include "vmerr.h"
28 #include "vmstack.h"
29 #include "vmmeta.h"
30 #include "vmundo.h"
31 #include "vmrun.h"
32 #include "charmap.h"
33 #include "utf8.h"
34 #include "vmstr.h"
35 #include "vmcset.h"
36 #include "vmdatasrc.h"
37 #include "vmpack.h"
38 #include "sha2.h"
39 #include "md5.h"
40
41
42 /* ------------------------------------------------------------------------ */
43 /*
44 * Byte Array data source
45 */
46 class CVmByteArraySource: public CVmDataSource
47 {
48 public:
49 /* set up a data source on the entire range of the array */
50 CVmByteArraySource(VMG_ vm_obj_id_t arr)
51 {
52 /* remember the array and globals */
53 this->vmg = VMGLOB_ADDR;
54 this->arr_id = arr;
55 this->arr = (CVmObjByteArray *)vm_objp(vmg_ arr);
56
57 /* we provide access to the entire range of the array */
58 this->idx = 0;
59 this->start_idx = 0;
60 this->end_idx = this->arr->get_element_count();
61 }
62
63 /* set up a data source on a slice of the array */
64 CVmByteArraySource(VMG_ vm_obj_id_t arr, long start_idx, long len)
65 {
66 /* remember the array and globals */
67 this->vmg = VMGLOB_ADDR;
68 this->arr_id = arr;
69 this->arr = (CVmObjByteArray *)vm_objp(vmg_ arr);
70
71 /* remember our window */
72 this->idx = start_idx;
73 this->start_idx = start_idx;
74 this->end_idx = start_idx + len;
75
76 /* limit the window to the actual available size */
77 if ((unsigned long)end_idx > this->arr->get_element_count())
78 end_idx = this->arr->get_element_count();
79 }
80
81 CVmDataSource *clone(VMG_ const char * /*mode*/)
82 {
83 return new CVmByteArraySource(
84 vmg_ arr_id, start_idx, end_idx - start_idx);
85 }
86
87 /* read bytes; returns 0 on success, non-zero on error */
88 virtual int read(void *buf, size_t len)
89 {
90 /* limit the read to the available length */
91 size_t rdlen = (idx + (long)len > end_idx
92 ? (size_t)(end_idx - idx) : len);
93
94 /* copy the requested bytes starting at the current index */
95 size_t copied = arr->copy_to_buf((unsigned char *)buf, idx + 1, rdlen);
96
97 /* move past the bytes copied */
98 idx += copied;
99
100 /* we were successful if we copied exactly the requested length */
101 return copied != len;
102 }
103
104 /* read bytes; returns the number of bytes read */
105 virtual int readc(void *buf, size_t len)
106 {
107 /* limit the read to the available length */
108 size_t rdlen = (idx + (long)len > end_idx
109 ? (size_t)(end_idx - idx) : len);
110
111 /* copy the requested bytes */
112 size_t copied = arr->copy_to_buf((unsigned char *)buf, idx + 1, rdlen);
113
114 /* move past the bytes copied */
115 idx += copied;
116
117 /* return the number of bytes actually read */
118 return copied;
119 }
120
121 /* write bytes; returns 0 on success, non-zero on error */
122 virtual int write(const void *buf, size_t len)
123 {
124 /* establish global access */
125 VMGLOB_PTR(vmg);
126
127 /* limit the write to the available length */
128 size_t wrtlen = (idx + (long)len > end_idx
129 ? (size_t)(end_idx - idx) : len);
130
131 /* copy the requested bytes (saving undo) */
132 size_t copied = arr->copy_from_buf_undo(
133 vmg_ arr_id, (const unsigned char *)buf, idx + 1, wrtlen);
134
135 /* move past the bytes copied */
136 idx += copied;
137
138 /* we were successful if we copied exactly the requested length */
139 return copied != len;
140 }
141
142 /* get the length of our slice of the array in bytes */
143 virtual long get_size() { return end_idx - start_idx; }
144
145 /* get the current seek location */
146 virtual long get_pos() { return idx - start_idx; }
147
148 /* set the current seek location - 'mode' is an OSFSK_xxx mode */
149 virtual int seek(long ofs, int mode)
150 {
151 switch (mode)
152 {
153 case OSFSK_SET:
154 idx = start_idx + ofs;
155 break;
156
157 case OSFSK_CUR:
158 idx += ofs;
159 break;
160
161 case OSFSK_END:
162 idx = end_idx + ofs;
163 break;
164
165 default:
166 return 1;
167 }
168
169 /* make sure it's in range */
170 if (idx < start_idx)
171 idx = start_idx;
172 else if (idx > end_idx)
173 idx = end_idx;
174
175 /* success */
176 return 0;
177 }
178
179 /* flush - returns 0 on success, non-zero on error */
180 virtual int flush() { return 0; }
181
182 /* close the underlying system resource */
183 virtual void close() { }
184
185 protected:
186 /* our underlying array */
187 vm_obj_id_t arr_id;
188 CVmObjByteArray *arr;
189
190 /* current read/write index in the array */
191 long idx;
192
193 /* the bounds of the slice of the array we present as the file */
194 long start_idx;
195 long end_idx;
196
197 /* we need globals in some interface routines without the VMG_ param */
198 vm_globals *vmg;
199 };
200
201
202
203 /* ------------------------------------------------------------------------ */
204 /*
205 * Integer format codes. A full format code is given by a bitwise
206 * combination of size, byte order, and signedness.
207 */
208
209 /* integer sizes */
210 #define FmtSizeMask 0x000F
211 #define FmtInt8 0x0000
212 #define FmtInt16 0x0001
213 #define FmtInt32 0x0002
214
215 /* integer byte orders */
216 #define FmtOrderMask 0x00F0
217 #define FmtLittleEndian 0x0000
218 #define FmtBigEndian 0x0010
219
220 /* integer signedness */
221 #define FmtSignedMask 0x0F00
222 #define FmtSigned 0x0000
223 #define FmtUnsigned 0x0100
224
225 /* ------------------------------------------------------------------------ */
226 /*
227 * statics
228 */
229
230 /* metaclass registration object */
231 static CVmMetaclassByteArray metaclass_reg_obj;
232 CVmMetaclass *CVmObjByteArray::metaclass_reg_ = &metaclass_reg_obj;
233
234 /* function table */
235 int (CVmObjByteArray::
236 *CVmObjByteArray::func_table_[])(VMG_ vm_obj_id_t self,
237 vm_val_t *retval, uint *argc) =
238 {
239 &CVmObjByteArray::getp_undef, /* 0 */
240 &CVmObjByteArray::getp_length, /* 1 */
241 &CVmObjByteArray::getp_subarray, /* 2 */
242 &CVmObjByteArray::getp_copy_from, /* 3 */
243 &CVmObjByteArray::getp_fill_val, /* 4 */
244 &CVmObjByteArray::getp_to_string, /* 5 */
245 &CVmObjByteArray::getp_read_int, /* 6 */
246 &CVmObjByteArray::getp_write_int, /* 7 */
247 &CVmObjByteArray::getp_packBytes, /* 8 */
248 &CVmObjByteArray::getp_unpackBytes, /* 9 */
249 &CVmObjByteArray::getp_sha256, /* 10 */
250 &CVmObjByteArray::getp_digestMD5 /* 11 */
251 };
252
253 /* static property indices */
254 const int PROPIDX_packBytes = 8;
255
256
257 /* ------------------------------------------------------------------------ */
258 /*
259 * Create from stack
260 */
261 vm_obj_id_t CVmObjByteArray::create_from_stack(VMG_ const uchar **pc_ptr,
262 uint argc)
263 {
264 vm_obj_id_t id = VM_INVALID_OBJ;
265 CVmObjByteArray *arr;
266 unsigned long cnt;
267 vm_val_t *arg1;
268 const char *str;
269
270 /* check our arguments */
271 if (argc < 1)
272 err_throw(VMERR_WRONG_NUM_OF_ARGS);
273
274 /* see what we have for the first argument */
275 arg1 = G_stk->get(0);
276 if (arg1->typ == VM_INT)
277 {
278 /*
279 * it's a simple count argument - make sure we only have one
280 * argument
281 */
282 if (argc != 1)
283 err_throw(VMERR_WRONG_NUM_OF_ARGS);
284
285 /* get the number of elements */
286 cnt = (unsigned long)arg1->val.intval;
287
288 /* create the array with the given number of elements */
289 id = vm_new_id(vmg_ FALSE, FALSE, FALSE);
290 arr = new (vmg_ id) CVmObjByteArray(vmg_ cnt);
291
292 /* set each element to zero */
293 arr->fill_with(0, 1, cnt);
294 }
295 else if ((str = arg1->get_as_string(vmg0_)) != 0)
296 {
297 /*
298 * String argument - we're creating a byte array from the string.
299 * We can map it from a character set, or we can just stuff the
300 * character values into bytes. Check arguments - we must have one
301 * or two of them (the string, and the optional character set)
302 */
303 if (argc < 1 || argc > 2)
304 err_throw(VMERR_WRONG_NUM_OF_ARGS);
305
306 /* fetch the character mapper, if there is one */
307 const vm_val_t *cmap = (argc >= 2 ? G_stk->get(1) : 0);
308
309 /* create the byte array */
310 id = create_from_string(vmg_ G_stk->get(0), str, cmap);
311 }
312 else if (arg1->typ == VM_OBJ && is_byte_array(vmg_ arg1->val.obj))
313 {
314 unsigned long src_idx;
315 unsigned long src_cnt;
316
317 /* remember the source array */
318 CVmObjByteArray *src_arr =
319 (CVmObjByteArray *)vm_objp(vmg_ arg1->val.obj);
320
321 /* get the count from the array */
322 src_cnt = src_arr->get_element_count();
323
324 /*
325 * check for the optional actual element count, and the optional
326 * starting index
327 */
328 if (argc == 1)
329 {
330 /* no size specified - use the same size as the original */
331 cnt = src_cnt;
332
333 /* start at the first element */
334 src_idx = 1;
335 }
336 else
337 {
338 /* make sure it's an integer */
339 if (G_stk->get(1)->typ != VM_INT)
340 err_throw(VMERR_INT_VAL_REQD);
341
342 /* use the specified starting index */
343 src_idx = (unsigned long)G_stk->get(1)->val.intval;
344
345 /* if the index is below 1, force it to 1 */
346 if (src_idx < 1)
347 src_idx = 1;
348
349 /* check for the starting element argument */
350 if (argc >= 3)
351 {
352 /* make sure it's an integer */
353 if (G_stk->get(2)->typ != VM_INT)
354 err_throw(VMERR_INT_VAL_REQD);
355
356 /* use the specified element count */
357 cnt = (unsigned long)G_stk->get(2)->val.intval;
358
359 /* make sure we don't have any extra arguments */
360 if (argc > 3)
361 err_throw(VMERR_WRONG_NUM_OF_ARGS);
362 }
363 else
364 {
365 /*
366 * no count specified - use the number of elements in the
367 * original remaining after the starting index
368 */
369 if (src_idx > src_cnt)
370 cnt = 0;
371 else
372 cnt = src_cnt + 1 - src_idx;
373 }
374 }
375
376 /* create the new array */
377 id = vm_new_id(vmg_ FALSE, FALSE, FALSE);
378 arr = new (vmg_ id) CVmObjByteArray(vmg_ cnt);
379
380 /* copy the source array */
381 arr->copy_from(1, src_arr, src_idx, cnt);
382 }
383 else
384 {
385 /* invalid argument */
386 err_throw(VMERR_BAD_TYPE_BIF);
387 }
388
389 /* discard arguments */
390 G_stk->discard(argc);
391
392 /* return the new object */
393 return id;
394 }
395
396 /* ------------------------------------------------------------------------ */
397 /*
398 * Create a new byte array from a string, mapping through the given
399 * character set object if present, or just stuffing the character values
400 * into bytes if not.
401 */
402 vm_obj_id_t CVmObjByteArray::create_from_string(
403 VMG_ const vm_val_t *strval, const char *str, const vm_val_t *mapval)
404 {
405 /* we can't allocate our object until we know the mapped byte count */
406 vm_obj_id_t id = VM_INVALID_OBJ;
407 CVmObjByteArray *arr = 0;
408
409 /* get the string's length and skip the length prefix */
410 size_t len = vmb_get_len(str);
411 str += VMB_LEN;
412
413 /*
414 * We have two modes: map to bytes via a character set, or stuff
415 * unmapped character values into bytes. Check which mode we're using.
416 */
417 if (mapval == 0 || mapval->typ == VM_NIL)
418 {
419 /*
420 * No character mapper - just stuff each character into a byte. If
421 * a character is outside the 0..255 range, it's an error.
422 */
423
424 /* count the number of characters */
425 utf8_ptr p((char *)str);
426 size_t clen = p.len(len);
427
428 /* allocate the array - each string character is one array byte */
429 id = create(vmg_ FALSE, clen);
430 arr = (CVmObjByteArray *)vm_objp(vmg_ id);
431
432 /* copy bytes into the array */
433 for (int idx = 1 ; len != 0 ; )
434 {
435 /* translate a buffer-full */
436 unsigned char buf[256];
437 size_t cur = 0;
438 for ( ; len != 0 && cur < sizeof(buf) ; p.inc(&len))
439 {
440 /* get the next character; make sure it fits in a byte */
441 wchar_t ch = p.getch();
442 if (ch > 255)
443 err_throw(VMERR_NUM_OVERFLOW);
444
445 /* save it */
446 buf[cur++] = (unsigned char)ch;
447 }
448
449 /* copy this chunk to the array */
450 arr->cons_copy_from_buf(buf, idx, cur);
451 idx += cur;
452 }
453 }
454 else
455 {
456 /* interpret the character set argument */
457 vm_obj_id_t mapid = CVmBif::get_charset_obj(vmg_ mapval);
458
459 /* get the to-local mapping from the character set */
460 CCharmapToLocal *mapper =
461 ((CVmObjCharSet *)vm_objp(vmg_ mapid))->get_to_local(vmg0_);
462
463 /*
464 * first, do a mapping with a null output buffer to determine how
465 * many bytes we need for the mapping
466 */
467 size_t src_bytes_used;
468 size_t byte_len = mapper->map_utf8(0, 0, str, len, &src_bytes_used);
469
470 /* allocate a new ByteArray with the required number of bytes */
471 id = CVmObjByteArray::create(vmg_ FALSE, byte_len);
472 arr = (CVmObjByteArray *)vm_objp(vmg_ id);
473
474 /* convert it again, this time storing the bytes */
475 for (size_t out_idx = 1 ; len != 0 ; )
476 {
477 char buf[128];
478
479 /* convert a buffer-full */
480 byte_len = mapper->map_utf8(buf, sizeof(buf), str, len,
481 &src_bytes_used);
482
483 /* store the bytes in the byte array */
484 arr->cons_copy_from_buf((unsigned char *)buf, out_idx, byte_len);
485
486 /* advance past the output bytes we used */
487 out_idx += byte_len;
488
489 /* advance past the source bytes we used */
490 str += src_bytes_used;
491 len -= src_bytes_used;
492 }
493 }
494
495 /* return the new array's object ID */
496 return id;
497 }
498
499 /* ------------------------------------------------------------------------ */
500 /*
501 * Create from binary data
502 */
503 vm_obj_id_t CVmObjByteArray::create_from_bytes(
504 VMG_ int in_root_set, const char *buf, size_t len)
505 {
506 /* allocate the array */
507 vm_obj_id_t id = create(vmg_ in_root_set, len);
508 CVmObjByteArray *arr = (CVmObjByteArray *)vm_objp(vmg_ id);
509
510 /* copy the bytes into the array */
511 arr->cons_copy_from_buf((const unsigned char *)buf, 1, len);
512
513 /* return the new array's object ID */
514 return id;
515 }
516
517 /* ------------------------------------------------------------------------ */
518 /*
519 * Create with no contents
520 */
521 vm_obj_id_t CVmObjByteArray::create(VMG_ int in_root_set)
522 {
523 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
524 new (vmg_ id) CVmObjByteArray();
525 return id;
526 }
527
528 /*
529 * Create with the given element count
530 */
531 vm_obj_id_t CVmObjByteArray::create(VMG_ int in_root_set,
532 unsigned long ele_count)
533 {
534 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
535 new (vmg_ id) CVmObjByteArray(vmg_ ele_count);
536 return id;
537 }
538
539 /* ------------------------------------------------------------------------ */
540 /*
541 * Instantiate
542 */
543 CVmObjByteArray::CVmObjByteArray(VMG_ unsigned long ele_count)
544 {
545 /* allocate space */
546 alloc_array(vmg_ ele_count);
547 }
548
549 /* ------------------------------------------------------------------------ */
550 /*
551 * Allocate space
552 */
553 void CVmObjByteArray::alloc_array(VMG_ unsigned long ele_count)
554 {
555 unsigned long ele_rem;
556 size_t slot_cnt;
557 size_t alloc_size;
558 size_t i;
559
560 /*
561 * figure out how many first-level page tables we need - each
562 * first-level page table refers to 256M bytes (8k pages per
563 * second-level page table times 32k bytes per page), so we need one
564 * page table pointer per 256 megabytes == 2^15*2^32 == 2^28.
565 */
566 slot_cnt = (ele_count == 0 ? 0 : ((size_t)((ele_count - 1) >> 28) + 1));
567
568 /*
569 * allocate the extension - 4 bytes for the element count plus one
570 * (char **) per slot
571 */
572 alloc_size = 4 + slot_cnt*sizeof(char **);
573 ext_ = (char *)G_mem->get_var_heap()->alloc_mem(alloc_size, this);
574
575 /* set the element count */
576 set_element_count(ele_count);
577
578 /* allocate the second-level page tables */
579 for (ele_rem = ele_count, i = 0 ; i < slot_cnt ; ++i)
580 {
581 unsigned char **pgtab;
582 unsigned long pgcnt;
583 size_t pg;
584
585 /*
586 * Determine how many pages we need in this page table. Each page
587 * holds 32k bytes, so we need one page per 32k bytes remaining to
588 * allocate. However, each page table can hold only up to 8k page
589 * pointers, so limit this table to 8k pages.
590 */
591 pgcnt = ((ele_rem - 1) >> 15) + 1;
592 if (pgcnt > 8*1024)
593 pgcnt = 8*1024;
594
595 /* allocate this second-level page table */
596 pgtab = (unsigned char **)t3malloc(
597 (size_t)(pgcnt * sizeof(unsigned char *)));
598
599 /* set this page table pointer */
600 get_page_table_array()[i] = pgtab;
601
602 /* allocate the pages in this table */
603 for (pg = 0 ; pg < pgcnt ; ++pg)
604 {
605 size_t pgsiz;
606
607 /*
608 * calculate the size for this page - the maximum size of a
609 * page is 32k, but allocate only the amount remaining if we
610 * have less than 32k left to allocate
611 */
612 pgsiz = 32*1024;
613 if (pgsiz > ele_rem)
614 pgsiz = (size_t)ele_rem;
615
616 /* deduct this page's size from the remaining element count */
617 ele_rem -= pgsiz;
618
619 /* allocate and store this page */
620 pgtab[pg] = (unsigned char *)t3malloc(pgsiz);
621 }
622 }
623 }
624
625 /* ------------------------------------------------------------------------ */
626 /*
627 * Notify of deletion
628 */
629 void CVmObjByteArray::notify_delete(VMG_ int /*in_root_set*/)
630 {
631 size_t slot;
632 unsigned char ***slotp;
633 size_t slot_cnt;
634 size_t bytes_rem;
635
636 /* if we have no extension, there's nothing to do */
637 if (ext_ == 0)
638 return;
639
640 /* calculate the number of second-level page table slots */
641 slot_cnt = (size_t)(get_element_count() == 0
642 ? 0
643 : ((get_element_count() >> 28) + 1));
644
645 /* we have all of the bytes in the array left do delete */
646 bytes_rem = get_element_count();
647
648 /* traverse the list of second-level page tables and delete each one */
649 for (slot = 0, slotp = get_page_table_array() ; slot < slot_cnt ;
650 ++slot, ++slotp)
651 {
652 size_t pg;
653 unsigned char **pgp;
654
655 /* traverse each page in this page table */
656 for (pg = 0, pgp = *slotp ; pg < 8*1024 && bytes_rem != 0 ;
657 ++pg, ++pgp)
658 {
659 /* delete this page */
660 t3free(*pgp);
661
662 /*
663 * deduct this page's size from the remaining bytes to delete
664 * - the page size is up to 32k, but no more than the
665 * remaining size
666 */
667 if (bytes_rem > 32*1024)
668 bytes_rem -= 32*1024;
669 else
670 bytes_rem = 0;
671 }
672
673 /* delete this page table */
674 t3free(*slotp);
675 }
676
677 /* free our extension */
678 G_mem->get_var_heap()->free_mem(ext_);
679 }
680
681 /* ------------------------------------------------------------------------ */
682 /*
683 * Cast to string. Maps to string treating the bytes as Latin-1
684 * characters.
685 */
686 const char *CVmObjByteArray::cast_to_string(
687 VMG_ vm_obj_id_t self, vm_val_t *new_str) const
688 {
689 /* set up a source stream to read from the byte array into the string */
690 CVmByteArraySource src(vmg_ self);
691
692 /* create the string */
693 new_str->set_obj(CVmObjString::create_latin1(vmg_ FALSE, &src));
694
695 /* return the new string's byte buffer */
696 return new_str->get_as_string(vmg0_);
697 }
698
699
700 /* ------------------------------------------------------------------------ */
701 /*
702 * set a property
703 */
704 void CVmObjByteArray::set_prop(VMG_ class CVmUndo *,
705 vm_obj_id_t, vm_prop_id_t,
706 const vm_val_t *)
707 {
708 err_throw(VMERR_INVALID_SETPROP);
709 }
710
711 /* ------------------------------------------------------------------------ */
712 /*
713 * Get a static property
714 */
715 int CVmObjByteArray::call_stat_prop(VMG_ vm_val_t *result,
716 const uchar **pc_ptr, uint *argc,
717 vm_prop_id_t prop)
718 {
719 /* get the function table index */
720 int idx = G_meta_table->prop_to_vector_idx(
721 metaclass_reg_->get_reg_idx(), prop);
722
723 /* check for static methods we define in ByteArray */
724 switch (idx)
725 {
726 case PROPIDX_packBytes:
727 /* the static version of packBytes() */
728 return static_packBytes(vmg_ result, argc);
729
730 default:
731 /* not one of ours - defer to the superclass */
732 return CVmObject::call_stat_prop(vmg_ result, pc_ptr, argc, prop);
733 }
734 }
735
736 /* ------------------------------------------------------------------------ */
737 /*
738 * get a property
739 */
740 int CVmObjByteArray::get_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval,
741 vm_obj_id_t self, vm_obj_id_t *source_obj,
742 uint *argc)
743 {
744 uint func_idx;
745
746 /* translate the property index to an index into our function table */
747 func_idx = G_meta_table
748 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop);
749
750 /* call the appropriate function */
751 if ((this->*func_table_[func_idx])(vmg_ self, retval, argc))
752 {
753 *source_obj = metaclass_reg_->get_class_obj(vmg0_);
754 return TRUE;
755 }
756
757 /* inherit default handling */
758 return CVmObject::get_prop(vmg_ prop, retval, self, source_obj, argc);
759 }
760
761 /* ------------------------------------------------------------------------ */
762 /*
763 * ByteArray private undo record - saved byte block
764 */
765 struct bytearray_undo_bytes
766 {
767 /* next block in the list */
768 bytearray_undo_bytes *nxt_;
769
770 /* the bytes - overallocated to the required size */
771 unsigned char buf_[1];
772 };
773
774 /*
775 * ByteArray private undo record
776 */
777 class bytearray_undo_rec
778 {
779 public:
780 bytearray_undo_rec(CVmObjByteArray *arr, unsigned long start_idx,
781 unsigned long cnt)
782 {
783 unsigned long idx;
784 unsigned long rem;
785 bytearray_undo_bytes *tail;
786
787 /* remember the starting index and length of the saved data */
788 idx_ = start_idx;
789 cnt_ = cnt;
790
791 /* store the original data in a linked list of byte blocks */
792 for (idx = start_idx, rem = cnt, save_head_ = tail = 0 ;
793 rem != 0 ; )
794 {
795 bytearray_undo_bytes *p;
796 size_t cur;
797
798 /* allocate up to 32k, or the amount remaining if lower */
799 cur = 32768;
800 if (cur > rem)
801 cur = (size_t)rem;
802
803 /* allocate a new block */
804 p = (bytearray_undo_bytes *)t3malloc(
805 sizeof(bytearray_undo_bytes) + cur - 1);
806
807 /* link this block into our list */
808 if (tail != 0)
809 tail->nxt_ = p;
810 else
811 save_head_ = p;
812 tail = p;
813 p->nxt_ = 0;
814
815 /* copy bytes into this block */
816 arr->copy_to_buf(p->buf_, idx, cur);
817
818 /* move past the copied bytes */
819 idx += cur;
820 rem -= cur;
821 }
822 }
823
824 ~bytearray_undo_rec()
825 {
826 bytearray_undo_bytes *cur;
827 bytearray_undo_bytes *nxt;
828
829 /* delete our list of saved byte blocks */
830 for (cur = save_head_ ; cur != 0 ; cur = nxt)
831 {
832 /*
833 * remember the next one, as we're about to lose the current
834 * one's memory
835 */
836 nxt = cur->nxt_;
837
838 /* delete this one */
839 t3free(cur);
840 }
841 }
842
843 /* copy our data back into an array */
844 void apply_undo(CVmObjByteArray *arr)
845 {
846 bytearray_undo_bytes *cur;
847 unsigned long idx;
848 unsigned long rem;
849
850 /* delete our list of saved byte blocks */
851 for (cur = save_head_, idx = idx_, rem = cnt_ ; rem != 0 ; )
852 {
853 size_t copy_len;
854
855 /* limit the copy to our block size (32k) */
856 copy_len = 32768;
857 if (copy_len > rem)
858 copy_len = (size_t)rem;
859
860 /* copy this block into the array */
861 arr->copy_from_buf(cur->buf_, idx, copy_len);
862
863 /* move past the copied data */
864 cur = cur->nxt_;
865 idx += copy_len;
866 rem -= copy_len;
867 }
868 }
869
870 /* starting index */
871 unsigned long idx_;
872
873 /* length */
874 unsigned long cnt_;
875
876 /* head of list of blocks of saved data */
877 bytearray_undo_bytes *save_head_;
878 };
879
880 /*
881 * Save undo for a change to a range of the array
882 */
883 void CVmObjByteArray::save_undo(VMG_ vm_obj_id_t self,
884 unsigned long start_idx,
885 unsigned long cnt)
886 {
887 bytearray_undo_rec *rec;
888 vm_val_t oldval;
889
890 /* create our key record - this contains the entire original value */
891 rec = new bytearray_undo_rec(this, start_idx, cnt);
892
893 /* we don't use the old value for anything; use nil as a dummy */
894 oldval.set_nil();
895
896 /* add the undo record */
897 if (!G_undo->add_new_record_ptr_key(vmg_ self, rec, &oldval))
898 {
899 /* failed to save the undo - discard our private key record */
900 delete rec;
901 }
902 }
903
904 /*
905 * Apply undo
906 */
907 void CVmObjByteArray::apply_undo(VMG_ struct CVmUndoRecord *gen_rec)
908 {
909 /* apply our private undo record, if present */
910 if (gen_rec->id.ptrval != 0)
911 {
912 bytearray_undo_rec *rec;
913
914 /* get my private record */
915 rec = (bytearray_undo_rec *)gen_rec->id.ptrval;
916
917 /* apply the undo in the record to self */
918 rec->apply_undo(this);
919
920 /* delete the record now that it's been applied */
921 delete rec;
922
923 /* clear the pointer so we know it's gone */
924 gen_rec->id.ptrval = 0;
925 }
926 }
927
928 /*
929 * Discard undo
930 */
931 void CVmObjByteArray::discard_undo(VMG_ struct CVmUndoRecord *rec)
932 {
933 /* delete our extra information record if present */
934 if (rec->id.ptrval != 0)
935 {
936 /* free the record */
937 t3free((bytearray_undo_rec *)rec->id.ptrval);
938
939 /* clear the pointer so we know it's gone */
940 rec->id.ptrval = 0;
941 }
942 }
943
944 /* ------------------------------------------------------------------------ */
945 /*
946 * load from an image file
947 */
948 void CVmObjByteArray::load_from_image(VMG_ vm_obj_id_t self,
949 const char *ptr, size_t siz)
950 {
951 /* load from the image data */
952 load_image_data(vmg_ ptr, siz);
953
954 /*
955 * save our image data pointer in the object table, so that we can
956 * access it (without storing it ourselves) during a reload
957 */
958 G_obj_table->save_image_pointer(self, ptr, siz);
959 }
960
961 /*
962 * reload the object from image data
963 */
964 void CVmObjByteArray::reload_from_image(VMG_ vm_obj_id_t,
965 const char *ptr, size_t siz)
966 {
967 /* load the image data */
968 load_image_data(vmg_ ptr, siz);
969 }
970
971 /*
972 * Load from image data
973 */
974 void CVmObjByteArray::load_image_data(VMG_ const char *ptr, size_t siz)
975 {
976 unsigned long cnt;
977 unsigned long idx;
978
979 /* if we already have memory allocated, free it */
980 notify_delete(vmg_ FALSE);
981
982 /* get the new array size */
983 cnt = t3rp4u(ptr);
984
985 /* make sure the size isn't larger than we'd expect */
986 if (siz > 4 + cnt)
987 siz = 4 + cnt;
988
989 /* allocate memory at the new size as indicated in the image data */
990 alloc_array(vmg_ cnt);
991
992 /* if the size is smaller than we'd expect, set extra elements to nil */
993 if (siz < VMB_LEN + (VMB_DATAHOLDER * cnt))
994 {
995 /* fill everything with zeros to start with */
996 fill_with(0, 1, cnt);
997 }
998
999 /* copy the bytes */
1000 for (ptr += 4, siz -= 4, idx = 1 ; siz != 0 ; )
1001 {
1002 unsigned char *dstp;
1003 size_t chunk_size;
1004 size_t avail;
1005
1006 /* get the next chunk */
1007 dstp = get_ele_ptr(idx, &avail);
1008
1009 /* limit this chunk size to the remaining copy size */
1010 chunk_size = avail;
1011 if (chunk_size > siz)
1012 chunk_size = siz;
1013
1014 /* copy this chunk */
1015 memcpy(dstp, ptr, chunk_size);
1016
1017 /* advance past this chunk */
1018 idx += chunk_size;
1019 ptr += chunk_size;
1020 siz -= chunk_size;
1021 }
1022 }
1023
1024 /* ------------------------------------------------------------------------ */
1025 /*
1026 * save to a file
1027 */
1028 void CVmObjByteArray::save_to_file(VMG_ class CVmFile *fp)
1029 {
1030 unsigned long rem;
1031 unsigned long idx;
1032
1033 /* write the element count */
1034 fp->write_int4(get_element_count());
1035
1036 /* write the bytes in chunks */
1037 for (idx = 1, rem = get_element_count() ; rem != 0 ; )
1038 {
1039 size_t avail;
1040 size_t chunk;
1041 unsigned char *p;
1042
1043 /* get the next chunk */
1044 p = get_ele_ptr(idx, &avail);
1045
1046 /* limit this copy to the remaining bytes */
1047 chunk = avail;
1048 if (chunk > rem)
1049 chunk = (size_t)rem;
1050
1051 /* write this chunk */
1052 fp->write_bytes((char *)p, chunk);
1053
1054 /* advance past this chunk */
1055 idx += chunk;
1056 rem -= chunk;
1057 }
1058 }
1059
1060 /*
1061 * restore from a file
1062 */
1063 void CVmObjByteArray::restore_from_file(VMG_ vm_obj_id_t self,
1064 CVmFile *fp, CVmObjFixup *)
1065 {
1066 unsigned long ele_cnt;
1067 unsigned long idx;
1068 unsigned long rem;
1069
1070 /* read the element count */
1071 ele_cnt = fp->read_uint4();
1072
1073 /* allocate or reallocate as needed */
1074 if (ext_ == 0)
1075 {
1076 /* we're not yet allocated - allocate now */
1077 alloc_array(vmg_ ele_cnt);
1078 }
1079 else
1080 {
1081 /* already allocated - if it's a different size, reallocate */
1082 if (get_element_count() != ele_cnt)
1083 {
1084 /* delete the old array */
1085 notify_delete(vmg_ FALSE);
1086
1087 /* allocate a new one */
1088 alloc_array(vmg_ ele_cnt);
1089 }
1090 }
1091
1092 /* read the data */
1093 for (idx = 1, rem = ele_cnt ; rem != 0 ; )
1094 {
1095 size_t avail;
1096 size_t chunk;
1097 unsigned char *p;
1098
1099 /* get the next chunk */
1100 p = get_ele_ptr(idx, &avail);
1101
1102 /* limit this copy to the remaining bytes */
1103 chunk = avail;
1104 if (chunk > rem)
1105 chunk = (size_t)rem;
1106
1107 /* read this chunk */
1108 fp->read_bytes((char *)p, chunk);
1109
1110 /* advance past this chunk */
1111 idx += chunk;
1112 rem -= chunk;
1113 }
1114 }
1115
1116 /* ------------------------------------------------------------------------ */
1117 /*
1118 * Retrieve the value at the given index
1119 */
1120 int CVmObjByteArray::index_val_q(VMG_ vm_val_t *result, vm_obj_id_t self,
1121 const vm_val_t *index_val)
1122 {
1123 /* get the index */
1124 int32_t idx = index_val->num_to_int(vmg0_);
1125
1126 /* make sure it's in range */
1127 if (idx < 1 || (uint32_t)idx > get_element_count())
1128 err_throw(VMERR_INDEX_OUT_OF_RANGE);
1129
1130 /* get a pointer to the desired element */
1131 size_t avail;
1132 unsigned char *p = get_ele_ptr(idx, &avail);
1133
1134 /* return the value as an integer */
1135 result->set_int((int)(unsigned short)*p);
1136
1137 /* handled */
1138 return TRUE;
1139 }
1140
1141 /* ------------------------------------------------------------------------ */
1142 /*
1143 * set an indexed element of the array
1144 */
1145 int CVmObjByteArray::set_index_val_q(VMG_ vm_val_t *new_container,
1146 vm_obj_id_t self,
1147 const vm_val_t *index_val,
1148 const vm_val_t *new_val)
1149 {
1150 /* get the index value as an integer */
1151 int32_t idx = index_val->num_to_int(vmg0_);
1152
1153 /* make sure it's in range - 1 to our element count, inclusive */
1154 if (idx < 1 || (uint32_t)idx > get_element_count())
1155 err_throw(VMERR_INDEX_OUT_OF_RANGE);
1156
1157 /* save undo for the change */
1158 save_undo(vmg_ self, idx, 1);
1159
1160 /* get the new value as an integer */
1161 int32_t new_byte = new_val->num_to_int(vmg0_);
1162
1163 /* make sure it's in range */
1164 if (new_byte < 0 || new_byte > 255)
1165 err_throw(VMERR_OUT_OF_RANGE);
1166
1167 /* get a pointer to the desired element */
1168 size_t avail;
1169 unsigned char *p = get_ele_ptr(idx, &avail);
1170
1171 /* set the value */
1172 *p = (unsigned char)new_byte;
1173
1174 /* the result is the original array value */
1175 new_container->set_obj(self);
1176
1177 /* handled */
1178 return TRUE;
1179 }
1180
1181 /* ------------------------------------------------------------------------ */
1182 /*
1183 * Compare for equality
1184 */
1185 int CVmObjByteArray::equals(VMG_ vm_obj_id_t self, const vm_val_t *val,
1186 int /*depth*/) const
1187 {
1188 CVmObjByteArray *other;
1189 unsigned long idx;
1190 unsigned long rem;
1191
1192 /* if it's a self-reference, it's certainly equal */
1193 if (val->typ == VM_OBJ && val->val.obj == self)
1194 return TRUE;
1195
1196 /* if it's not another byte array, it's not equal */
1197 if (val->typ != VM_OBJ || !is_byte_array(vmg_ val->val.obj))
1198 return FALSE;
1199
1200 /* we know it's another byte array - cast it */
1201 other = (CVmObjByteArray *)vm_objp(vmg_ val->val.obj);
1202
1203 /* if it's not of the same length, it's not equal */
1204 if (other->get_element_count() != get_element_count())
1205 return FALSE;
1206
1207 /* compare the arrays */
1208 for (idx = 1, rem = get_element_count() ; rem != 0 ; )
1209 {
1210 unsigned char *p1;
1211 unsigned char *p2;
1212 size_t avail1;
1213 size_t avail2;
1214 size_t chunk;
1215
1216 /* get the next chunk of each array */
1217 p1 = get_ele_ptr(idx, &avail1);
1218 p2 = other->get_ele_ptr(idx, &avail2);
1219
1220 /* if the chunk sizes aren't the same, there's some problem */
1221 assert(avail1 == avail2);
1222
1223 /* limit the chunk size to the remaining size */
1224 chunk = avail1;
1225 if (chunk > rem)
1226 chunk = (size_t)rem;
1227
1228 /* if the chunks differ, the arrays differ */
1229 if (memcmp(p1, p2, chunk) != 0)
1230 return FALSE;
1231
1232 /* advance past the chunk */
1233 idx += avail1;
1234 rem -= avail1;
1235 }
1236
1237 /* we found no differences */
1238 return TRUE;
1239 }
1240
1241 /*
1242 * Calculate a hash value
1243 */
1244 uint CVmObjByteArray::calc_hash(VMG_ vm_obj_id_t self, int /*depth*/) const
1245 {
1246 unsigned long idx;
1247 unsigned long rem;
1248 uint hash;
1249
1250 /* add up the bytes in the array */
1251 for (hash = 0, idx = 1, rem = get_element_count() ; rem != 0 ; )
1252 {
1253 unsigned char *p;
1254 size_t avail;
1255 size_t chunk;
1256
1257 /* get the next chunk */
1258 p = get_ele_ptr(idx, &avail);
1259
1260 /* limit the chunk size to the remaining size */
1261 chunk = avail;
1262 if (chunk > rem)
1263 chunk = (size_t)rem;
1264
1265 /* advance our counters for this chunk */
1266 idx += chunk;
1267 rem -= chunk;
1268
1269 /* add up the bytes in this part */
1270 for ( ; chunk != 0 ; --chunk, ++p)
1271 hash += *p;
1272 }
1273
1274 /* return the result */
1275 return hash;
1276 }
1277
1278 /* ------------------------------------------------------------------------ */
1279 /*
1280 * Copy bytes from an array
1281 */
1282 void CVmObjByteArray::copy_from(unsigned long dst_idx,
1283 CVmObjByteArray *src_arr,
1284 unsigned long src_idx,
1285 unsigned long cnt)
1286 {
1287 /* if we're moving zero bytes, there's nothing to do */
1288 if (cnt == 0)
1289 return;
1290
1291 /* make sure we don't overrun our array */
1292 if (dst_idx > get_element_count())
1293 cnt = 0;
1294 else if (dst_idx + cnt - 1 > get_element_count())
1295 cnt = get_element_count() + 1 - dst_idx;
1296
1297 /*
1298 * If the source and destination objects are the same, and the source
1299 * and destination regions overlap, we must take care to move the
1300 * bytes in such a way that we don't overwrite parts of the source in
1301 * the course of moving the bytes.
1302 */
1303 if (src_arr == this
1304 && src_idx + cnt - 1 >= dst_idx && src_idx <= dst_idx + cnt - 1)
1305 {
1306 /* the regions overlap - use the overlap-safe move routine */
1307 move_bytes(dst_idx, src_idx, cnt);
1308
1309 /* done */
1310 return;
1311 }
1312
1313 /* continue until we exhaust the count */
1314 while (cnt != 0)
1315 {
1316 size_t src_avail;
1317 size_t src_chunk_size;
1318 unsigned char *srcp;
1319
1320 /* if we're past the end of the source array, stop copying */
1321 if (src_idx > src_arr->get_element_count())
1322 break;
1323
1324 /* get the next source chunk */
1325 srcp = src_arr->get_ele_ptr(src_idx, &src_avail);
1326
1327 /* limit this chunk size to the remaining copy size */
1328 src_chunk_size = src_avail;
1329 if (src_chunk_size > cnt)
1330 src_chunk_size = (size_t)cnt;
1331
1332 /* limit this chunk to the remaining source array size */
1333 if (src_idx + src_chunk_size - 1 > src_arr->get_element_count())
1334 src_chunk_size = src_arr->get_element_count() + 1 - src_idx;
1335
1336 /* copy this chunk into the destination */
1337 copy_from_buf(srcp, dst_idx, src_chunk_size);
1338
1339 /* move past this chunk in the source */
1340 cnt -= src_chunk_size;
1341 src_idx += src_chunk_size;
1342
1343 /* move past this chunk in the destination */
1344 dst_idx += src_chunk_size;
1345 }
1346
1347 /*
1348 * if there's any copying size left, we ran out of source array bytes
1349 * - fill the balance of the destination array with zeros
1350 */
1351 if (cnt != 0)
1352 fill_with(0, dst_idx, cnt);
1353 }
1354
1355 /*
1356 * Move bytes within our array. This is safe even if the source and
1357 * destination regions overlap.
1358 */
1359 void CVmObjByteArray::move_bytes(unsigned long dst_idx,
1360 unsigned long src_idx,
1361 unsigned long cnt)
1362 {
1363 size_t src_avail;
1364 size_t dst_avail;
1365 unsigned char *srcp;
1366 unsigned char *dstp;
1367
1368 /*
1369 * If the destination is before the source, we're moving bytes down,
1370 * so we must start at the low end and work forwards through the
1371 * array. If the destination is after the source, we're moving bytes
1372 * up, so we must start at the high end and work backwards through the
1373 * array.
1374 */
1375 if (dst_idx < src_idx)
1376 {
1377
1378 /*
1379 * Moving bytes down in the array - start at the low end and work
1380 * forwards through the array. Get the starting pointers and
1381 * available lengths.
1382 */
1383 srcp = get_ele_ptr(src_idx, &src_avail);
1384 dstp = get_ele_ptr(dst_idx, &dst_avail);
1385
1386 /* keep going until we've moved all of the bytes requested */
1387 while (cnt != 0)
1388 {
1389 size_t move_len;
1390
1391 /*
1392 * figure the largest amount we can move - we can move the
1393 * smallest of the remaining requested move size, the source
1394 * chunk, and the destination chunk
1395 */
1396 move_len = cnt;
1397 if (move_len > src_avail)
1398 move_len = src_avail;
1399 if (move_len > dst_avail)
1400 move_len = dst_avail;
1401
1402 /* move the data */
1403 memmove(dstp, srcp, move_len);
1404
1405 /* advance all of the counters by the move size */
1406 srcp += move_len;
1407 dstp += move_len;
1408 cnt -= move_len;
1409 src_avail -= move_len;
1410 dst_avail -= move_len;
1411 src_idx += move_len;
1412 dst_idx += move_len;
1413
1414 /* stop if we're done */
1415 if (cnt == 0)
1416 break;
1417
1418 /* if the source chunk is at an end, get the next one */
1419 if (src_avail == 0)
1420 srcp = get_ele_ptr(src_idx, &src_avail);
1421
1422 /* if the destination chunk is at an end, get the next one */
1423 if (dst_avail == 0)
1424 dstp = get_ele_ptr(dst_idx, &dst_avail);
1425 }
1426 }
1427 else
1428 {
1429 /*
1430 * We're to move bytes up in the array - start at the high end and
1431 * work backwards through the array. Advance each index to one
1432 * past the last byte of its range.
1433 */
1434 src_idx += cnt;
1435 dst_idx += cnt;
1436
1437 /* get the chunk pointers */
1438 srcp = get_ele_ptr(src_idx - 1, &src_avail) + 1;
1439 dstp = get_ele_ptr(dst_idx - 1, &dst_avail) + 1;
1440
1441 /*
1442 * since we're working backwards, we actually want to know the
1443 * number of bytes on the page *before* the current pointers, so
1444 * subtract the available spaces from the size of the page to get
1445 * the available space preceding each
1446 */
1447 src_avail = 32*1024 - src_avail + 1;
1448 dst_avail = 32*1024 - dst_avail + 1;
1449
1450 /* keep going until we've moved all of the requested bytes */
1451 while (cnt != 0)
1452 {
1453 size_t move_len;
1454
1455 /*
1456 * figure the largest amount we can move - we can move the
1457 * smallest of the remaining requested move size, the source
1458 * chunk, and the destination chunk
1459 */
1460 move_len = cnt;
1461 if (move_len > src_avail)
1462 move_len = src_avail;
1463 if (move_len > dst_avail)
1464 move_len = dst_avail;
1465
1466 /* move the data */
1467 memmove(dstp - move_len, srcp - move_len, move_len);
1468
1469 /* advance all of the counters by the move size */
1470 srcp -= move_len;
1471 dstp -= move_len;
1472 cnt -= move_len;
1473 src_avail -= move_len;
1474 dst_avail -= move_len;
1475 src_idx -= move_len;
1476 dst_idx -= move_len;
1477
1478 /* stop if we're done */
1479 if (cnt == 0)
1480 break;
1481
1482 /* if we've exhausted the source chunk, get the next one */
1483 if (src_avail == 0)
1484 {
1485 srcp = get_ele_ptr(src_idx - 1, &src_avail) + 1;
1486 src_avail = 32*1024 - src_avail + 1;
1487 }
1488
1489 /* if we've exhausted the destination chunk, get the next one */
1490 if (dst_avail == 0)
1491 {
1492 dstp = get_ele_ptr(dst_idx - 1, &dst_avail) + 1;
1493 dst_avail = 32*1024 - dst_avail + 1;
1494 }
1495 }
1496 }
1497 }
1498
1499 /* ------------------------------------------------------------------------ */
1500 /*
1501 * Fill a 1-based index range with the given value
1502 */
1503 void CVmObjByteArray::fill_with(unsigned char val, unsigned long start_idx,
1504 unsigned long cnt)
1505 {
1506 unsigned long idx;
1507 unsigned long rem;
1508
1509 /* ensure we don't overrun the array */
1510 if (start_idx > get_element_count())
1511 cnt = 0;
1512 else if (start_idx + cnt - 1 > get_element_count())
1513 cnt = get_element_count() + 1 - start_idx;
1514
1515 /* continue until we exhaust the count */
1516 for (idx = start_idx, rem = cnt ; rem != 0 ; )
1517 {
1518 size_t avail;
1519 size_t chunk_size;
1520 unsigned char *p;
1521
1522 /* get the next chunk */
1523 p = get_ele_ptr(idx, &avail);
1524
1525 /* limit this chunk size to the remaining size to fill */
1526 chunk_size = avail;
1527 if (chunk_size > rem)
1528 chunk_size = (size_t)rem;
1529
1530 /* fill this chunk */
1531 memset(p, val, chunk_size);
1532
1533 /* skip this chunk */
1534 rem -= chunk_size;
1535 idx += chunk_size;
1536 }
1537 }
1538
1539 /* ------------------------------------------------------------------------ */
1540 /*
1541 * property evaluator - length
1542 */
1543 int CVmObjByteArray::getp_length(VMG_ vm_obj_id_t self,
1544 vm_val_t *retval, uint *argc)
1545 {
1546 static CVmNativeCodeDesc desc(0);
1547
1548 /* check arguments */
1549 if (get_prop_check_argc(retval, argc, &desc))
1550 return TRUE;
1551
1552 /* return the length */
1553 retval->set_int(get_element_count());
1554
1555 /* handled */
1556 return TRUE;
1557 }
1558
1559 /*
1560 * property evaluator - subarray
1561 */
1562 int CVmObjByteArray::getp_subarray(VMG_ vm_obj_id_t self,
1563 vm_val_t *retval, uint *in_argc)
1564 {
1565 uint argc = (in_argc != 0 ? *in_argc : 0);
1566 static CVmNativeCodeDesc desc(1, 1);
1567 unsigned long idx;
1568 unsigned long cnt;
1569 CVmObjByteArray *arr;
1570
1571 /* check arguments */
1572 if (get_prop_check_argc(retval, in_argc, &desc))
1573 return TRUE;
1574
1575 /* get the starting index */
1576 idx = CVmBif::pop_int_val(vmg0_);
1577
1578 /* force it to be in range */
1579 if (idx < 1)
1580 idx = 1;
1581 else if (idx > get_element_count() + 1)
1582 idx = get_element_count() + 1;
1583
1584 /* if there's a count, get it */
1585 if (argc >= 2)
1586 {
1587 /* get the explicit count */
1588 cnt = CVmBif::pop_int_val(vmg0_);
1589 }
1590 else
1591 {
1592 /* use the entire rest of the array */
1593 cnt = get_element_count();
1594 }
1595
1596 /* limit the count to the available size */
1597 if (idx > get_element_count())
1598 cnt = 0;
1599 else if (idx + cnt - 1 > get_element_count())
1600 cnt = get_element_count() + 1 - idx;
1601
1602 /* push a self-reference while we're working for gc protection */
1603 G_stk->push()->set_obj(self);
1604
1605 /* allocate a new array to hold the result */
1606 retval->set_obj(create(vmg_ FALSE, cnt));
1607 arr = (CVmObjByteArray *)vm_objp(vmg_ retval->val.obj);
1608
1609 /* copy the data from our array into the new one */
1610 arr->copy_from(1, this, idx, cnt);
1611
1612 /* discard our self-reference */
1613 G_stk->discard();
1614
1615 /* handled */
1616 return TRUE;
1617 }
1618
1619 /*
1620 * property evaluator - copy from another byte array
1621 */
1622 int CVmObjByteArray::getp_copy_from(VMG_ vm_obj_id_t self,
1623 vm_val_t *retval, uint *argc)
1624 {
1625 static CVmNativeCodeDesc desc(4);
1626 unsigned long dst_idx;
1627 unsigned long src_idx;
1628 unsigned long cnt;
1629 vm_obj_id_t src_arr_id;
1630 CVmObjByteArray *src_arr;
1631
1632 /* check arguments */
1633 if (get_prop_check_argc(retval, argc, &desc))
1634 return TRUE;
1635
1636 /* get the source array */
1637 src_arr_id = CVmBif::pop_obj_val(vmg0_);
1638
1639 /* make sure it is indeed an array */
1640 if (!is_byte_array(vmg_ src_arr_id))
1641 err_throw(VMERR_BAD_TYPE_BIF);
1642
1643 /* we know it's the right type, so cast it */
1644 src_arr = (CVmObjByteArray *)vm_objp(vmg_ src_arr_id);
1645
1646 /* get the starting source index */
1647 src_idx = CVmBif::pop_int_val(vmg0_);
1648
1649 /* force it to be in range */
1650 if (src_idx < 1)
1651 src_idx = 1;
1652 else if (src_idx > src_arr->get_element_count() + 1)
1653 src_idx = src_arr->get_element_count() + 1;
1654
1655 /* get the destination index */
1656 dst_idx = CVmBif::pop_int_val(vmg0_);
1657
1658 /* force it to be within range */
1659 if (dst_idx < 1)
1660 dst_idx = 1;
1661 else if (dst_idx > get_element_count() + 1)
1662 dst_idx = get_element_count() + 1;
1663
1664 /* get the count */
1665 cnt = CVmBif::pop_int_val(vmg0_);
1666
1667 /* limit the copying to the available destination space */
1668 if (dst_idx > get_element_count())
1669 cnt = 0;
1670 else if (dst_idx + cnt - 1 > get_element_count())
1671 cnt = get_element_count() + 1 - dst_idx;
1672
1673 /* save undo for the change */
1674 save_undo(vmg_ self, dst_idx, cnt);
1675
1676 /* copy the data from the source array into our array */
1677 copy_from(dst_idx, src_arr, src_idx, cnt);
1678
1679 /* the result is 'self' */
1680 retval->set_obj(self);
1681
1682 /* handled */
1683 return TRUE;
1684 }
1685
1686 /*
1687 * property evaluator - fill with a value
1688 */
1689 int CVmObjByteArray::getp_fill_val(VMG_ vm_obj_id_t self,
1690 vm_val_t *retval, uint *in_argc)
1691 {
1692 uint argc = (in_argc != 0 ? *in_argc : 0);
1693 static CVmNativeCodeDesc desc(1, 2);
1694 unsigned long idx;
1695 unsigned long cnt;
1696 long fill_val;
1697
1698 /* check arguments */
1699 if (get_prop_check_argc(retval, in_argc, &desc))
1700 return TRUE;
1701
1702 /* get the value with which to fill elements */
1703 fill_val = CVmBif::pop_int_val(vmg0_);
1704 if (fill_val < 0 || fill_val > 255)
1705 err_throw(VMERR_OUT_OF_RANGE);
1706
1707 /* get the starting index, if provided */
1708 if (argc >= 2)
1709 {
1710 /* get the index */
1711 idx = CVmBif::pop_int_val(vmg0_);
1712
1713 /* force it to be in range */
1714 if (idx < 1)
1715 idx = 1;
1716 else if (idx > get_element_count() + 1)
1717 idx = get_element_count() + 1;
1718 }
1719 else
1720 {
1721 /* fill from the first element */
1722 idx = 1;
1723 }
1724
1725 /* get the count, if provided */
1726 if (argc >= 3)
1727 {
1728 /* get the count */
1729 cnt = CVmBif::pop_int_val(vmg0_);
1730 }
1731 else
1732 {
1733 /* fill the entire array */
1734 cnt = get_element_count();
1735 }
1736
1737 /* force the length to be in range */
1738 if (idx > get_element_count())
1739 cnt = 0;
1740 else if (idx + cnt - 1 > get_element_count())
1741 cnt = get_element_count() + 1 - idx;
1742
1743 /* save undo for the change */
1744 save_undo(vmg_ self, idx, cnt);
1745
1746 /* fill with the given value */
1747 fill_with((unsigned char)fill_val, idx, cnt);
1748
1749 /* the result is 'self' */
1750 retval->set_obj(self);
1751
1752 /* handled */
1753 return TRUE;
1754 }
1755
1756 /*
1757 * property evaluator - convert to string
1758 */
1759 int CVmObjByteArray::getp_to_string(VMG_ vm_obj_id_t self,
1760 vm_val_t *retval, uint *in_argc)
1761 {
1762 uint argc = (in_argc != 0 ? *in_argc : 0);
1763 static CVmNativeCodeDesc desc(0, 3);
1764 unsigned long idx;
1765 unsigned long cnt;
1766 vm_val_t charset;
1767 CCharmapToUni *mapper = 0;
1768 size_t str_len;
1769 CVmObjString *str;
1770
1771 /* check arguments */
1772 if (get_prop_check_argc(retval, in_argc, &desc))
1773 return TRUE;
1774
1775 /* get the character set object */
1776 charset.set_nil();
1777 if (argc >= 1)
1778 charset.set_obj_or_nil(CVmBif::pop_charset_obj(vmg0_));
1779
1780 /* if we got a CharacterSet, get its to-unicode mapper */
1781 if (charset.typ != VM_NIL)
1782 mapper = ((CVmObjCharSet *)vm_objp(vmg_ charset.val.obj))
1783 ->get_to_uni(vmg0_);
1784
1785 /* if there's a starting index, retrieve it */
1786 if (argc >= 2)
1787 {
1788 /* retrieve the starting index */
1789 idx = CVmBif::pop_int_val(vmg0_);
1790
1791 /* force it to be in range */
1792 if (idx < 1)
1793 idx = 1;
1794 else if (idx > get_element_count() + 1)
1795 idx = get_element_count() + 1;
1796 }
1797 else
1798 {
1799 /* start at the first byte */
1800 idx = 1;
1801 }
1802
1803 /* if there's a length, retrieve it */
1804 if (argc >= 3)
1805 {
1806 /* retrieve the length */
1807 cnt = CVmBif::pop_int_val(vmg0_);
1808 }
1809 else
1810 {
1811 /* use all remaining characters */
1812 cnt = get_element_count();
1813 }
1814
1815 /* force the length to be in range */
1816 if (idx > get_element_count())
1817 cnt = 0;
1818 else if (idx + cnt - 1 > get_element_count())
1819 cnt = get_element_count() + 1 - idx;
1820
1821 /* push a self-ref for gc protection, and a ref to the character set */
1822 G_stk->push()->set_obj(self);
1823 G_stk->push(&charset);
1824
1825 /* map via the character mapper, or as raw unicode character values */
1826 if (mapper != 0)
1827 {
1828 /*
1829 * We have a character set mapper. First, measure the required
1830 * buffer length by mapping to a null buffer.
1831 */
1832 str_len = map_to_string(idx, cnt, 0, 0, mapper);
1833
1834 /* allocate a string of the required length */
1835 retval->set_obj(CVmObjString::create(vmg_ FALSE, str_len));
1836 str = (CVmObjString *)vm_objp(vmg_ retval->val.obj);
1837
1838 /* map the string, actually storing the bytes this time */
1839 map_to_string(idx, cnt, str, str_len, mapper);
1840 }
1841 else
1842 {
1843 /* there's no mapper - treat our bytes as unicode character codes */
1844 CVmByteArraySource src(vmg_ self, idx - 1, cnt);
1845 retval->set_obj(CVmObjString::create_latin1(vmg_ FALSE, &src));
1846 }
1847
1848 /* discard the gc protection */
1849 G_stk->discard(2);
1850
1851 /* handled */
1852 return TRUE;
1853 }
1854
1855 /*
1856 * Run a range of bytes through a character mapper to produce string data,
1857 * optionally storing the string data in a string object. Returns the
1858 * number of bytes in the resulting string.
1859 */
1860 size_t CVmObjByteArray::map_to_string(unsigned long idx,
1861 unsigned long len,
1862 CVmObjString *str, size_t str_len,
1863 CCharmapToUni *mapper)
1864 {
1865 size_t str_total;
1866 size_t buf_len;
1867 unsigned char buf[128];
1868 char *dst;
1869
1870 /* get the string's buffer pointer */
1871 dst = (str != 0 ? str->cons_get_buf() : 0);
1872
1873 /* go through the source bytes a bit at a time */
1874 for (str_total = 0, buf_len = 0 ; len != 0 ; )
1875 {
1876 size_t copy_len;
1877 size_t str_cur;
1878 size_t partial_len;
1879
1880 /*
1881 * fill up the buffer, up to the remaining source length or the
1882 * buffer's capacity, whichever is lower
1883 */
1884 copy_len = sizeof(buf) - buf_len;
1885 if (copy_len > len)
1886 copy_len = (size_t)len;
1887
1888 /* copy the bytes to our staging buffer */
1889 copy_to_buf(buf, idx, copy_len);
1890
1891 /* add the copied bytes into the buffer length */
1892 buf_len += copy_len;
1893
1894 /* advance past the copied bytes in the source */
1895 idx += copy_len;
1896 len -= copy_len;
1897
1898 /* translate the bytes through the character set mapping */
1899 str_cur = mapper->map2(&dst, &str_len, (char *)buf, buf_len,
1900 &partial_len);
1901
1902 /*
1903 * if this would push us over the maximum string size, we can't
1904 * convert the data
1905 */
1906 if (str_cur > OSMALMAX - str_total - VMB_LEN)
1907 err_throw(VMERR_OUT_OF_MEMORY);
1908
1909 /* add the current length into the total string length */
1910 str_total += str_cur;
1911
1912 /* copy the partial last character bytes to the start of the buffer */
1913 if (partial_len != 0)
1914 memmove(buf, buf + buf_len - partial_len, partial_len);
1915
1916 /* the buffer now contains only the partial character bytes */
1917 buf_len = partial_len;
1918 }
1919
1920 /* return the total string length */
1921 return str_total;
1922 }
1923
1924 /*
1925 * Copy bytes from the array to a buffer
1926 */
1927 size_t CVmObjByteArray::copy_to_buf(unsigned char *buf,
1928 unsigned long idx, size_t len) const
1929 {
1930 /* we haven't copied any bytes so far */
1931 size_t actual = 0;
1932
1933 /* limit it to the actual available space */
1934 unsigned long contlen = get_element_count();
1935 if (idx > contlen)
1936 len = 0;
1937 else if (idx + len > contlen)
1938 len = contlen - idx + 1;
1939
1940 /* keep going until we satisfy the request */
1941 while (len != 0)
1942 {
1943 size_t avail;
1944 unsigned char *p;
1945 size_t copy_len;
1946
1947 /* get the next chunk */
1948 p = get_ele_ptr(idx, &avail);
1949
1950 /* if there's nothing left, stop */
1951 if (avail == 0)
1952 break;
1953
1954 /* copy the available bytes or the reamining desired bytes */
1955 copy_len = avail;
1956 if (copy_len > len)
1957 copy_len = len;
1958
1959 /* copy the bytes */
1960 memcpy(buf, p, copy_len);
1961
1962 /* advance past the copied bytes */
1963 buf += copy_len;
1964 idx += copy_len;
1965 len -= copy_len;
1966 actual += copy_len;
1967 }
1968
1969 /* return the actual size copied */
1970 return actual;
1971 }
1972
1973 /*
1974 * Copy bytes from a buffer into the array, saving undo
1975 */
1976 size_t CVmObjByteArray::copy_from_buf_undo(VMG_ vm_obj_id_t self,
1977 const unsigned char *buf,
1978 unsigned long idx, size_t len)
1979 {
1980 /* limit the size to the remaining length from 'idx' */
1981 unsigned long avail_len = get_element_count() - idx + 1;
1982 if (len > avail_len)
1983 len = (size_t)avail_len;
1984
1985 /* save undo */
1986 save_undo(vmg_ self, idx, len);
1987
1988 /* copy the bytes */
1989 copy_from_buf(buf, idx, len);
1990
1991 /* return the copy length */
1992 return len;
1993 }
1994
1995 /*
1996 * Copy bytes from a buffer into the array
1997 */
1998 void CVmObjByteArray::copy_from_buf(const unsigned char *buf,
1999 unsigned long idx, size_t len)
2000 {
2001 /* keep going until we satisfy the request */
2002 while (len != 0)
2003 {
2004 size_t avail;
2005 unsigned char *p;
2006 size_t copy_len;
2007
2008 /* get the next chunk */
2009 p = get_ele_ptr(idx, &avail);
2010
2011 /* copy the available bytes or the remaining desired bytes */
2012 copy_len = avail;
2013 if (copy_len > len)
2014 copy_len = len;
2015
2016 /* copy the bytes */
2017 memcpy(p, buf, copy_len);
2018
2019 /* advance past the copied bytes */
2020 buf += copy_len;
2021 idx += copy_len;
2022 len -= copy_len;
2023 }
2024 }
2025
2026 /* ------------------------------------------------------------------------ */
2027 /*
2028 * Swap byte order
2029 */
2030 static void swap_bytes(unsigned char *buf, int len)
2031 {
2032 int i, j;
2033 for (i = 0, j = len - 1 ; i < j ; ++i, --j)
2034 {
2035 unsigned char tmp = buf[i];
2036 buf[i] = buf[j];
2037 buf[j] = tmp;
2038 }
2039 }
2040
2041 /* ------------------------------------------------------------------------ */
2042 /*
2043 * property evaluator - read an integer
2044 */
2045 int CVmObjByteArray::getp_read_int(VMG_ vm_obj_id_t self,
2046 vm_val_t *retval, uint *argc)
2047 {
2048 static CVmNativeCodeDesc desc(2);
2049 unsigned int idx;
2050 unsigned int fmt;
2051 long result = 0;
2052 size_t siz;
2053 unsigned char cbuf[4];
2054
2055 /* check arguments */
2056 if (get_prop_check_argc(retval, argc, &desc))
2057 return TRUE;
2058
2059 /* get the starting index and format code */
2060 idx = CVmBif::pop_int_val(vmg0_);
2061 fmt = CVmBif::pop_int_val(vmg0_);
2062
2063 /* get the size from the format */
2064 switch (fmt & FmtSizeMask)
2065 {
2066 case FmtInt8:
2067 default:
2068 siz = 1;
2069 break;
2070
2071 case FmtInt16:
2072 siz = 2;
2073 break;
2074
2075 case FmtInt32:
2076 siz = 4;
2077 break;
2078 }
2079
2080 /* check that the index is in range */
2081 if (idx < 1 || idx + siz - 1 > get_element_count())
2082 err_throw(VMERR_INDEX_OUT_OF_RANGE);
2083
2084 /* make a copy of the bytes in cbuf[] for easy access */
2085 copy_to_buf(cbuf, idx, siz);
2086
2087 /* read the value */
2088 switch (siz)
2089 {
2090 case 1:
2091 /* 8-bit integer - all that matters is the signedness */
2092 if ((fmt & FmtSignedMask) == FmtSigned)
2093 result = (long)(int)(char)cbuf[0];
2094 else
2095 result = cbuf[0];
2096 break;
2097
2098 case 2:
2099 /*
2100 * 16-bit integer. Our standard portable order is little-endian,
2101 * so swap bytes if it's big-endian.
2102 */
2103 if ((fmt & FmtOrderMask) == FmtBigEndian)
2104 swap_bytes(cbuf, 2);
2105
2106 /* it's little-endian now, so pull out the signed or unsigned value */
2107 if ((fmt & FmtSignedMask) == FmtSigned)
2108 result = osrp2s(cbuf);
2109 else
2110 result = osrp2(cbuf);
2111
2112 break;
2113
2114 case 4:
2115 /*
2116 * 32-bit integer. Convert to our standard little-endian ordering
2117 * if it's currently big-endian, by swapping the byte order.
2118 */
2119 if ((fmt & FmtOrderMask) == FmtBigEndian)
2120 swap_bytes(cbuf, 4);
2121
2122 /* it's little-endian now, so pull out the signed or unsigned value */
2123 if ((fmt & FmtSignedMask) == FmtSigned)
2124 result = osrp4s(cbuf);
2125 else
2126 result = osrp4(cbuf);
2127 break;
2128 }
2129
2130 /* return the result */
2131 retval->set_int(result);
2132
2133 /* handled */
2134 return TRUE;
2135 }
2136
2137 /*
2138 * property evaluator - write an integer
2139 */
2140 int CVmObjByteArray::getp_write_int(VMG_ vm_obj_id_t self,
2141 vm_val_t *retval, uint *argc)
2142 {
2143 static CVmNativeCodeDesc desc(3);
2144 unsigned int idx;
2145 unsigned int fmt;
2146 long val;
2147 size_t siz;
2148 unsigned char cbuf[4];
2149
2150 /* check arguments */
2151 if (get_prop_check_argc(retval, argc, &desc))
2152 return TRUE;
2153
2154 /* get the starting index, format code, and value to write */
2155 idx = CVmBif::pop_int_val(vmg0_);
2156 fmt = CVmBif::pop_int_val(vmg0_);
2157 val = CVmBif::pop_long_val(vmg0_);
2158
2159 /* get the size from the format */
2160 switch (fmt & FmtSizeMask)
2161 {
2162 case FmtInt8:
2163 default:
2164 siz = 1;
2165 break;
2166
2167 case FmtInt16:
2168 siz = 2;
2169 break;
2170
2171 case FmtInt32:
2172 siz = 4;
2173 break;
2174 }
2175
2176 /* check that the index is in range */
2177 if (idx < 1 || idx + siz - 1 > get_element_count())
2178 err_throw(VMERR_INDEX_OUT_OF_RANGE);
2179
2180 /* write the value to cbuf[] */
2181 switch (siz)
2182 {
2183 case 1:
2184 /* 8-bit integer */
2185 cbuf[0] = (char)(val & 0xFF);
2186 break;
2187
2188 case 2:
2189 /* 16-bit integer - start with our standard little-endian format */
2190 if ((fmt & FmtSignedMask) == FmtSigned)
2191 oswp2s(cbuf, (int)val);
2192 else
2193 oswp2(cbuf, (int)val);
2194 break;
2195
2196 case 4:
2197 /* 32-bit integer - start with our standard little-endian format */
2198 if ((fmt & FmtSignedMask) == FmtSigned)
2199 oswp4s(cbuf, val);
2200 else
2201 oswp4(cbuf, val);
2202 break;
2203 }
2204
2205 /* swap bytes if they want big-endian */
2206 if (siz > 1 && (fmt & FmtOrderMask) == FmtBigEndian)
2207 swap_bytes(cbuf, siz);
2208
2209 /* save undo for the change */
2210 save_undo(vmg_ self, idx, siz);
2211
2212 /* store the byte representation we've constructed */
2213 copy_from_buf(cbuf, idx, siz);
2214
2215 /* there's no return value */
2216 retval->set_nil();
2217
2218 /* handled */
2219 return TRUE;
2220 }
2221
2222
2223
2224 /* ------------------------------------------------------------------------ */
2225 /*
2226 * Write bytes from the specified region of the array to a file. Returns
2227 * zero on success, non-zero on failure.
2228 */
2229 int CVmObjByteArray::write_to_file(CVmDataSource *fp, unsigned long start_idx,
2230 unsigned long len) const
2231 {
2232 unsigned long rem;
2233 unsigned long idx;
2234
2235 /* make sure the starting index is valid */
2236 if (start_idx < 1)
2237 err_throw(VMERR_INDEX_OUT_OF_RANGE);
2238
2239 /*
2240 * if the starting index is past the end of the array, there's nothing
2241 * to do - just return success
2242 */
2243 if (start_idx > get_element_count())
2244 return 0;
2245
2246 /*
2247 * limit the request to the number of bytes available after the
2248 * starting index
2249 */
2250 if (start_idx + len - 1 > get_element_count())
2251 len = get_element_count() - start_idx + 1;
2252
2253 /* keep going until we satisfy the request or run into a problem */
2254 for (idx = start_idx, rem = len ; rem != 0 ; )
2255 {
2256 unsigned char *p;
2257 size_t avail;
2258 size_t chunk;
2259
2260 /* get the next chunk */
2261 p = get_ele_ptr(idx, &avail);
2262
2263 /* limit writing to the amount remaining of the requested size */
2264 chunk = avail;
2265 if (chunk > rem)
2266 chunk = (size_t)rem;
2267
2268 /*
2269 * write out this chunk - if an error occurs, abort with a failure
2270 * indication
2271 */
2272 if (fp->write(p, chunk))
2273 return 1;
2274
2275 /* move our counters past this chunk */
2276 idx += chunk;
2277 rem -= chunk;
2278 }
2279
2280 /* we satisfied the request without problems - indicate success */
2281 return 0;
2282 }
2283
2284 /*
2285 * Read bytes from the file into the specified region of the array.
2286 * Returns the number of bytes actually read.
2287 */
2288 unsigned long CVmObjByteArray::read_from_file(
2289 VMG_ vm_obj_id_t self, CVmDataSource *fp,
2290 unsigned long start_idx, unsigned long len, int undo)
2291 {
2292 unsigned long rem;
2293 unsigned long idx;
2294 unsigned long total;
2295
2296 /* make sure the starting index is at least 1 */
2297 if (start_idx < 1)
2298 err_throw(VMERR_INDEX_OUT_OF_RANGE);
2299
2300 /*
2301 * if the starting index is past the end of the array, there's nothing
2302 * to do - just return success
2303 */
2304 if (start_idx > get_element_count())
2305 return 0;
2306
2307 /* if the requested length is zero, consider it a success */
2308 if (len == 0)
2309 return 0;
2310
2311 /*
2312 * limit the request to the number of bytes available after the
2313 * starting index
2314 */
2315 if (start_idx + len - 1 > get_element_count())
2316 len = get_element_count() - start_idx + 1;
2317
2318 /* save undo */
2319 if (undo)
2320 save_undo(vmg_ self, start_idx, len);
2321
2322 /* keep going until we satisfy the request or run into a problem */
2323 for (idx = start_idx, rem = len, total = 0 ; rem != 0 ; )
2324 {
2325 unsigned char *p;
2326 size_t avail;
2327 size_t chunk;
2328 size_t cur_read;
2329
2330 /* get the next chunk */
2331 p = get_ele_ptr(idx, &avail);
2332
2333 /* limit reading to the amount of the request remaining */
2334 chunk = avail;
2335 if (chunk > rem)
2336 chunk = (size_t)rem;
2337
2338 /* read as much as we can of this chunk */
2339 cur_read = fp->readc(p, chunk);
2340
2341 /* add this amount into the total so far */
2342 total += cur_read;
2343
2344 /*
2345 * if we didn't get as much as we asked for, we must have reached
2346 * the end of the file before satisfying the request - there's
2347 * nothing more to be read in this case, so we can stop looping
2348 */
2349 if (cur_read != chunk)
2350 break;
2351
2352 /* move our counters past this chunk */
2353 idx += chunk;
2354 rem -= chunk;
2355 }
2356
2357 /* return the total amount we read */
2358 return total;
2359 }
2360
2361 /* ------------------------------------------------------------------------ */
2362 /*
2363 * Write to a 'data' mode file
2364 */
2365 int CVmObjByteArray::write_to_data_file(CVmDataSource *fp)
2366 {
2367 char buf[16];
2368
2369 /* write the number of bytes in our array */
2370 oswp4(buf, get_element_count());
2371 if (fp->write(buf, 4))
2372 return 1;
2373
2374 /* write the bytes */
2375 return write_to_file(fp, 1, get_element_count());
2376 }
2377
2378 /*
2379 * Read from a 'data' mode file
2380 */
2381 int CVmObjByteArray::read_from_data_file(VMG_ vm_val_t *retval,
2382 CVmDataSource *fp)
2383 {
2384 char buf[16];
2385 CVmObjByteArray *arr;
2386 unsigned long len;
2387
2388 /* read the number of bytes in the array */
2389 if (fp->read(buf, 4))
2390 return 1;
2391 len = t3rp4u(buf);
2392
2393 /* create a new ByteArray to hold the result */
2394 retval->set_obj(create(vmg_ FALSE, len));
2395 arr = (CVmObjByteArray *)vm_objp(vmg_ retval->val.obj);
2396
2397 /* read the bytes (it's a new object, so don't save undo) */
2398 if (arr->read_from_file(vmg_ retval->val.obj, fp, 1, len, FALSE) != len)
2399 {
2400 /*
2401 * we didn't manage to read all of the bytes - since the value was
2402 * tagged with the correct number of bytes, end-of-file in the
2403 * middle of the bytes indicates a corrupted file, so return
2404 * failure
2405 */
2406 return 1;
2407 }
2408
2409 /* success */
2410 return 0;
2411 }
2412
2413 /* ------------------------------------------------------------------------ */
2414 /*
2415 * property evaluator - packBytes
2416 */
2417 int CVmObjByteArray::getp_packBytes(
2418 VMG_ vm_obj_id_t self, vm_val_t *retval, uint *oargc)
2419 {
2420 /* check arguments */
2421 uint argc = oargc != 0 ? *oargc : 0;
2422 static CVmNativeCodeDesc desc(2, 0, TRUE);
2423 if (get_prop_check_argc(retval, oargc, &desc))
2424 return TRUE;
2425
2426 /* retrieve the starting index from the first argument */
2427 long idx = CVmBif::pop_long_val(vmg0_);
2428 --argc;
2429
2430 /* limit the index to 1..length */
2431 if (idx < 1)
2432 idx = 1;
2433 else if ((ulong)idx > get_element_count())
2434 idx = get_element_count();
2435
2436 /* adjust to a zero-based index */
2437 --idx;
2438
2439 /* set up a data source for the byte array */
2440 CVmByteArraySource dst(vmg_ self);
2441
2442 /* seek to the starting index */
2443 dst.seek(idx, OSFSK_SET);
2444
2445 /* do the packing */
2446 CVmPack::pack(vmg_ 0, argc, &dst);
2447
2448 /* discard the arguments */
2449 G_stk->discard(argc);
2450
2451 /* return the number of bytes written */
2452 retval->set_int(dst.get_pos() - idx);
2453
2454 /* handled */
2455 return TRUE;
2456 }
2457
2458 /* ------------------------------------------------------------------------ */
2459 /*
2460 * Property evaluator - static ByteArray.packBytes(). This version of the
2461 * method creates a new ByteArray object containing the packed bytes.
2462 */
2463 int CVmObjByteArray::static_packBytes(VMG_ vm_val_t *retval, uint *oargc)
2464 {
2465 /* check arguments */
2466 uint argc = oargc != 0 ? *oargc : 0;
2467 static CVmNativeCodeDesc desc(1, 0, TRUE);
2468 if (get_prop_check_argc(retval, oargc, &desc))
2469 return TRUE;
2470
2471 /* set up an in-memory data stream to receive the packed data */
2472 CVmMemorySource *dst = new CVmMemorySource(0L);
2473
2474 err_try
2475 {
2476 /* do the packing */
2477 CVmPack::pack(vmg_ 0, argc, dst);
2478
2479 /* create a byte array to hold the packed data */
2480 long len = dst->get_size();
2481 retval->set_obj(create(vmg_ FALSE, len));
2482 CVmObjByteArray *arr = (CVmObjByteArray *)vm_objp(vmg_ retval->val.obj);
2483
2484 /*
2485 * copy the bytes from the stream to the byte array; it's a new
2486 * object, so there's no undo to save
2487 */
2488 dst->seek(0, OSFSK_SET);
2489 arr->read_from_file(vmg_ retval->val.obj, dst, 1, len, FALSE);
2490 }
2491 err_finally
2492 {
2493 /* done with the data stream */
2494 delete dst;
2495 }
2496 err_end;
2497
2498 /* discard the arguments */
2499 G_stk->discard(argc);
2500
2501 /* handled */
2502 return TRUE;
2503 }
2504
2505
2506 /* ------------------------------------------------------------------------ */
2507 /*
2508 * property evaluator - unpackBytes
2509 */
2510 int CVmObjByteArray::getp_unpackBytes(
2511 VMG_ vm_obj_id_t self, vm_val_t *retval, uint *oargc)
2512 {
2513 /* check arguments */
2514 uint argc = oargc != 0 ? *oargc : 0;
2515 static CVmNativeCodeDesc desc(2);
2516 if (get_prop_check_argc(retval, oargc, &desc))
2517 return TRUE;
2518
2519 /* retrieve the starting index from the first argument */
2520 long idx = CVmBif::pop_long_val(vmg0_);
2521 --argc;
2522
2523 /* limit the index to 1..length */
2524 if (idx < 1)
2525 idx = 1;
2526 else if ((ulong)idx > get_element_count())
2527 idx = get_element_count();
2528
2529 /* get the format string, but leave it on the stack for gc protection */
2530 const char *fmt = G_stk->get(0)->get_as_string(vmg0_);
2531
2532 /* get the format string length and buffer pointer */
2533 size_t fmtlen = vmb_get_len(fmt);
2534 fmt += VMB_LEN;
2535
2536 /* set up a data source for the byte array */
2537 CVmByteArraySource src(vmg_ self);
2538
2539 /* seek to the starting index */
2540 src.seek(idx - 1, OSFSK_SET);
2541
2542 /* do the unpacking */
2543 CVmPack::unpack(vmg_ retval, fmt, fmtlen, &src);
2544
2545 /* discard arguments */
2546 G_stk->discard(argc);
2547
2548 /* handled */
2549 return TRUE;
2550 }
2551
2552 /* ------------------------------------------------------------------------ */
2553 /*
2554 * property evaluator - sha256
2555 */
2556 int CVmObjByteArray::getp_sha256(
2557 VMG_ vm_obj_id_t self, vm_val_t *retval, uint *oargc)
2558 {
2559 /* check arguments */
2560 uint argc = oargc != 0 ? *oargc : 0;
2561 static CVmNativeCodeDesc desc(0, 2);
2562 if (get_prop_check_argc(retval, oargc, &desc))
2563 return TRUE;
2564
2565 /* get the starting index and length */
2566 long cnt = get_element_count();
2567 long idx = argc >= 1 ? CVmBif::pop_int_val(vmg0_) : 1;
2568 long len = argc >= 2 ? CVmBif::pop_int_val(vmg0_) : cnt;
2569
2570 /* set up a data source on the array, and seek to the starting index */
2571 CVmByteArraySource src(vmg_ self);
2572 src.seek(idx - 1, OSFSK_SET);
2573
2574 /* calculate the hash */
2575 char buf[65];
2576 sha256_datasrc(buf, &src, len);
2577
2578 /* return the string */
2579 retval->set_obj(CVmObjString::create(vmg_ FALSE, buf, 64));
2580
2581 /* handled */
2582 return TRUE;
2583 }
2584
2585 /* ------------------------------------------------------------------------ */
2586 /*
2587 * property evaluator - digestMD5
2588 */
2589 int CVmObjByteArray::getp_digestMD5(
2590 VMG_ vm_obj_id_t self, vm_val_t *retval, uint *oargc)
2591 {
2592 /* check arguments */
2593 uint argc = oargc != 0 ? *oargc : 0;
2594 static CVmNativeCodeDesc desc(0, 2);
2595 if (get_prop_check_argc(retval, oargc, &desc))
2596 return TRUE;
2597
2598 /* get the starting index and length */
2599 long cnt = get_element_count();
2600 long idx = argc >= 1 ? CVmBif::pop_int_val(vmg0_) : 1;
2601 long len = argc >= 2 ? CVmBif::pop_int_val(vmg0_) : cnt;
2602
2603 /* limit the starting index to the available range */
2604 if (idx < 1)
2605 idx = 1;
2606 else if (idx > cnt + 1)
2607 idx = cnt + 1;
2608
2609 /* limit the length to the range remaining */
2610 if (len < 0)
2611 len = 0;
2612 else if (len > cnt - idx + 1)
2613 len = cnt - idx + 1;
2614
2615 /* set up the hash accumulator */
2616 md5_state_t ctx;
2617 md5_init(&ctx);
2618
2619 /* feed the selected range of bytes into the hash */
2620 while (len > 0)
2621 {
2622 /* get the next chunk */
2623 size_t avail;
2624 unsigned char *p = get_ele_ptr(idx, &avail);
2625
2626 /* use the whole chunk, up to the amount remaining in the request */
2627 size_t cur = (len < (long)avail ? (size_t)len : avail);
2628
2629 /* feed this chunk into the hash */
2630 md5_append(&ctx, p, cur);
2631
2632 /* deduct this chunk from the remaining length */
2633 len -= cur;
2634 }
2635
2636 /* calculate the hash result */
2637 const int HASH_BYTES = 16;
2638 unsigned char hash[HASH_BYTES];
2639 md5_finish(&ctx, hash);
2640
2641 /* convert the binary hash to printable hex digits */
2642 char buf[HASH_BYTES*2], *bufp = buf;
2643 for (int i = 0 ; i < HASH_BYTES ; ++i, bufp += 2)
2644 byte_to_xdigits(bufp, hash[i]);
2645
2646 /* return the string */
2647 retval->set_obj(CVmObjString::create(vmg_ FALSE, buf, HASH_BYTES*2));
2648
2649 /* handled */
2650 return TRUE;
2651 }
2652