3 * by John Hodge (thePowersGang)
6 * - Generate a bytecode file
10 #include "bytecode_gen.h"
21 int Bytecode_ConvertScript(tSpiderScript *Script, const char *DestFile)
23 tStringList strings = {0};
26 int fcn_hdr_offset = 0;
30 void _put8(uint8_t val)
32 fwrite(&val, 1, 1, fp);
34 void _put32(uint32_t val)
42 fp = fopen(DestFile, "wb");
46 fwrite("SSBC\r\n\xBC\x55", 8, 1, fp);
47 _put32(0); // Function count, to be filled
48 _put32(0); // String count
49 _put32(0); // String table offset
52 fcn_hdr_offset = ftell(fp);
54 // Create function descriptors
55 for(fcn = Script->Script->Functions; fcn; fcn = fcn->Next, fcn_count ++)
59 _put32( StringList_GetString(&strings, fcn->Name, strlen(fcn->Name)) );
60 _put32( 0 ); // Code offset
61 _put8( fcn->ReturnType );
63 if(fcn->ArgumentCount > 255) {
64 // ERROR: Too many args
67 _put8( fcn->ArgumentCount );
70 for(arg = fcn->Arguments; arg; arg = arg->NextSibling)
72 _put32( StringList_GetString(&strings, arg->DefVar.Name, strlen(arg->DefVar.Name)) );
73 _put8( arg->DefVar.DataType );
77 // Put function code in
78 for(fcn = Script->Script->Functions; fcn; fcn = fcn->Next)
86 fseek(fp, SEEK_SET, fcn_hdr_offset + 4);
88 fseek(fp, SEEK_SET, code_pos );
90 fcn_hdr_offset += 4+4+1+1+(4+1)*fcn->ArgumentCount;
93 bc_fcn = Bytecode_ConvertFunction(fcn);
94 code = Bytecode_SerialiseFunction(bc_fcn, &len, &strings);
95 Bytecode_DeleteFunction(bc_fcn);
96 fwrite(code, len, 1, fp);
101 strtab_ofs = ftell(fp);
103 int string_offset = strtab_ofs + (4+4)*strings.Count;
106 for(str = strings.Head; str; str = str->Next)
109 _put32(string_offset);
110 string_offset += str->Length + 1;
113 for(str = strings.Head; str;)
115 tString *nextstr = str->Next;
116 fwrite(str->Data, str->Length, 1, fp);
126 fseek(fp, 8, SEEK_SET);
128 _put32(strings.Count);