-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathw3.cpp
1140 lines (970 loc) · 30.7 KB
/
w3.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
// A WebAssembly codebase by Jay Krell
//
// https://webassembly.github.io/spec/core/binary/index.html
// https://webassembly.github.io/spec/core/_download/WebAssembly.pdf
#include "w3.h"
#include "w3Fd.h"
#include "w3Handle.h"
#include "w3MemoryMappedFile.h"
#include "w3Module.h"
#include "ieee.h"
#include "math_private.h"
extern const float wasm_hugef = 1.0e30F;
extern const double wasm_huged = 1.0e300;
#include "w3Value.h"
#include "w3TaggedValue.h"
#include "w3StackValue.h"
#include "w3StackBaseBase.h"
#include "w3StackBase.h"
#include "w3Int.h"
void ThrowString (const std::string& a)
{
//fprintf (stderr, "%s\n", a.c_str ());
throw a + "\n";
//abort ();
}
#if 0
void AssertFailed (PCSTR file, int line, PCSTR expr)
{
fprintf (stderr, "Assert failed: %s(%d):%s\n", file, line, expr);
#ifdef _WIN32
DebugBreak();
#else
abort ();
#endif
}
#define Assert(expr) ((void)((expr) || AssertFailed (__FILE__, __LINE__, #expr)))
#else
void AssertFailedFormat (PCSTR condition, const std::string& extra)
{
fputs (("AssertFailed:" + std::string (condition) + ":" + extra + "\n").c_str (), stderr);
//Assert (0);
//abort ();
#ifdef _WIN32 // TODO
if (IsDebuggerPresent ()) __debugbreak ();
#endif
ThrowString ("AssertFailed:" + std::string (condition) + ":" + extra);
}
void AssertFailed (PCSTR expr)
{
fprintf (stderr, "AssertFailed:%s\n", expr);
#ifdef _WIN32 // TODO
if (IsDebuggerPresent ()) __debugbreak ();
#endif
assert (0);
abort ();
}
#endif
std::string StringFormatVa (PCSTR format, va_list va);
std::string StringFormat (PCSTR format, ...)
{
va_list va;
va_start (va, format);
std::string a = StringFormatVa (format, va);
va_end (va);
return a;
}
void ThrowInt (int i, PCSTR a)
{
ThrowString (StringFormat ("error 0x%08X %s", i, a));
}
void ThrowErrno (PCSTR a)
{
ThrowInt (errno, a);
}
#ifdef _WIN32
void throw_Win32Error (int err, PCSTR a)
{
ThrowInt (err, a);
}
void throw_GetLastError (PCSTR a)
{
ThrowInt ((int)GetLastError (), a);
}
#endif
#ifdef _MSC_VER
#pragma warning (disable:4777) // printf maybe wrong for other platforms
#pragma warning (push)
#pragma warning (disable:4996) // _vsnprintf dangerous
#endif
size_t string_vformat_length (PCSTR format, va_list va)
{
#ifdef _MSC_VER
return 2 + _vscprintf (format, va);
#else
return 2 + vsnprintf (0, 0, format, va);
#endif
}
#if _MSC_VER >= 1200
#pragma warning (pop)
#endif
//template <class T> void WasmStdConstructN (T* a, size_t n) { for (size_t i = 0; i < n; ++i) new (a++) T (); }
//template <class T> void WasmStdCopyConstructNtoN (T* to, T* from, size_t n) { for (size_t i = 0; i < n; ++i) new (to++) T (*from++); }
//template <class T> void WasmStdCopyConstruct1toN (T* to, const T& from, size_t n) { for (size_t i = 0; i < n; ++i) new (to++) T (from); }
//template <class T> void WasmStdCopyConstruct1 (T& to, const T& from) { WasmStdCopyConstruct1toN (&to, from, 1u); }
struct w3FuncAddr // TODO
{
};
struct w3TableAddr // TODO
{
};
struct w3MemAddr // TODO
{
};
struct w3GlobalAddr // TODO
{
};
char TagChar(w3Tag t) //todo: short string?
{
switch (t)
{
case Tag_none: return 'n';
case Tag_bool: return 'b';
case Tag_any: return 'a';
//case Tag_i8: return 'c';
//case Tag_u8: return 'd';
//case Tag_i16: return 's';
//case Tag_u16: return 't';
case Tag_i32: return 'i';
case Tag_i64: return 'j';
case Tag_f32: return 'f';
case Tag_f64: return 'g';
case Tag_empty: return 'e';
case Tag_Value: return 'v';
case Tag_Label: return 'L';
case Tag_Frame: return 'r';
case Tag_FuncRef: return 'u';
}
return '$';
}
#include "w3SourceGenValue.h"
#include "w3SourceGenStack.h"
std::string StringFormatVa (PCSTR format, va_list va)
{
// Some systems, including Linux/amd64, cannot consume a
// va_list multiple times. It must be copied first.
// Passing the parameter twice does not work.
#ifndef _WIN32
va_list va2;
#ifdef __va_copy
__va_copy (va2, va);
#else
va_copy (va2, va); // C99
#endif
#endif
std::vector <char> s (string_vformat_length (format, va));
#ifdef _WIN32
_vsnprintf (&s [0], s.size (), format, va);
#else
vsnprintf (&s [0], s.size (), format, va2);
#endif
return &s [0];
}
#define NotImplementedYed() (AssertFormat (0, ("not yet implemented %s 0x%08X ", __func__, __LINE__)))
struct w3stream
{
virtual ~w3stream() { }
virtual void write (const void* bytes, size_t size) = 0;
void prints (PCSTR a) { write (a, strlen (a)); }
void prints (const std::string& a) { write (a.c_str (), a.length ()); }
void printc (char a) { write (&a, 1); }
void printf (PCSTR format, ...)
{
va_list va;
va_start (va, format);
printv (format, va);
va_end (va);
}
void printv (PCSTR format, va_list va)
{
prints (StringFormatVa (format, va));
}
};
struct w3stdout_stream : w3stream
{
virtual void write (const void* bytes, size_t size)
{
fflush (stdout);
PCSTR pc = (PCSTR)bytes;
while (size > 0)
{
// TODO: Use smaller number for Win32 console?
uint32_t const n = (uint32_t)std::min (size, (((size_t)1) << 30));
#ifdef _WIN32
::_write (_fileno (stdout), pc, n);
#else
::write (fileno (stdout), pc, n);
#endif
size -= n;
pc += n;
}
}
};
struct w3stderr_stream : w3stream
{
// TODO: Refactor with stdout.
virtual void write (const void* bytes, size_t size)
{
fflush (stderr);
PCSTR pc = (PCSTR)bytes;
while (size > 0)
{
uint32_t const n = (uint32_t)std::min (size, (((size_t)1) << 30));
#ifdef _WIN32
::_write (_fileno (stderr), pc, n);
#else
::write (fileno (stderr), pc, n);
#endif
size -= n;
pc += n;
}
}
};
uint8_t read_byte (uint8_t** cursor, const uint8_t* end)
{
if (*cursor >= end)
ThrowString (StringFormat ("malformed %d", __LINE__)); // UNDONE context (move to module or section)
return *(*cursor)++;
}
uint64_t read_varuint64 (uint8_t** cursor, const uint8_t* end)
{
uint64_t result = 0;
uint32_t shift = 0;
while (true)
{
const uint64_t byte = read_byte (cursor, end);
printf ("read_varuint64_2:%X\n", byte);
abort ();
result |= (byte & 0x7F) << shift;
if ((byte & 0x80) == 0)
return result;
shift += 7;
}
}
// TODO: range check, errors
uint32_t read_varuint32 (uint8_t** cursor, const uint8_t* end)
{
return (uint32_t)read_varuint64(cursor, end);
}
uint8_t read_varuint7 (uint8_t** cursor, const uint8_t* end)
{
const uint8_t result = read_byte (cursor, end);
if (result & 0x80)
ThrowString (StringFormat ("malformed %d", __LINE__)); // UNDONE context (move to module or section)
return result;
}
int64_t read_varint64 (uint8_t** cursor, const uint8_t* end)
{
int64_t result = 0;
uint32_t shift = 0;
uint32_t size = 64;
uint32_t byte = 0;
do
{
byte = read_byte (cursor, end);
result |= (byte & 0x7F) << shift;
shift += 7;
} while (byte & 0x80);
// sign bit of byte is second high order bit (0x40)
if ((shift < size) && (byte & 0x40))
result |= (~((int64_t)0) << shift); // sign extend
return result;
}
int32_t read_varint32 (uint8_t** cursor, const uint8_t* end)
{
int32_t result = 0;
uint32_t shift = 0;
uint32_t size = 32;
uint32_t byte = 0;
do
{
byte = read_byte (cursor, end);
result |= (byte & 0x7F) << shift;
shift += 7;
} while (byte & 0x80);
// sign bit of byte is second high order bit (0x40)
if ((shift < size) && (byte & 0x40))
result |= (~0 << shift); // sign extend
return result;
}
PCSTR TagToStringCxx (int tag)
{
switch ((w3Tag)tag)
{
default:break;
case Tag_none: return "void";
case Tag_bool: return "bool";
case Tag_any: return "void*"; // union?
case Tag_i32: return "int";
case Tag_i64: return "int64_t";
case Tag_f32: return "float";
case Tag_f64: return "double";
case Tag_empty: return "void";
case Tag_Value: return "Value";
case Tag_Label: return "Label";
case Tag_Frame: return "Frame";
}
return "unknown";
}
PCSTR TagToString (int tag)
{
switch ((w3Tag)tag)
{
default:break;
case Tag_none: return "none(0)";
case Tag_bool: return "bool(1)";
case Tag_any: return "any(2)";
case Tag_i32: return "i32(7F)";
case Tag_i64: return "i64(7E)";
case Tag_f32: return "f32(7D)";
case Tag_f64: return "f64(7C)";
case Tag_empty: return "empty(40)";
case Tag_Value: return "Value(1)";
case Tag_Label: return "Label(2)";
case Tag_Frame: return "w3Frame(3)";
}
return "unknown";
}
//const uint32_t FunctionTypeTag = 0x60;
// Globals are mutable or constant.
typedef enum w3Mutable
{
w3Mutable_constant = 0, // aka false
w3Mutable_variable = 1, // aka true
} w3Mutable;
// The stack shall use _alloca in a non-recursive interpreter loop.
// This requires some care and macros. Macros that reference locals.
// The interpreter is likely to mostly dispatch to function pointers.
// Some pieces must not be in those functions. They can return values
// to the calling loop and the loop can do some of the work.
//
// In time, the function pointers might be case labels instead.
// However decomposition into separate functions is more elegant, if not less efficient.
//
// Such decomposition will also be good for conversion to JIT, LLVM, C++, etc.
// It is only interpreter, perhaps, that has overwhelming efficiency concern.
//
// w3StackValue initial_stack[1];
// int stack_depth;
// w3StackValue* stack = initial_stack;
// w3StackValue* min_stack = initial_stack;
// struct String { PCH buf; size_t len; };
#if 0
struct w3Variable
{
w3Tag tag;
bool temp : 1;
bool global : 1;
bool local : 1;
long id; // in lieue of name
PCH name;
char namebuf[64];
};
PCH VarName(w3Variable* var)
{
// if (var->name)
// return var->name;
// sprintf("
return 0;
}
#endif
struct w3Interp;
#include "w3Frame.h"
#include "w3Stack.h"
#define INTERP(x) void interp_ ## x ();
INTERP (Unreach)
INTERP (Nop)
INTERP (Block)
INTERP (Loop)
INTERP (If)
INTERP (Else)
INTERP (BlockEnd)
INTERP (Br)
INTERP (BrIf)
INTERP (BrTable)
INTERP (Ret)
INTERP (Call)
INTERP (Calli)
INTERP (Drop)
INTERP (Select)
INTERP (Local_get)
INTERP (Local_set)
INTERP (Local_tee)
INTERP (Global_get)
INTERP (Global_set)
INTERP (MemSize)
INTERP (MemGrow)
INTERP (Convert) // TODO templatize
INTERP (Reserved) // TODO templatize
INTERP (Load) // TODO templatize
INTERP (Store) // TODO templatize
INTERP (Const) // TODO templatize
INTERP (ITestOp)
INTERP (IRelOp)
INTERP (FRelOp)
INTERP (IUnOp)
INTERP (IBinOp)
INTERP (FUnOp)
INTERP (FBinOp)
#include "w3StdStaticAssert.h"
static_assert (BITS_FOR_UINT (0) == 1, "0");
static_assert (BITS_FOR_UINT (1) == 1, "1");
static_assert (BITS_FOR_UINT (2) == 2, "2");
static_assert (BITS_FOR_UINT (3) == 2, "3");
static_assert (BITS_FOR_UINT (4) == 3, "4");
static_assert (BITS_FOR_UINT (10) == 4, "");
static_assert (BITS_FOR_UINT (30) == 5, "");
static_assert (BITS_FOR_UINT (200) == 8, "");
static_assert (BITS_FOR_UINT (sizeof (instructionNames)) == 12, "");
static_assert (bits_for_uint (0) == 1, "0");
static_assert (bits_for_uint (1) == 1, "1");
static_assert (bits_for_uint (2) == 2, "2");
static_assert (bits_for_uint (3) == 2, "3");
static_assert (bits_for_uint (4) == 3, "4");
static_assert (bits_for_uint (10) == 4, "");
static_assert (bits_for_uint (30) == 5, "");
static_assert (bits_for_uint (200) == 8, "");
static_assert (bits_for_uint (sizeof (instructionNames)) == 12, "");
#define w3ExportTag_Function w3ImportTag_Function
#define w3ExportTag_Table w3ImportTag_Table
#define w3ExportTag_Memory w3ImportTag_Memory
#define w3ExportTag_Global w3ImportTag_Global
//struct w3ImportFunction;
//struct w3ImportTable;
//struct w3ImportMemory;
#include "w3ExternalValue.h"
#include "w3ExportInstance.h"
#include "w3ModuleInstance.h"
#include "w3FunctionInstance.h"
#include "w3SectionTraits.h"
extern const w3SectionTraits section_traits [ ] =
{
{ 0 },
#define SECTIONS \
SECTION (TypesSection, read_types) \
SECTION (ImportsSection, read_imports) \
SECTION (FunctionsSection, read_functions) \
SECTION (TablesSection, read_tables) \
SECTION (MemorySection, read_memory) \
SECTION (GlobalsSection, read_globals) \
SECTION (ExportsSection, read_exports) \
SECTION (StartSection, read_start) \
SECTION (ElementsSection, read_elements) \
SECTION (CodeSection, read_code) \
SECTION (DataSection, read_data) \
#undef SECTION
#define SECTION(x, read) {&w3Module::read, #x},
SECTIONS
};
#include "w3Wasm.h"
void Overflow (void)
{
Assert (!"Overflow");
}
struct w3Interp : w3Stack, Wasm
{
private:
w3Interp(const w3Interp&);
void operator =(const w3Interp&);
public:
w3Interp() : module (0), module_instance (0), frame (0), stack (*this)
{
}
void* LoadStore (size_t size);
w3Module* module; // TODO multiple modules
w3ModuleInstance* module_instance; // TODO multiple modules
w3Frame* frame;
// FIXME multiple modules
w3Stack& stack;
void Invoke (w3Function&);
void interp (w3Module* mod, w3Export* emain = 0)
{
Assert (mod && emain && emain->tag == w3ExportTag_Function);
Assert (emain->function < mod->functions.size ());
Assert (emain->function < mod->code.size ());
Assert (mod->functions.size () == mod->code.size ());
w3Function& fmain = mod->functions [emain->function];
//w3Code& cmain = mod->code [emain->function];
// instantiate module
this->module = mod;
w3ModuleInstance instance (module);
this->module_instance = &instance;
// Simulate call to initial function.
Invoke (fmain);
}
void Reserved ();
#undef RESERVED
#define RESERVED(b0) INSTRUCTION (0x ## b0, 0, 0, Reserved ## b0, Imm_none, 0, 0, Tag_none, Tag_none, Tag_none, Tag_none) { Reserved (); }
#undef INSTRUCTION
#define INSTRUCTION(byte0, fixed_size, byte1, name, imm, push, pop, in0, in1, in2, out0) ; void name ()
#include "w3Instructions.h"
;
};
struct SourceGenFunction
{
//std::vector<w3Variable> locals;
//std::vector<w3Variable> temps;
//void reset()
//{
// locals.clear();
// temps.clear();
//}
};
struct w3SourceGen : Wasm
{
w3SourceGen() : temp(0), function_type(0)
{
}
long temp;
//std::vector<w3Variable> globals;
w3SourceGenStack stack; // TODO? std::stack<std::string>
std::stack<w3Label> labels;
w3FunctionType* function_type;
// The value stack is the central data structure so assume it.
PCSTR cstr() { return stack.top().cstr(); }
void push_i32 (int i)
{
char s[99];
sprintf(s, "%d", i); // TODO C vs. Rust TODO perf
w3SourceGenValue sourceGenValue = {Tag_i32, s};
stack.push(sourceGenValue);
}
void push_i32 (PCSTR s)
{
w3SourceGenValue sourceGenValue = {Tag_i32, s};
stack.push(sourceGenValue);
}
void push_i64 (...) //todo
{
}
void push_f32(...) // todo
{
}
void push_f64(...) // todo
{
}
std::string pop ()
{
return stack.pop();
}
/*std::string top ()
{
std::string a = pop ();
push (a);
return a;
}*/
static std::string string_format(PCSTR, ...)
{
return "todo";
}
void push(const std::string& s)
{
w3SourceGenValue value;
value.str = s;
stack.push(value);
}
w3SourceGenValue& top() { return stack.top(); }
};
struct w3RustGen : w3SourceGen //TODO
{
};
struct WasmCGen : w3SourceGen
{
private:
WasmCGen(const WasmCGen&);
void operator=(const WasmCGen&);
public:
void Prefix();
void flush() { }
void print(...) { }
virtual ~WasmCGen()
{
}
WasmCGen() : module (0)
{
}
void Load (PCSTR stack_type, PCSTR mem_type);
void Store (PCSTR stack_type, PCSTR mem_type);
void LoadStore (PCSTR stack_type, PCSTR mem_type, bool loadOrStore);
w3Module* module;
void interp (w3Module* mod, w3Export* emain = 0)
{
// instantiate module
this->module = mod;
w3ModuleInstance instance (module);
//this->module_instance = &instance;
// Simulate call to initial function.
Prefix ();
size_t function_count = mod->functions.size ();
for (size_t function_index = 0; function_index < function_count; ++function_index)
{
// TODO Rust not C.
printf("/*function%d*/\n", (int)function_index);
w3Function& function = mod->functions[function_index];
const size_t function_type_index = function.function_type_index;
printf("/*function_type%d*/\n", (int)function_type_index);
Assert (function_type_index < module->function_types.size ());
function_type = &module->function_types [function_type_index];
w3Code* code = &module->code [function.function_index];
const size_t param_count = function_type->parameters.size ();
uint8_t* cursor = code->cursor;
if (cursor)
{
printf("\n#if 0\n");
DecodeFunction (module, code, &cursor);
printf("\n#endif\n");
code->cursor = 0;
}
if (function_type->results.size() == 0)
printf("\nvoid ");
else
printf("\n%s ", TagToStringCxx(function_type->results[0]));
printf(" function%d ( \n", (int)function_index);
// args are the first locals
// join them here and elsewhere does not care
if (param_count == 0)
printf("void");
else
{
for (size_t j = 0; j < param_count; ++j)
{
if (j)
printf(",");
printf("%s local%" FORMAT_SIZE "d", TagToStringCxx(function_type->parameters[j]), (long_t)j);
}
}
printf(") {");
// Declare locals, merged with parameters.
const size_t local_count = code->locals.size();
for (size_t k = 0; k < local_count; ++k)
{
printf("%s local%" FORMAT_SIZE "d;\n", TagToStringCxx(code->locals[k]), (long_t)k + param_count);
}
this->instr = &code->decoded_instructions [0];
const size_t function_size = code->decoded_instructions.size ();
w3DecodedInstruction* end = instr + function_size;
for (; this->instr < end; ++instr)
{
Assert (this->instr);
switch (this->instr->name)
{
// break before instead of after to avoid unreachable code warning
#undef INSTRUCTION
#define INSTRUCTION(byte0, fixed_size, byte1, name, imm, pop, push, in0, in1, in2, out0) \
break; \
case ::name: \
printf ("/*gen%s x:%X u:%u i:%i*/\n", #name, this->instr->u32, this->instr->u32, this->instr->u32); \
this->name ();
#include "w3Instructions.h"
}
}
while (stack.size() > 1)
printf("%s;\n", pop ().c_str());
if (function_type->results.size())
printf("return ");
while (stack.size())
printf("%s;\n", pop ().c_str());
printf("\n}\n");
}
}
void Reserved ()
{
}
#undef RESERVED
#define RESERVED(b0) void Reserved ## b0 () { Reserved (); }
#undef INSTRUCTION
#define INSTRUCTION(byte0, fixed_size, byte1, name, imm, push, pop, in0, in1, in2, out0) void name ();
#include "w3Instructions.h"
};
#include "w3cgen.cpp"
w3StackValue& w3Frame::Local (size_t index)
{
return interp->stack [locals + index];
}
//if
//else
//brtable
void* w3Interp::LoadStore (size_t size)
{
// TODO Not clear from spec and paper what to do here, despite
// focused discussion on it.
// Why is the operand signed??
size_t effective_address = 0;
const int32_t i = pop_i32 ();
const size_t offset = instr->offset;
if (i >= 0)
{
effective_address = offset + (uint32_t)i;
if (effective_address < offset)
Overflow ();
}
else
{
const size_t magnitude = IntMagnitude (i);
if (magnitude > offset)
Overflow ();
effective_address = offset - magnitude;
}
if (effective_address > UINT_MAX - size)
Overflow ();
AssertFormat (effective_address + size <= frame->module_instance->memory.size (),
("%" FORMAT_SIZE "X %" FORMAT_SIZE "X %" FORMAT_SIZE "X",
(long_t)effective_address, (long_t)size, (long_t)frame->module_instance->memory.size ()));
return &frame->module_instance->memory [effective_address];
}
#undef INTERP
#define INTERP(x) void w3Interp::x ()
void w3Interp::Invoke (w3Function& function)
{
//__debugbreak ();
// Decode function upon first call.
// TODO thread safety
// TODO merge with calli (invoke)
const size_t function_type_index = function.function_type_index;
Assert (function_type_index < module->function_types.size ());
w3FunctionType* function_type = &module->function_types [function_type_index];
w3Code* code = &module->code [function.function_index];
const size_t local_only_count = code->locals.size ();
const size_t param_count = function_type->parameters.size ();
uint8_t* cursor = code->cursor;
if (cursor)
{
DecodeFunction (module, code, &cursor);
code->cursor = 0;
}
const size_t size = code->decoded_instructions.size ();
Assert (size);
DumpStack ("invoke1");
// TODO cross-module calls
// TODO calling embedding
// setup frame
w3Frame frame_value;
frame_value.interp = this;
frame_value.code = code;
frame_value.module = this->module; // TODO cross module calls
frame_value.module_instance = this->module_instance; // TODO cross module calls
frame_value.function_index = function.function_index;
frame_value.param_count = param_count;
frame_value.param_and_local_count = local_only_count + param_count; // TODO overflow
frame_value.local_only_count = local_only_count;
frame_value.local_only_types = local_only_count ? &code->locals [0] : 0;
frame_value.param_types = param_count ? &function_type->parameters [0] : 0;
frame_value.function_type = function_type;
w3StackValue ret (frame);
this->frame = &frame_value;
push_frame (ret);
DumpStack ("pushed_frame");
size_t i = 0;
size_t j = 0;
for (j = 0; j != param_count; ++j)
{
printf ("2 entering function with param [%" FORMAT_SIZE "X] type %X\n", j, (end () - (ssize_t)param_count + (ssize_t)j)->value.tag);
}
// CONSIDER put the interp loop elsewhere
// Invoke would adjust member data and return to it
// params are subsumed into new frame
// TODO We really want this to be more efficient.
// Either by having split stacks, or by computing
// maximum parameter count and putting return before it.
// For now live with memcpy or slower (stack is not presently contiguous)..
if (param_count)
{
for (i = 0; i < param_count; ++i)
{
DumpStack ("moved_param_before");
*(end () - 1 - (ssize_t)i) = *(end () - 2 - (ssize_t)i);
DumpStack ("moved_param_after");
}
}
// place return frame/address (frame is just a marker now, the data is on the native stack)
(end () - 1 - (ssize_t)param_count)->tag = Tag_Frame;
//(end () - 1 - param_count)->frame = frame;
//(end () - 1 - param_count)->instr = instr + !!instr;
// Push locals on stack.
// TODO params also
// TODO reserve (size () + local_only_count);
DumpStack ("push_locals_before");
for (i = 0; i != local_only_count; ++i)
push_value (w3StackValue (code->locals [i]));
DumpStack ("push_locals_after");
// Provide for indexing locals.
frame_value.locals = stack.size () - local_only_count - param_count;
for (j = 0; j != local_only_count + param_count; ++j)
printf ("2 entering function with local [%" FORMAT_SIZE "X] type %X\n", j, frame_value.Local (j).value.tag);
//DumpStack ("invoke2");
// TODO provide for separate depth -- i.e. here is now 0; locals/params cannot be popped
w3DecodedInstruction* previous = instr; // call/ret handling
instr = &code->decoded_instructions [0];
w3DecodedInstruction* end = instr + size;
for (; instr < end; ++instr) // Br subtracts one so this works.
{
Assert (instr);
switch (instr->name)
{
// break before instead of after to avoid unreachable code warning
#undef RESERVED
#define RESERVED(b0) INSTRUCTION (0x ## b0, 0, 0, Reserved ## b0, Imm_none, 0, 0, Tag_none, Tag_none, Tag_none, Tag_none) { Reserved (); }
#undef INSTRUCTION
#define INSTRUCTION(byte0, fixed_size, byte1, name, imm, pop, push, in0, in1, in2, out0) \
break; \
case ::name: \
printf ("interp%s x:%X u:%u i:%i\n", #name, instr->u32, instr->u32, instr->u32); \
this->name ();
#include "w3Instructions.h"
}
// special handling
if (instr->name == ::Ret) // gross but most choices are
break;
#include "diag-switch-push.h"
switch (instr->name)
{
case ::Call:
case ::Calli:
frame = &frame_value; // TODO should handled in Ret.
break;
}
#include "diag-switch-pop.h"
}
instr = previous;
// TODO handle ret
//__debugbreak ();
}
#include "w3interp.cpp" //todo separate compile
int
main (int argc, PCH* argv)
{
if (IsDebuggerPresent ()) DebugBreak ();