-
Notifications
You must be signed in to change notification settings - Fork 0
/
caj_vm.cpp
2989 lines (2756 loc) · 86.6 KB
/
caj_vm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2009-2010 Aidan Thornton, all rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY AIDAN THORNTON ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AIDAN THORNTON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "caj_vm.h"
#include "caj_vm_internal.h"
#include "caj_types.h"
#include "caj_logging.h"
#include <cassert>
#include <stdarg.h>
#include <math.h>
//#define DEBUG_TRACEVALS
typedef uint32_t vm_traceval;
typedef std::vector<uint8_t> traceval_stack;
#define TRACEVAL_COUNT(v) ( ((v) >> 24) & 0xff)
#define TRACEVAL_IP(v) ( (v) & 0xffffff)
#define CAJ_LOGGER (st->log)
struct heap_header {
uint32_t refcnt;
uint32_t len;
};
static uint8_t heap_entry_vtype(heap_header *hentry) {
return hentry->refcnt >> 24;
}
struct vm_nfunc_desc { // native function
uint8_t ret_type;
int arg_count;
uint8_t* arg_types;
int number;
vm_native_func_cb cb;
};
struct vm_world {
std::vector<vm_nfunc_desc> nfuncs;
std::map<std::string, int> nfunc_map;
std::map<std::string, vm_nfunc_desc> event_map; // may want to give own type
vm_state_change_cb state_change_cb;
int num_events;
};
#define VM_SCRAM_OK 0
#define VM_SCRAM_ERR 1
#define VM_SCRAM_DIV_ZERO 2
#define VM_SCRAM_STACK_OVERFLOW 3
#define VM_SCRAM_BAD_OPCODE 4
#define VM_SCRAM_MISSING_FUNC 5
#define VM_SCRAM_MEM_LIMIT 6
struct script_state {
uint32_t ip;
uint32_t mem_use;
uint32_t bytecode_len;
uint16_t num_gvals, num_gptrs;
uint16_t num_funcs;
uint16_t* bytecode;
uint16_t* patched_bytecode; // FIXME - only needed on 64-bit systems
vm_traceval* tracevals;
int32_t *stack_start, *stack_top;
int32_t* gvals;
heap_header** gptrs;
uint8_t* gptr_types;
vm_function *funcs;
vm_native_func_cb *nfuncs;
uint16_t *cur_state; // event functions for current state
vm_world *world;
void *priv; // for the user of the VM
caj_logger *log;
int32_t state_id;
int scram_flag;
};
static int verify_code(script_state *st);
static void script_calc_stack(script_state *st, traceval_stack &stack);
static void unwind_stack(script_state * st);
static void vm_bind_events(script_state *st);
void vm_func_set_ptr_ret(script_state *st, int func_no, heap_header *p);
static inline int ptr_stack_sz(void) {
if(sizeof(uint32_t) == sizeof(void*))
return 1;
else if(sizeof(uint32_t)*2 == sizeof(void*))
return 2;
else assert(0);
}
static script_state *new_script(caj_logger *log) {
script_state *st = new script_state();
st->log = log;
st->ip = 0; st->mem_use = 0; st->scram_flag = 0;
st->bytecode_len = 0;
st->num_gvals = st->num_gptrs = st->num_funcs = 0;
st->bytecode = st->patched_bytecode = NULL;
st->tracevals = NULL;
st->nfuncs = NULL;
st->stack_start = st->stack_top = NULL;
st->gvals = NULL; st->gptr_types = NULL;
st->gptrs = NULL; st->funcs = NULL;
st->cur_state = NULL; st->state_id = 0;
return st;
}
static heap_header *script_alloc(script_state *st, uint32_t len, uint8_t vtype) {
uint32_t hlen = len + sizeof(heap_header);
if(len > VM_LIMIT_HEAP || (st->mem_use+hlen) > VM_LIMIT_HEAP) {
CAJ_WARN("DEBUG: exceeded mem limit of %i allocating %i with %i in use\n",
VM_LIMIT_HEAP, (int)len, (int)st->mem_use);
st->scram_flag = VM_SCRAM_MEM_LIMIT; return NULL;
}
heap_header* p = (heap_header*)malloc(hlen);
p->refcnt = ((uint32_t)vtype << 24) | 1;
p->len = len;
st->mem_use += hlen;
return p;
}
static heap_header *script_alloc_list(script_state *st, uint32_t len) {
uint32_t fakelen = len*4 + sizeof(heap_header);
if(len > VM_LIMIT_HEAP || (st->mem_use+fakelen) > VM_LIMIT_HEAP) {
CAJ_WARN("DEBUG: exceeded mem limit of %i allocating %i-item list with %i in use\n",
VM_LIMIT_HEAP, (int)len, (int)st->mem_use);
st->scram_flag = VM_SCRAM_MEM_LIMIT; return NULL;
}
heap_header* p = (heap_header*)malloc(len*sizeof(heap_header*) +
sizeof(heap_header));
p->refcnt = ((uint32_t)VM_TYPE_LIST << 24) | 1;
p->len = len;
st->mem_use += fakelen;
return p;
}
static inline void *script_getptr(heap_header *p) {
return p+1;
}
static void heap_ref_decr(heap_header *p, script_state *st) {
if( ((--(p->refcnt)) & 0xffffff) == 0) {
// printf("DEBUG: freeing heap entry 0x%p\n",p);
if(heap_entry_vtype(p) == VM_TYPE_LIST) {
heap_header **list = (heap_header**)script_getptr(p);
for(unsigned i = 0; i < p->len; i++)
heap_ref_decr(list[i], st);
st->mem_use -= p->len*4 + sizeof(heap_header);
} else {
st->mem_use -= p->len + sizeof(heap_header);
}
free(p);
}
}
static inline void heap_ref_incr(heap_header *p) {
p->refcnt++;
}
static inline uint32_t heap_get_refcnt(heap_header *p) {
return p->refcnt & 0xffffff;
}
static heap_header* make_vm_string(script_state *st, const char* str) {
int len = strlen(str);
heap_header* p = script_alloc(st, len, VM_TYPE_STR);
if(p != NULL) {
memcpy(script_getptr(p), str, len);
}
return p;
}
static heap_header* make_vm_string(script_state *st, const std::string str) {
if(str.length() > 0x100000) {
st->scram_flag = VM_SCRAM_MEM_LIMIT; return NULL;
}
int len = str.length();
heap_header* p = script_alloc(st, len, VM_TYPE_STR);
if(p != NULL) {
memcpy(script_getptr(p), str.c_str(), len);
}
return p;
}
static heap_header* make_num_on_heap(script_state *st, int32_t *val,
int vtype, int count) {
heap_header* p = script_alloc(st, 4*count, vtype);
if(p != NULL) {
memcpy(script_getptr(p), val, count*sizeof(int32_t));
}
return p;
}
static heap_header* make_single_list(script_state *st, heap_header* item) {
if(item == NULL) return NULL;
heap_header* list = script_alloc_list(st, 1);
if(list != NULL) {
*(heap_header**)script_getptr(list) = item;
} else {
heap_ref_decr(item, st);
}
return list;
}
void vm_free_script(script_state * st) {
if(st->stack_start != NULL && st->ip != 0) {
unwind_stack(st);
}
for(unsigned i = 0; i < st->num_gptrs; i++) {
heap_header *p = st->gptrs[i]; heap_ref_decr(p, st);
}
delete[] st->gvals; delete[] st->gptrs; delete[] st->gptr_types;
if(st->patched_bytecode != st->bytecode) delete[] st->patched_bytecode;
delete[] st->bytecode; // FIXME - will want to add bytecode sharing
delete[] st->tracevals;
for(unsigned i = 0; i < st->num_funcs; i++) {
delete[] st->funcs[i].arg_types; delete[] st->funcs[i].name;
}
delete[] st->funcs;
delete[] st->stack_start;
delete[] st->cur_state;
delete st;
}
static int vm_vtype_size(uint8_t vtype) { // not same as vm_asm equivalent
switch(vtype) {
case VM_TYPE_NONE:
return 0; // for return values, mainly
case VM_TYPE_INT:
case VM_TYPE_FLOAT:
return 1;
case VM_TYPE_STR:
case VM_TYPE_KEY:
case VM_TYPE_LIST:
return ptr_stack_sz();
case VM_TYPE_VECT:
return 3;
case VM_TYPE_ROT:
return 4;
default: printf("ERROR: bad vtype in vm_vtype_size()\n"); abort();
}
}
class script_loader {
private:
script_state *st;
caj_logger *log;
unsigned char *data; int data_len, pos;
int has_failed;
uint32_t heap_count;
vm_heap_entry *heap;
uint32_t read_u32() {
if(pos+4 > data_len) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: overran buffer end\n");
has_failed = 1; return 0;
}
uint32_t ret = ((uint32_t)data[pos] << 24) | ((uint32_t)data[pos+1] << 16) |
((uint32_t)data[pos+2] << 8) | (uint32_t)data[pos+3];
pos += 4; return ret;
}
uint16_t read_u16() {
if(pos+2 > data_len) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: overran buffer end\n");
has_failed = 1; return 0;
}
uint32_t ret = ((uint16_t)data[pos] << 8) | (uint16_t)data[pos+1];
pos += 2; return ret;
}
uint16_t read_u8() {
if(pos+1 > data_len) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: overran buffer end\n");
has_failed = 1; return 0;
}
return data[pos++];
}
void read_data(void* buf, int len) {
if(pos+len > data_len) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: overran buffer end\n");
has_failed = 1; return;
}
memcpy(buf,data+pos,len); pos += len;
}
void free_our_heap() {
if(heap != NULL) {
assert(st != NULL);
for(uint32_t i = 0; i < heap_count; i++) {
heap_ref_decr((heap_header*) heap[i].data, st); // FIXME bad types
}
delete[] heap; heap = NULL;
}
}
public:
script_loader(caj_logger *log) : st(NULL), heap(NULL), log(log) {
}
~script_loader() {
free_our_heap();
if(st != NULL) vm_free_script(st);
}
script_state *load(unsigned char* dat, int len) {
data = dat; data_len = len; pos = 0; has_failed = false;
if(read_u32() != VM_MAGIC || has_failed) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: bad magic\n"); return NULL;
}
free_our_heap();
if(st != NULL) vm_free_script(st);
st = new_script(log);
int is_end = 0;
while(!is_end) {
uint32_t sect = read_u32();
if(has_failed) {
CAJ_WARN_L(log, "SCRIPT LOAD ERROR: unexpected EOF reading section\n");
return NULL;
} else if(sect == VM_MAGIC_END) {
is_end = 1; break;
}
uint32_t sect_len = read_u32(); int sect_end = pos + sect_len;
if(has_failed || (uint32_t)(data_len - pos) < sect_len) {
CAJ_WARN_L(log, "SCRIPT LOAD ERROR: unexpected EOF reading section\n");
return NULL;
} else if(!VM_VALID_SECT_ID(sect)) {
CAJ_WARN_L(log, "SCRIPT LOAD ERROR: invalid section ID 0x%x\n", (unsigned)sect);
return NULL;
}
switch(sect) {
case VM_SECT_HEAP:
{
if(heap != NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERROR: duplicate heap section\n");
return NULL;
}
uint32_t hcount = read_u32();
if(has_failed) return NULL;
if(hcount > VM_LIMIT_HEAP_ENTRIES) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: too many heap entries\n"); return NULL;
}
CAJ_DEBUG_L(log, "DEBUG: %u heap entries\n", (unsigned)hcount);
heap = new vm_heap_entry[hcount];
// FIXME - don't really need the vm_heap_entry struct!
for(heap_count = 0; heap_count < hcount;) {
heap[heap_count].vtype = read_u8();
if(heap[heap_count].vtype > VM_TYPE_MAX) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: bad vtype %i on heap\n",
(int)heap[heap_count].vtype); return NULL;
}
uint32_t it_len = heap[heap_count].len = read_u32();
heap_header *p;
// FIXME - handle this right
if(heap[heap_count].vtype == VM_TYPE_STR ||
heap[heap_count].vtype == VM_TYPE_KEY) {
p = script_alloc(st, it_len, heap[heap_count].vtype);
if(p == NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: memory limit\n"); return NULL;
}
read_data(script_getptr(p), it_len);
} else if(heap[heap_count].vtype == VM_TYPE_LIST) {
it_len /= 4;
p = script_alloc_list(st, it_len);
if(p == NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: memory limit\n"); return NULL;
}
CAJ_DEBUG_L(log, "DEBUG: created a list at %p\n", p);
p->len = 0; // HACK!!!!
heap_header **list = (heap_header**)script_getptr(p);
memset(list, 0, it_len*sizeof(heap_header*));
for(uint32_t i = 0; i < it_len; i++) {
uint32_t gptr = read_u32();
if(has_failed) return NULL;
if(gptr >= heap_count) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: invalid gptr\n");
has_failed = 1; break;
}
heap_header *itemp = (heap_header*)heap[gptr].data; // FIXME
if(heap_entry_vtype(itemp) == VM_TYPE_LIST) {
// technically, we don't need to block this... it should be
// impossible to load or create a circularly-linked data
// structure anyway (immutable data + ordering restrictions
// within the file format). LSL doesn't allow it, though.
CAJ_WARN_L(log, "SCRIPT LOAD ERR: list within a list\n");
has_failed = 1; break;
}
heap_ref_incr(itemp); list[i] = itemp;
p->len = i+1; // HACK!!!!
}
} else if(heap[heap_count].vtype == VM_TYPE_INT ||
heap[heap_count].vtype == VM_TYPE_FLOAT) {
if(it_len != 4) {
CAJ_ERROR_L(log, "SCRIPT LOAD ERR: heap int/float not 4 bytes\n");
return NULL;
}
p = script_alloc(st, 4, heap[heap_count].vtype);
if(p == NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: memory limit\n"); return NULL;
}
*(int32_t*)script_getptr(p) = read_u32();
} else if(heap[heap_count].vtype == VM_TYPE_VECT ||
heap[heap_count].vtype == VM_TYPE_ROT) {
int count = heap[heap_count].vtype == VM_TYPE_VECT ? 3 : 4;
if(it_len != 4*count) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: heap vect/rot wrong size\n");
return NULL;
}
p = script_alloc(st, 4*count, heap[heap_count].vtype);
if(p == NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: memory limit\n"); return NULL;
}
int32_t *v = (int32_t*)script_getptr(p);
for(int i = 0; i < count; i++, v++) {
*v = read_u32();
}
} else {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: unhandled heap entry vtype\n"); return NULL;
}
heap[heap_count].data = (unsigned char*)p; // FIXME - bad types!
heap_count++; // placement important for proper mem freeing later
if(has_failed) return NULL;
}
}
if(pos != sect_end) {
CAJ_WARN_L(log, "ERROR: bad length of section\n"); return NULL;
}
break;
case VM_SECT_GLOBALS:
if(st->gvals != NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERROR: duplicate globals section\n");
return NULL;
} else if(heap == NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERROR: heap section must precede globals\n");
return NULL;
}
{
uint16_t gcnt = read_u16();
if(has_failed) return NULL;
if(gcnt > VM_MAX_GVALS) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: excess gvals\n"); return NULL;
}
CAJ_DEBUG_L(log, "DEBUG: %i gvals\n", (int)gcnt);
st->gvals = new int32_t[gcnt];
for(unsigned int i = 0; i < gcnt; i++) {
st->gvals[i] = read_u32();
}
if(has_failed) return NULL;
st->num_gvals = gcnt;
}
{
uint16_t gcnt = read_u16();
if(has_failed) return NULL;
if(gcnt > VM_MAX_GPTRS) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: excess gptrs\n"); return NULL;
}
st->gptrs = new heap_header*[gcnt]; st->num_gptrs = 0;
st->gptr_types = new uint8_t[gcnt];
CAJ_DEBUG_L(log, "DEBUG: %i gptrs\n", (int)gcnt);
for(unsigned int i = 0; i < gcnt; i++) {
uint32_t gptr = read_u32();
if(has_failed) return NULL;
if(gptr >= heap_count) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: invalid gptr\n"); return NULL;
}
heap_header *p = (heap_header*)heap[gptr].data; // FIXME
heap_ref_incr(p);
st->gptrs[i] = p; st->gptr_types[i] = heap_entry_vtype(p);
st->num_gptrs++;
}
if(has_failed) return NULL;
}
if(pos != sect_end) {
CAJ_WARN_L(log, "ERROR: bad length of section\n"); return NULL;
}
break;
case VM_SECT_FUNCS:
if(st->funcs != NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERROR: duplicate functions section\n");
return NULL;
}
{
uint16_t gcnt = read_u16();
if(has_failed) return NULL;
if(gcnt > VM_MAX_FUNCS) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: excess funcs\n"); return NULL;
}
CAJ_DEBUG_L(log, "DEBUG: %i funcs\n", (int)gcnt);
st->funcs = new vm_function[gcnt]; st->num_funcs = 0;
for(unsigned int i = 0; i < gcnt; i++) {
st->funcs[i].ret_type = read_u8(); //(funcs[i].ret_type);
if(st->funcs[i].ret_type > VM_TYPE_MAX) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: bad vtype %i as ret type\n",
(int)st->funcs[i].ret_type); return NULL;
}
int arg_count = st->funcs[i].arg_count = read_u8();
st->funcs[i].arg_types = new uint8_t[arg_count];
st->funcs[i].name = NULL; st->num_funcs++; // for eventual freeing
st->funcs[i].frame_sz = 1;
for(int j = 0; j < arg_count; j++) {
uint8_t arg_type = st->funcs[i].arg_types[j] = read_u8();
if(arg_type > VM_TYPE_MAX) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: bad vtyp %i of argument\n",
(int)arg_type); return NULL;
}
st->funcs[i].frame_sz += vm_vtype_size(arg_type);
}
int slen = read_u8();
if(has_failed) return NULL;
char *name = new char[slen+1];
read_data(name, slen); name[slen] = 0;
st->funcs[i].name = name;
st->funcs[i].insn_ptr = read_u32();
if(has_failed) return NULL;
}
}
if(pos != sect_end) {
CAJ_WARN_L(log, "ERROR: bad length of section\n"); return NULL;
}
break;
case VM_SECT_BYTECODE:
if(st->bytecode != NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERROR: duplicate bytecode section\n");
return NULL;
}
st->bytecode_len = sect_len/2;
if(st->bytecode_len > VM_LIMIT_INSNS) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: too much bytecode\n");
return NULL;
}
st->bytecode = new uint16_t[st->bytecode_len];
for(unsigned int i = 0; i < st->bytecode_len; i++) {
st->bytecode[i] = read_u16();
if(has_failed) return NULL;
}
if(pos != sect_end) {
CAJ_WARN_L(log, "ERROR: bad length of section\n"); return NULL;
}
break;
case VM_SECT_STATE_ID: // optional
st->state_id = read_u32();
if(has_failed) return NULL;
if(pos != sect_end) {
CAJ_WARN_L(log, "ERROR: bad length of section\n"); return NULL;
}
break;
default:
pos = sect_end; break;
}
}
if(has_failed) return NULL;
if(heap == NULL || st->gvals == NULL || st->gptrs == NULL ||
st->funcs == NULL || st->bytecode == NULL) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: missing required section\n"); return NULL;
}
if(!verify_code(st)) {
CAJ_WARN_L(log, "SCRIPT LOAD ERR: didn't verify\n"); return NULL;
};
{ // final return
script_state *st2 = st; free_our_heap(); st = NULL;
return st2;
}
}
};
script_state* vm_load_script(caj_logger *log, void* data, int data_len) {
script_loader loader(log);
return loader.load((unsigned char*)data, data_len);
}
static uint32_t serialise_heap_int(vm_serialiser &serial, heap_header* hptr,
unsigned count,
std::vector<unsigned char*> &tmpbufs) {
int32_t *val = (int32_t*)script_getptr(hptr);
unsigned char *buf = (unsigned char*)malloc(4*count);
assert(hptr->len == 4*count);
for(unsigned i = 0; i < count; i++) {
serial.int_to_bin(val[i], buf+(4*i));
}
tmpbufs.push_back(buf);
return serial.add_heap_entry(heap_entry_vtype(hptr), 4*count, buf);
}
static uint32_t serialise_heap_item(std::map<heap_header*,uint32_t> &heap_map,
vm_serialiser &serial, heap_header* hptr,
std::vector<unsigned char*> &tmpbufs) {
std::map<heap_header*,uint32_t>::iterator iter =
heap_map.find(hptr);
uint8_t vtype = heap_entry_vtype(hptr);
if(iter != heap_map.end()) {
return iter->second;
} else if(vtype == VM_TYPE_STR || vtype == VM_TYPE_KEY) {
uint32_t hidx = serial.add_heap_entry(vtype, hptr->len,
script_getptr(hptr));
heap_map[hptr] = hidx; return hidx;
} else if(vtype == VM_TYPE_INT || vtype == VM_TYPE_FLOAT) {
uint32_t hidx = serialise_heap_int(serial, hptr, 1, tmpbufs);
heap_map[hptr] = hidx; return hidx;
} else if(vtype == VM_TYPE_VECT) {
uint32_t hidx = serialise_heap_int(serial, hptr, 3, tmpbufs);
heap_map[hptr] = hidx; return hidx;
} else if(vtype == VM_TYPE_ROT) {
uint32_t hidx = serialise_heap_int(serial, hptr, 4, tmpbufs);
heap_map[hptr] = hidx; return hidx;
} else if(vtype == VM_TYPE_LIST) {
heap_header **items = (heap_header**)script_getptr(hptr);
unsigned char *buf = (unsigned char*)calloc(hptr->len, 4);
for(uint32_t i = 0; i < hptr->len; i++) {
uint32_t item_idx = serialise_heap_item(heap_map, serial,
items[i], tmpbufs);
serial.int_to_bin(item_idx, buf+(4*i));
}
uint32_t hidx = serial.add_heap_entry(vtype, hptr->len*4, buf);
tmpbufs.push_back(buf);
heap_map[hptr] = hidx; return hidx;
} else {
printf("FATAL ERROR: unhandled heap item type %i\n", vtype);
// FIXME
abort(); return 0;
}
}
// FIXME - really need to serialise stack too...
unsigned char* vm_serialise_script(script_state *st, size_t *len) {
if(st->scram_flag != 0) {
*len = 0; return NULL;
}
vm_serialiser serial; std::vector<unsigned char*> tmpbufs;
std::map<heap_header*,uint32_t> heap_map;
uint32_t *gptrs = new uint32_t[st->num_gptrs];
for(unsigned i = 0; i < st->num_gptrs; i++) {
gptrs[i] = serialise_heap_item(heap_map, serial, st->gptrs[i], tmpbufs);
}
serial.set_bytecode(st->bytecode, st->bytecode_len);
serial.set_gvals(st->gvals, st->num_gvals);
serial.set_gptrs(gptrs, st->num_gptrs);
for(unsigned i = 0; i < st->num_funcs; i++) {
serial.add_func(&st->funcs[i]);
}
serial.set_cur_state_id(st->state_id);
unsigned char *ret = serial.serialise(len);
for(std::vector<unsigned char*>::iterator iter = tmpbufs.begin();
iter != tmpbufs.end(); iter++) {
free(*iter);
}
delete[] gptrs; return ret;
}
static int verify_pass1(unsigned char * visited, uint16_t *bytecode, vm_function *func,
caj_logger *log) {
std::vector<uint32_t> pending;
pending.push_back(func->insn_ptr);
next_chunk:
while(!pending.empty()) {
uint32_t ip = pending.back(); pending.pop_back();
for(;;) {
if(ip < func->insn_ptr || ip >= func->insn_end) {
CAJ_WARN_L(log, "SCRIPT VERIFY ERR: IP out of bounds\n"); return 0;
}
if(visited[ip] != 0) {
visited[ip] = 2; goto next_chunk;
}
visited[ip] = 1; uint16_t insn = bytecode[ip++];
switch(GET_ICLASS(insn)) {
case ICLASS_NORMAL:
{
uint16_t ival = GET_IVAL(insn);
if(ival >= NUM_INSNS) {
CAJ_WARN_L(log, "SCRIPT VERIFY ERR: invalid instruction\n"); return 0;
}
switch(vm_insns[ival].special) {
case IVERIFY_INVALID:
CAJ_WARN_L(log, "SCRIPT VERIFY ERR: invalid instruction\n"); return 0;
case IVERIFY_RET:
goto next_chunk;
case IVERIFY_COND:
// execution could skip the next instruction...
pending.push_back(ip+1);
break;
case IVERIFY_NORMAL: // not interesting yet
default: break;
}
break;
}
case ICLASS_JUMP:
{
uint16_t ival = GET_IVAL(insn);
if(ival & 0x800) {
ip -= ival & 0x7ff;
} else {
ip += ival;
}
}
break;
default: break;
}
}
}
return 1;
}
struct pass2_state {
uint32_t ip; vm_traceval trace;
struct asm_verify* verify;
pass2_state(uint32_t ipstart, vm_traceval trace_now, struct asm_verify* v) : ip(ipstart), trace(trace_now), verify(v) {
}
};
static inline vm_traceval build_traceval(uint32_t ip, int count) {
assert(ip < 0xffffff); assert(count < 256);
return ((uint32_t)count<<24) | ip;
}
static int traceval_type_to_count(uint8_t type) {
switch(type) {
case VM_TYPE_NONE: return 0;
case VM_TYPE_INT:
case VM_TYPE_FLOAT:
case VM_TYPE_STR:
case VM_TYPE_KEY:
case VM_TYPE_LIST:
case VM_TYPE_PTR:
case VM_TYPE_RET_ADDR:
return 1;
case VM_TYPE_VECT:
return 3;
case VM_TYPE_ROT:
return 4;
default:
printf("FATAL ERROR: unhandled type %i in traceval_type_to_count\n", type);
fflush(stdout);
assert(0); abort(); return 0;
}
}
static vm_traceval traceval_pop(vm_traceval cur, uint8_t type,
script_state *st) {
int count = traceval_type_to_count(type);
while(count > 0) {
int tv_num = TRACEVAL_COUNT(cur);
uint32_t tv_ip = TRACEVAL_IP(cur);
count -= tv_num;
if(count < 0) {
return build_traceval(tv_ip, -count);
}
if(tv_ip == 0 && count == 0)
return build_traceval(0, 0);
assert(tv_ip > 0);
cur = st->tracevals[tv_ip];
}
return cur;
}
typedef std::vector<uint8_t> traceval_stack;
static void traceval_to_stack(vm_traceval cur, script_state *st,
uint32_t ip, traceval_stack &stack) {
for(;;) {
int tv_num = TRACEVAL_COUNT(cur);
uint32_t tv_ip = TRACEVAL_IP(cur);
if(tv_ip == 0) break;
assert(tv_num > 0);
uint16_t insn = st->bytecode[tv_ip];
uint8_t vtype;
switch(GET_ICLASS(insn)) {
case ICLASS_NORMAL:
vtype = vm_insns[GET_IVAL(insn)].ret;
break;
case ICLASS_RDL_I:
case ICLASS_RDG_I:
vtype = VM_TYPE_INT; break;
case ICLASS_RDL_P:
case ICLASS_RDG_P:
vtype = VM_TYPE_PTR; break;
case ICLASS_WRL_I:
case ICLASS_WRL_P:
case ICLASS_WRG_I:
case ICLASS_WRG_P:
case ICLASS_JUMP:
case ICLASS_CALL:
vtype = VM_TYPE_NONE; break;
default:
printf("FATAL ERROR: unhandled iclass %i in traceval_to_stack\n",
(int)GET_ICLASS(insn));
abort(); return;
}
assert(vtype != VM_TYPE_NONE);
if(vtype == VM_TYPE_VECT || vtype == VM_TYPE_ROT)
vtype = VM_TYPE_FLOAT;
for(int i = 0; i < tv_num; i++)
stack.push_back(vtype);
cur = st->tracevals[tv_ip];
}
vm_function *func = NULL;
for(int i = 0; i < st->num_funcs; i++) {
if(st->funcs[i].insn_ptr == 0) continue;
if(st->funcs[i].insn_ptr <= ip &&
ip < st->funcs[i].insn_end) {
func = &st->funcs[i];
}
}
assert(func != NULL);
traceval_stack args;
int count = TRACEVAL_COUNT(cur);
#if 0
for(uint8_t *arg_type = func->arg_types+func->arg_count-1;
arg_type >= func->arg_types && count > 0; arg_type--) {
#else
for(int argno = 0; argno < func->arg_count && count > 0; argno++) {
uint8_t *arg_type = func->arg_types+argno;
#endif
switch(*arg_type) {
case VM_TYPE_INT:
case VM_TYPE_FLOAT:
case VM_TYPE_STR:
case VM_TYPE_KEY:
case VM_TYPE_LIST:
args.push_back(*arg_type); count--;
break;
case VM_TYPE_ROT:
if(count > 0) { args.push_back(VM_TYPE_FLOAT); count--; }
/* fall through */
case VM_TYPE_VECT:
if(count > 0) { args.push_back(VM_TYPE_FLOAT); count--; }
if(count > 0) { args.push_back(VM_TYPE_FLOAT); count--; }
if(count > 0) { args.push_back(VM_TYPE_FLOAT); count--; }
break;
default:
printf("FATAL ERROR: unhandled arg type %i in traceval_to_stack\n",
*arg_type);
abort(); break;
}
}
if(count > 0) {
printf("FATAL ERROR: excess args %i in traceval_to_stack\n",
count);
abort();
}
while(!args.empty()) {
stack.push_back(args.back()); args.pop_back();
}
}
static void calc_stack_curop(traceval_stack &stack, uint8_t vtype) {
switch(vtype) {
case VM_TYPE_NONE:
break;
case VM_TYPE_INT:
case VM_TYPE_FLOAT:
case VM_TYPE_KEY:
case VM_TYPE_STR:
case VM_TYPE_LIST:
case VM_TYPE_RET_ADDR:
stack.push_back(vtype); break;
case VM_TYPE_ROT:
stack.push_back(VM_TYPE_FLOAT);
/* fall through */
case VM_TYPE_VECT:
stack.push_back(VM_TYPE_FLOAT);
stack.push_back(VM_TYPE_FLOAT);
stack.push_back(VM_TYPE_FLOAT);
break;
default:
printf("FATAL: unhandled type %i in calc_stack_curop\n", vtype);
fflush(stdout); abort();
}
}
static void script_calc_stack(script_state *st, traceval_stack &stack) {
uint16_t insn = st->bytecode[st->ip];
switch(GET_ICLASS(insn)) {
case ICLASS_NORMAL:
calc_stack_curop(stack, vm_insns[GET_IVAL(insn)].arg2);
calc_stack_curop(stack, vm_insns[GET_IVAL(insn)].arg1);
break;
case ICLASS_RDL_I:
case ICLASS_RDG_I:
case ICLASS_RDL_P:
case ICLASS_RDG_P:
break;
case ICLASS_WRL_I:
case ICLASS_WRG_I:
stack.push_back(VM_TYPE_INT); break;
case ICLASS_WRL_P:
case ICLASS_WRG_P:
stack.push_back(VM_TYPE_PTR); break;
case ICLASS_JUMP:
break;
case ICLASS_CALL:
{
uint16_t ival = GET_IVAL(insn);
assert(ival < st->num_funcs);
vm_function *func = &st->funcs[ival];
for(int i = func->arg_count - 1; i >= 0; i--) {
calc_stack_curop(stack, func->arg_types[i]);
}
calc_stack_curop(stack, VM_TYPE_RET_ADDR);
break;
}
default:
printf("FATAL ERROR: unhandled iclass %i in traceval_to_stack\n",
(int)GET_ICLASS(insn));
abort(); return;
}
traceval_to_stack(st->tracevals[st->ip], st, st->ip, stack);
}
static int verify_pass2(unsigned char * visited, uint16_t *bytecode,
vm_function *func, script_state *st) {
std::vector<pass2_state> pending; const char* err = NULL;
std::map<uint32_t,asm_verify*> done;
{
int arg_size_tv = 0;
for(int i = 0; i < func->arg_count; i++) {
arg_size_tv += traceval_type_to_count(func->arg_types[i]);
}
if(arg_size_tv > 255) {
err = "Arguments too big for traceval code"; goto out;
}
asm_verify* verify = new asm_verify(err, func, ptr_stack_sz());
pending.push_back(pass2_state(func->insn_ptr,
build_traceval(0, arg_size_tv), verify));
}
func->max_stack_use = 0;
next_chunk:
while(!pending.empty()) {
pass2_state vs = pending.back(); pending.pop_back();
for(;;) {
assert(!(vs.ip < func->insn_ptr || vs.ip >= func->insn_end)); // checked pass 1
assert(visited[vs.ip] != 0);
if(visited[vs.ip] > 1) {
std::map<uint32_t,asm_verify*>::iterator iter = done.find(vs.ip);