fixed bug in field description
[swftools.git] / lib / as3 / code.c
1 #include <assert.h>
2 #include "code.h"
3 #include "pool.h"
4
5 #define OP_REGISTER 1
6 #define OP_STACK_ARGS 2
7 #define OP_STACK_NS 4
8 #define OP_SET_DXNS 8
9 #define OP_RETURN 16
10 #define OP_THROW 32
11 #define OP_BRANCH 64
12 #define OP_JUMP 128
13 #define OP_LABEL 256
14 #define OP_LOOKUPSWITCH 512
15 #define OP_NEED_ACTIVATION 1024
16 #define OP_STACK_ARGS2 2048
17
18 /* 2 = u30 index into multiname
19    m = u30 index into method
20    n = u30 number of params
21    i = u30 index into method info
22    b = byte
23    c = u30 index into class
24    s = string (u30 index into strings)
25    S = switch
26    u = u30
27    r = register
28 */
29
30 opcode_t opcodes[]={
31 {0xa0, "add", "",              -2, 1, 0, 0},
32 {0xc5, "add_i", "",            -2, 1, 0, 0},
33 {0x86, "astype", "2",          -1, 1, 0, 0},
34 {0x87, "astypelate", "",       -2, 1, 0, 0},
35 {0xA8, "bitand", "",           -2, 1, 0, 0},
36 {0x97, "bitnot", "",           -1, 1, 0, 0},
37 {0xa9, "bitor", "",            -2, 1, 0, 0},
38 {0xaa, "bitxor", "",           -2, 1, 0, 0},
39 {0x41, "call", "n",            -2, 1, 0, OP_STACK_ARGS},
40 {0x43, "callmethod", "mn",     -1, 1, 0, OP_STACK_ARGS},
41 {0x4c, "callproplex", "2n",    -1, 1, 0, OP_STACK_ARGS|OP_STACK_NS},
42 {0x46, "callproperty", "2n",   -1, 1, 0, OP_STACK_ARGS|OP_STACK_NS},
43 {0x4f, "callpropvoid", "2n",   -1, 0, 0, OP_STACK_ARGS|OP_STACK_NS},
44 {0x44, "callstatic", "in",     -1, 1, 0, OP_STACK_ARGS},
45 {0x45, "callsuper", "2n",      -1, 1, 0, OP_STACK_ARGS|OP_STACK_NS},
46 {0x4e, "callsupervoid", "2n",  -1, 0, 0, OP_STACK_ARGS|OP_STACK_NS},
47 {0x78, "checkfilter", "",      -1, 1, 0, 0},
48 {0x80, "coerce", "2",          -1, 1, 0, 0},
49 {0x82, "coerce_a", "",         -1, 1, 0, 0},
50 {0x85, "coerce_s", "",         -1, 1, 0, 0},
51 {0x42, "construct", "n",       -1, 1, 0, OP_STACK_ARGS},
52 {0x4a, "constructprop", "2n",  -1, 1, 0, OP_STACK_ARGS|OP_STACK_NS},
53 {0x49, "constructsuper", "n",  -1, 0, 0, OP_STACK_ARGS},
54 {0x76, "convert_b", "",        -1, 1, 0, 0},
55 {0x73, "convert_i", "",        -1, 1, 0, 0},
56 {0x75, "convert_d", "",        -1, 1, 0, 0},
57 {0x77, "convert_o", "",        -1, 1, 0, 0},
58 {0x74, "convert_u", "",        -1, 1, 0, 0},
59 {0x70, "convert_s", "",        -1, 1, 0, 0},
60 {0xef, "debug", "D",            0, 0, 0, 0},
61 {0xf1, "debugfile", "s",        0, 0, 0, 0},
62 {0xf0, "debugline", "u",        0, 0, 0, 0},
63 {0x94, "declocal", "r",         0, 0, 0, OP_REGISTER},
64 {0xc3, "declocal_i", "r",       0, 0, 0, OP_REGISTER},
65 {0x93, "decrement", "",        -1, 1, 0, 0}, 
66 {0xc1, "decrement_i", "",      -1, 1, 0, 0},
67 {0x6a, "deleteproperty", "2",  -1, 1, 0, OP_STACK_NS},
68 {0xa3, "divide", "",           -2, 1, 0, 0},
69 {0x2a, "dup", "",              -1, 2, 0, 0},
70 {0x06, "dxns", "s",             0, 0, 0, OP_SET_DXNS},
71 {0x07, "dxnslate", "",         -1, 0, 0, OP_SET_DXNS},
72 {0xab, "equals", "",           -2, 1, 0, 0},
73 {0x72, "esc_xattr", "",        -1, 1, 0, 0},
74 {0x71, "esc_xelem", "",        -1, 1, 0, 0},
75 {0x5e, "findproperty", "2",     0, 1, 0, OP_STACK_NS},
76 {0x5d, "findpropstrict", "2",   0, 1, 0, OP_STACK_NS},
77 {0x59, "getdescendants", "2",  -1, 1, 0, OP_STACK_NS},
78 {0x64, "getglobalscope", "",    0, 1, 0, 0},
79 {0x6e, "getglobalslot", "u",    0, 1, 0, 0},
80 {0x60, "getlex", "2",           0, 1, 0, 0}, //multiname may not be runtime
81 {0x62, "getlocal", "r",         0, 1, 0, OP_REGISTER},
82 {0xd0, "getlocal_0", "",        0, 1, 0, OP_REGISTER},
83 {0xd1, "getlocal_1", "",        0, 1, 0, OP_REGISTER},
84 {0xd2, "getlocal_2", "",        0, 1, 0, OP_REGISTER},
85 {0xd3, "getlocal_3", "",        0, 1, 0, OP_REGISTER},
86 {0x66, "getproperty", "2",     -1, 1, 0, OP_STACK_NS},
87 {0x65, "getscopeobject", "u",   0, 1, 0, 0}, // u = index into scope stack
88 {0x6c, "getslot", "u",         -1, 1, 0, 0},
89 {0x04, "getsuper", "2",        -1, 1, 0, OP_STACK_NS},
90 {0xaf, "greaterthan", "",      -2, 1, 0, 0},
91 {0xb0, "greaterequals", "",    -2, 1, 0, 0},
92 {0x1f, "hasnext", "",          -2, 1, 0, 0},
93 {0x32, "hasnext2", "rr",        0, 1, 0, OP_REGISTER},
94 {0x13, "ifeq", "j",            -2, 0, 0, OP_BRANCH},
95 {0x12, "iffalse", "j",         -1, 0, 0, OP_BRANCH},
96 {0x18, "ifge", "j",            -2, 0, 0, OP_BRANCH},
97 {0x17, "ifgt", "j",            -2, 0, 0, OP_BRANCH},
98 {0x16, "ifle", "j",            -2, 0, 0, OP_BRANCH},
99 {0x15, "iflt", "j",            -2, 0, 0, OP_BRANCH},
100 {0x0f, "ifnge", "j",           -2, 0, 0, OP_BRANCH},
101 {0x0e, "ifngt", "j",           -2, 0, 0, OP_BRANCH},
102 {0x0d, "ifnle", "j",           -2, 0, 0, OP_BRANCH},
103 {0x0c, "ifnlt", "j",           -2, 0, 0, OP_BRANCH},
104 {0x14, "ifne", "j",            -2, 0, 0, OP_BRANCH},
105 {0x19, "ifstricteq", "j",      -2, 0, 0, OP_BRANCH},
106 {0x1a, "ifstrictne", "j",      -2, 0, 0, OP_BRANCH},
107 {0x11, "iftrue", "j",          -1, 0, 0, OP_BRANCH},
108 {0xb4, "in", "",               -2, 1, 0, 0},
109 {0x92, "inclocal", "r",         0, 0, 0, OP_REGISTER},
110 {0xc2, "inclocal_i", "r",       0, 0, 0, OP_REGISTER},
111 {0x91, "increment", "",        -1, 1, 0, 0},
112 {0xc0, "increment_i", "",      -1, 1, 0, 0},
113 {0x68, "initproperty", "2",    -2, 0, 0, OP_STACK_NS},
114 {0xb1, "instanceof", "",       -2, 1, 0, 0},
115 {0xb2, "istype", "2",          -1, 1, 0, 0}, // may not be a runtime multiname
116 {0xb3, "istypelate", "",       -2, 1, 0, 0},
117 {0x10, "jump", "j",             0, 0, 0, OP_JUMP},
118 {0x08, "kill", "r",             0, 0, 0, OP_REGISTER},
119 {0x09, "label", "",             0, 0, 0, OP_LABEL},
120 {0xae, "lessequals", "",       -2, 1, 0, 0},
121 {0xad, "lessthan", "",         -2, 1, 0, 0},
122 {0x1b, "lookupswitch", "S",    -1, 0, 0, OP_LOOKUPSWITCH},
123 {0xa5, "lshift", "",           -2, 1, 0, 0},
124 {0xa4, "modulo", "",           -2, 1, 0, 0},
125 {0xa2, "multiply", "",         -2, 1, 0, 0},
126 {0xc7, "multiply_i", "",       -2, 1, 0, 0},
127 {0x90, "negate", "",           -1, 1, 0, 0},
128 {0xc4, "negate_i", "",         -1, 1, 0, 0},
129 {0x57, "newactivation", "",     0, 1, 0, OP_NEED_ACTIVATION},
130 {0x56, "newarray", "n",         0, 1, 0, OP_STACK_ARGS},
131 {0x5a, "newcatch", "u",         0, 1, 0, 0}, //u = index into exception_info
132 #define OP_NEWCLASS 0x58
133 {0x58, "newclass", "c",        -1, 1, 0, 0}, //c = index into class_info
134 #define OP_NEWFUNCTION 0x40
135 {0x40, "newfunction", "m",      0, 1, 0, 0}, //i = index into method_info
136 {0x55, "newobject", "n",        0, 1, 0, OP_STACK_ARGS2},
137 {0x1e, "nextname", "",         -2, 1, 0, 0},
138 {0x23, "nextvalue", "",        -2, 1, 0, 0},
139 {0x02, "nop", "",               0, 0, 0, 0},
140 {0x96, "not", "",              -1, 1, 0 ,0},
141 {0x29, "pop", "",              -1, 0, 0, 0},
142 {0x1d, "popscope", "",          0, 0,-1, 0},
143 {0x24, "pushbyte", "b",         0, 1, 0, 0},
144 {0x2f, "pushdouble", "f",       0, 1, 0, 0}, //index into floats
145 {0x27, "pushfalse", "",         0, 1, 0, 0},
146 {0x2d, "pushint", "I",          0, 1, 0, 0}, //index into ints
147 {0x31, "pushnamespace", "u",    0, 1, 0, 0}, //index into namespace TODO
148 {0x28, "pushnan", "",           0, 1, 0, 0},
149 {0x20, "pushnull", "",          0, 1, 0, 0},
150 {0x30, "pushscope", "",        -1, 0, 1, 0},
151 {0x25, "pushshort", "u",        0, 1, 0, 0},
152 {0x2c, "pushstring", "s",       0, 1, 0, 0},
153 {0x26, "pushtrue", "",          0, 1, 0, 0},
154 {0x2e, "pushuint", "U",         0, 1, 0, 0}, //index into uints
155 {0x21, "pushundefined", "",     0, 1, 0, 0},
156 {0x1c, "pushwith", "",         -1, 0, 1, 0},
157 {0x48, "returnvalue", "",      -1, 0, 0, OP_RETURN},
158 {0x47, "returnvoid", "",        0, 0, 0, OP_RETURN},
159 {0xa6, "rshift", "",           -2, 1, 0, 0},
160 {0x63, "setlocal", "r",        -1, 0, 0, OP_REGISTER},
161 {0xd4, "setlocal_0", "",       -1, 0, 0, OP_REGISTER},
162 {0xd5, "setlocal_1", "",       -1, 0, 0, OP_REGISTER},
163 {0xd6, "setlocal_2", "",       -1, 0, 0, OP_REGISTER},
164 {0xd7, "setlocal_3", "",       -1, 0, 0, OP_REGISTER},
165 {0x6f, "setglobalslot", "u",   -1, 0, 0, 0},
166 {0x61, "setproperty", "2",     -2, 0, 0, OP_STACK_NS},
167 {0x6d, "setslot", "u",         -2, 0, 0, 0},
168 {0x05, "setsuper", "2",        -2, 0, 0, OP_STACK_NS},
169 {0xac, "strictequals", "",     -2, 1, 0, 0},
170 {0xa1, "subtract", "",         -2, 1, 0, 0},
171 {0xc6, "subtract_i", "",       -2, 1, 0, 0},
172 {0x2b, "swap", "",             -2, 2, 0, 0},
173 {0x03, "throw", "",            -1, 0, 0, OP_THROW},
174 {0x95, "typeof", "",           -1, 1, 0, 0},
175 {0xa7, "urshift", "",          -2, 1, 0, 0},
176 };
177
178 static U8 op2index[256] = {254};
179
180 opcode_t* opcode_get(U8 op)
181 {
182     int t;
183     if(op2index[0]==254) {
184         memset(op2index, 255, sizeof(op2index));
185         for(t=0;t<sizeof(opcodes)/sizeof(opcodes[0]);t++) {
186             op2index[opcodes[t].opcode] = t;
187         }
188     }
189     if(op2index[op]!=255)
190         return &opcodes[op2index[op]];
191     return 0;
192 }
193
194 static code_t*pos2code(code_t**bytepos, code_t*c, int pos, int len)
195 {
196     if(c) {
197         pos+=c->pos;
198     }
199     if(pos < 0 ||
200        pos > len ||
201       (pos!=len && !bytepos[pos])) {
202         /* flex likes to generate these. yuck. */
203         if(c) {
204             opcode_t*op = opcode_get(c->opcode);
205             fprintf(stderr, "Warning: Invalid jump instruction \"%s\" from %d to %d (%d)\n", op->name, c->pos, pos, len);
206         } else {
207             fprintf(stderr, "Warning: Invalid jump to %d (%d)\n", pos, len);
208         }
209         return 0;
210     } else {
211         if(pos==len) {
212             //opcode_t*op = opcode_get(c->opcode);
213             //fprintf(stderr, "Warning: jump beyond end of code in instruction %s at position %d\n", op->name, c->pos);
214             return 0;
215         } else {
216             return bytepos[pos];
217         }
218     }
219 }
220 code_t* code_atposition(codelookup_t*l, int pos)
221 {
222     return pos2code(l->bytepos, 0, pos, l->len);
223 }
224
225 void lookupswitch_print(lookupswitch_t*l)
226 {
227     printf("default: %08x\n", l->def);
228     code_list_t*t = l->targets;
229     while(t) {
230         printf("target: %08x\n", t->code);
231         t = t->next;
232     }
233 }
234
235 code_t*code_parse(TAG*tag, int len, abc_file_t*file, pool_t*pool, codelookup_t**codelookup)
236 {
237     code_t*head=0;
238     code_t*code=0;
239     int start=tag->pos;
240     int end=tag->pos+len;
241     //printf("-->\n");fflush(stdout);
242
243     code_t**bytepos = rfx_calloc(sizeof(code_t*)*len);
244         
245     while(tag->pos<end) {
246         int codepos = tag->pos-start;
247         U8 opcode = swf_GetU8(tag);
248         opcode_t*op = opcode_get(opcode);
249         if(!op) {
250             fprintf(stderr, "Can't parse opcode %02x\n", opcode);
251             return head;
252         }
253         //printf("%s\n", op->name);fflush(stdout);
254         NEW(code_t,c);
255         c->pos = codepos;
256
257         bytepos[codepos] = c;
258
259         if(!head) {
260             head = code = c;
261         } else {
262             code->next = c;
263             code = c;
264         }
265
266         c->opcode = opcode;
267
268         char*p = op->params;
269         int pos = 0;
270         while(*p) {
271             void*data = 0;
272             if(*p == 'n') { // number
273                 data = (void*)(ptroff_t)swf_GetU30(tag);
274             } else if(*p == '2') { //multiname
275                 data = multiname_clone(pool_lookup_multiname(pool, swf_GetU30(tag)));
276             } else if(*p == 'U') { //uint
277                 data = (void*)(ptroff_t)pool_lookup_uint(pool, swf_GetU30(tag));
278             } else if(*p == 'I') { //int
279                 data = (void*)(ptroff_t)pool_lookup_int(pool, swf_GetU30(tag));
280             } else if(*p == 'f') { //int
281                 double*fp = malloc(sizeof(double));
282                 *fp = pool_lookup_float(pool, swf_GetU30(tag));
283                 data = fp;
284             } else if(*p == 'm') { //method
285                 data = array_getvalue(file->methods, swf_GetU30(tag));
286             } else if(*p == 'c') { //classinfo
287                 data = array_getvalue(file->classes, swf_GetU30(tag));
288             } else if(*p == 'i') {
289                 data = array_getvalue(file->method_bodies, swf_GetU30(tag));
290             } else if(*p == 'u') { // generic integer
291                 data = (void*)(ptroff_t)swf_GetU30(tag);
292             } else if(*p == 'r') { // local register
293                 data = (void*)(ptroff_t)swf_GetU30(tag);
294             } else if(*p == 'b') { // byte
295                 data = (void*)(ptroff_t)swf_GetU8(tag);
296             } else if(*p == 'j') { // jump
297                 int j = swf_GetS24(tag);
298                 data = (void*)(ptroff_t)j;
299             } else if(*p == 's') { // string
300                 data = strdup((char*)pool_lookup_string(pool, swf_GetU30(tag)));
301             } else if(*p == 'D') { // debug
302                 /*type, usually 1*/
303                 U8 type = swf_GetU8(tag);
304                 if(type!=1) 
305                     fprintf(stderr, "Unknown debug type: %02x\n", type);
306                 /*register name*/
307                 code->data[0] = strdup((char*)pool_lookup_string(pool, swf_GetU30(tag)));
308                 /*register index*/
309                 code->data[1] = (void*)(ptroff_t)swf_GetU8(tag);
310                 /*unused*/
311                 swf_GetU30(tag);
312             } else if(*p == 'S') { // switch statement
313                 lookupswitch_t*l = malloc(sizeof(lookupswitch_t));
314                 l->def = (code_t*)(ptroff_t)swf_GetS24(tag);
315                 l->targets = list_new();
316                 int num = swf_GetU30(tag)+1;
317                 int t;
318                 for(t=0;t<num;t++) 
319                     list_append(l->targets, (code_t*)(ptroff_t)swf_GetS24(tag));
320                 data = l;
321             } else {
322                 printf("Can't parse opcode param type \"%c\" (for op %02x %s).\n", *p, code->opcode, op->name);
323                 return 0;
324             }
325             if(data)
326                 code->data[pos++] = data;
327             p++;
328         }
329     }
330
331 //#define DEBUG_BYTES
332 #ifdef DEBUG_BYTES
333     int t;
334     for(t=0;t<len;t++) {
335         code_t*c = bytepos[t];
336         if(c) {
337             opcode_t*op = opcode_get(c->opcode);
338             if(op->flags & (OP_JUMP|OP_BRANCH)) {
339                 printf("%5d) %02x %s %d\n", t, tag->data[start+t], op->name, c->data[0]);
340             } else {
341                 printf("%5d) %02x %s\n", t, tag->data[start+t], op->name);
342             }
343         } else {
344             printf("%5d) %02x\n", t, tag->data[start+t]);
345         }
346     }
347     //printf("%5d) %02x\n", t, tag->data[start+t]);
348 #endif
349
350     code_t*c = head;
351     while(c) {
352         opcode_t*op = opcode_get(c->opcode);
353         if(op->flags & (OP_JUMP|OP_BRANCH)) {
354             int j = ((int)(ptroff_t)c->data[0]);
355             c->branch = pos2code(bytepos,c,j+4,len);
356         } else if(op->flags & (OP_LOOKUPSWITCH)) {
357             lookupswitch_t*l = (lookupswitch_t*)c->data[0];
358             int offset = 0;
359             l->def = pos2code(bytepos,c,(ptroff_t)l->def+offset,len);
360             code_list_t*t=l->targets;
361             while(t) {
362                 t->code = pos2code(bytepos,c,(ptroff_t)t->code+offset,len);
363                 t = t->next;
364             }
365         }
366         c = c->next;
367     } 
368
369     if(codelookup) {
370         (*codelookup) = malloc(sizeof(codelookup_t));
371         (*codelookup)->bytepos = bytepos;
372         (*codelookup)->len = len;
373     } else {
374         free(bytepos);
375     }
376
377     return head;
378 }
379
380 void codelookup_free(codelookup_t*codelookup)
381 {
382     free(codelookup->bytepos);codelookup->bytepos=0;
383     free(codelookup);
384 }
385
386 code_t*code_find_start(code_t*c)
387 {
388     while(c && c->prev) 
389         c=c->prev;
390     return c;
391 }
392
393 void code_free(code_t*c)
394 {
395     c = code_find_start(c);
396     while(c) {
397         code_t*next = c->next;
398         opcode_t*op = opcode_get(c->opcode);
399         char*p = op?op->params:"";
400         int pos=0;
401         while(*p) {
402             void*data = c->data[pos];
403             if(*p == '2') { //multiname
404                 multiname_destroy(data);
405             } else if(strchr("sDf", *p)) {
406                 free(data);
407             } else if(strchr("S", *p)) {
408                 lookupswitch_t*l = (lookupswitch_t*)data;
409                 list_free(l->targets);l->targets=0;
410                 free(l);
411             }
412             c->data[pos]=0;
413             p++;pos++;
414         }
415         memset(c, 0, sizeof(c));
416         free(c);
417         c = next;
418     }
419 }
420
421 static int opcode_write(TAG*tag, code_t*c, pool_t*pool, abc_file_t*file, int length)
422 {
423     opcode_t*op = opcode_get(c->opcode);
424     char*p = op->params;
425     int pos = 0;
426     int len = 0;
427
428     if(tag)
429         swf_SetU8(tag, c->opcode);
430     len++;
431
432     while(*p) {
433         void*data = c->data[pos++];
434         assert(pos<=2);
435         if(*p == 'n') { // number
436             len += swf_SetU30(tag, (ptroff_t)data);
437         } else if(*p == '2') { //multiname
438             multiname_t*m = (multiname_t*)data;
439             len += swf_SetU30(tag, pool_register_multiname(pool, m));
440         } else if(*p == 'm') { //method
441             abc_method_t*m = (abc_method_t*)data;
442             len += swf_SetU30(tag, m->index);
443         } else if(*p == 'c') { //classinfo 
444             abc_class_t*cls = (abc_class_t*)data;
445             len += swf_SetU30(tag, cls->index);
446         } else if(*p == 'i') { //methodbody
447             abc_method_body_t*m = (abc_method_body_t*)data;
448             len += swf_SetU30(tag, m->index);
449         } else if(*p == 'I') { // int
450             len += swf_SetU30(tag, pool_register_int(pool, (ptroff_t)data));
451         } else if(*p == 'U') { // uint
452             len += swf_SetU30(tag, pool_register_uint(pool, (ptroff_t)data));
453         } else if(*p == 'f') { //  float
454             len += swf_SetU30(tag, pool_register_float(pool, *(double*)data));
455         } else if(*p == 'u') { // integer
456             len += swf_SetU30(tag, (ptroff_t)data);
457         } else if(*p == 'r') { // integer
458             len += swf_SetU30(tag, (ptroff_t)data);
459         } else if(*p == 'b') { // byte
460             if(tag)
461                 swf_SetU8(tag, (ptroff_t)data);
462             len++;
463         } else if(*p == 'j') { // jump
464             int skip = length-c->pos-4;
465             if(c->branch) 
466                 skip = (c->branch->pos) - c->pos - 4;
467             len += swf_SetS24(tag, skip);
468         } else if(*p == 's') { // string
469             int index = pool_register_string(pool, data);
470             len += swf_SetU30(tag, index);
471         } else if(*p == 'D') { // debug statement
472             if(tag)
473                 swf_SetU8(tag, 1);
474             len++;
475             len+=swf_SetU30(tag, pool_register_string(pool,c->data[0]));
476             if(tag)
477                 swf_SetU8(tag, (ptroff_t)c->data[1]);
478             len++;
479             len+=swf_SetU30(tag, 0);
480         } else if(*p == 'S') { // switch statement
481             lookupswitch_t*l = (lookupswitch_t*)data;
482             int offset = 0;
483             len+=swf_SetS24(tag, l->def->pos-c->pos+offset); //default
484             code_list_t*t = l->targets;
485             if(list_length(t)) {
486                 len+=swf_SetU30(tag, list_length(t)-1); //nr-1
487                 code_list_t*t = l->targets;
488                 while(t) {
489                     len+=swf_SetS24(tag, t->code->pos - c->pos+offset);
490                     t = t->next;
491                 }
492             } else {
493                 len+=swf_SetU30(tag, 0); //nr-1
494                 len+=swf_SetS24(tag, l->def->pos-c->pos+offset);
495             }
496         } else {
497             printf("Can't parse opcode param type \"%c\"\n", *p);
498         }
499         p++;
500     }
501     return len;
502 }
503
504 void code_write(TAG*tag, code_t*code, pool_t*pool, abc_file_t*file)
505 {
506     code = code_find_start(code);
507     int pos = 0;
508     int length = 0;
509     code_t*c = code;
510     while(c) {
511         c->pos = pos;
512         pos += opcode_write(0, c, pool, file, 0);
513         c = c->next;
514     }
515     length = pos;
516     swf_SetU30(tag, pos);
517     int start = tag->len;
518     c = code;
519     pos = 0;
520     while(c) {
521         opcode_t*op = opcode_get(code->opcode);
522         if(op->flags&(OP_BRANCH|OP_JUMP)) {
523             int skip = 0;
524         }
525         pos += opcode_write(tag, c, pool, file, length);
526         c = c->next;
527     }
528     assert(tag->len - start == pos);
529 }
530
531 typedef struct {
532     int stackpos;
533     int scopepos;
534     code_t*code;
535     char seen;
536 } stackpos_t;
537
538 typedef struct {
539     stackpos_t*stack;
540     int num;
541     int maxlocal;
542     int maxstack;
543     int maxscope;
544     int flags;
545 } currentstats_t;
546
547 static int stack_minus(code_t*c)
548 {
549     opcode_t*op = opcode_get(c->opcode);
550     if(op->stack_minus>0) {
551         fprintf(stderr, "Invalid opcode entry %02x %s\n", c->opcode, op->name);
552     }
553     int stack = op->stack_minus;
554     if(op->flags&OP_STACK_NS) {
555         multiname_t*m = (multiname_t*)c->data[0];
556         if(multiname_late_namespace(m))
557             stack--;
558         if(multiname_late_name(m))
559             stack--;
560     } 
561     if(op->flags&OP_STACK_ARGS || op->flags&OP_STACK_ARGS2) {
562         assert(strchr(op->params, 'n'));
563         int nr = (ptroff_t)(op->params[0]=='n'?c->data[0]:c->data[1]);
564         stack-=nr;
565         if(op->flags&OP_STACK_ARGS2)
566             stack-=nr;
567     }
568     return stack;
569 }
570 static void handleregister(currentstats_t*stats, int reg)
571 {
572     if(reg+1 > stats->maxlocal)
573         stats->maxlocal = reg+1;
574 }
575
576 static void dumpstack(currentstats_t*stats)
577 {
578     int t;
579     for(t=0;t<stats->num;t++) {
580         code_t*c = stats->stack[t].code;
581         opcode_t*op = opcode_get(c->opcode);
582         printf("%5d) %c %d:%d %s", t, stats->stack[t].seen?'x':'|', 
583                                stats->stack[t].stackpos,
584                                stats->stack[t].scopepos,
585                                op->name);
586
587         if(op->flags&(OP_BRANCH|OP_JUMP)) {
588             if(c->branch)
589                 printf(" ->%d\n", c->branch->pos);
590             else
591                 printf(" 00000000\n");
592         }
593         if(op->params[0]=='2') {
594             printf(" %s", multiname_tostring(c->data[0]));
595         }
596         printf("\n");
597     }
598 }
599
600 static char callcode(currentstats_t*stats, int pos, int stack, int scope)
601 {
602     while(pos<stats->num) {
603         if(stats->stack[pos].seen) {
604             if(stats->stack[pos].stackpos != stack ||
605                stats->stack[pos].scopepos != scope) {
606                 //dumpstack(stats);
607                 fprintf(stderr, "Stack mismatch at pos %d\n", pos);
608                 fprintf(stderr, "Should be: %d:%d, is: %d:%d\n", stack, scope,
609                     stats->stack[pos].stackpos, stats->stack[pos].scopepos);
610                
611                 /* return error here if we do verification */
612                 //return 0;
613             }
614             return 1;
615         }
616     
617         stats->stack[pos].seen = 1;
618         stats->stack[pos].stackpos = stack;
619         stats->stack[pos].scopepos = scope;
620
621         code_t*c = stats->stack[pos].code;
622         opcode_t*op = opcode_get(c->opcode);
623         
624         //printf("Walking %s at position %d, stack=%d, scope=%d\n", op->name, pos, stack, scope);
625
626         stack += stack_minus(c);
627
628         if(stack<0) {
629             fprintf(stderr, "error: stack underflow at %d (%s)\n", pos, op->name);
630            
631             /* if we would do true verification (if we would be a vm), this is 
632                where we would return the error 
633                return 0;
634              */
635         }
636
637         stack += op->stack_plus;
638         scope += op->scope_stack_plus;
639
640         if(stack > stats->maxstack)
641             stats->maxstack = stack;
642         if(scope > stats->maxscope)
643             stats->maxscope = scope;
644
645         if(op->flags & OP_SET_DXNS)
646             stats->flags |= FLAGS_SET_DXNS;
647         if(op->flags & OP_NEED_ACTIVATION)
648             stats->flags |= FLAGS_ACTIVATION;
649
650         if(c->opcode == OP_NEWCLASS) {
651             abc_class_t*cls = (abc_class_t*)(c->data[0]);
652             if(scope > cls->init_scope_depth)
653                 cls->init_scope_depth = scope;
654         }
655         if(c->opcode == OP_NEWFUNCTION) {
656             abc_method_t*m = (abc_method_t*)(c->data[0]);
657             if(m->body && scope > m->body->init_scope_depth)
658                 m->body->init_scope_depth = scope;
659         }
660         
661         if(op->flags & OP_REGISTER) {
662             char*p = op->params;
663             int pos = 0;
664             char ok=0;
665             while(*p) {
666                 if(*p=='r') {
667                     handleregister(stats, (ptroff_t)c->data[pos]);
668                     ok = 1;
669                 }
670                 p++;
671             }
672             if(!ok) {
673                 handleregister(stats, c->opcode&3);
674             }
675         }
676         if(op->flags&OP_RETURN) {
677             if(OP_RETURN==0x48/*returnvalue*/) {
678                 if(stack!=1)
679                     fprintf(stderr, "return(value) with stackposition %d\n", stack);
680             } else if(OP_RETURN==0x47) {
681                 if(stack!=0)
682                     fprintf(stderr, "return(void) with stackposition %d\n", stack);
683             }
684         }
685         if(op->flags & (OP_THROW|OP_RETURN))
686             return 1;
687         if(op->flags & OP_JUMP) {
688             if(!c->branch) {
689                 fprintf(stderr, "Error: Invalid jump target in instruction %s at position %d.\n", op->name, pos);
690                 return 0;
691             }
692             c = c->branch;
693             pos = c->pos;
694             continue;
695         }
696         if(op->flags & OP_BRANCH) {
697             if(!c->branch) {
698                 fprintf(stderr, "Error: Invalid jump target in instruction %s at position %d\n", op->name, pos);
699                 return 0;
700             }
701             int newpos = c->branch->pos;
702             if(!callcode(stats, newpos, stack, scope))
703                 return 0;
704         }
705         if(op->flags & OP_LOOKUPSWITCH) {
706             lookupswitch_t*l = c->data[0];
707             if(!l->def) {
708                 fprintf(stderr, "Error: Invalid jump target in instruction %s at position %d\n", op->name, pos);
709                 return 0;
710             }
711             if(!callcode(stats, l->def->pos, stack, scope))
712                 return 0;
713             code_list_t*t = l->targets;
714             while(t) {
715                 if(!t->code) {
716                     fprintf(stderr, "Error: Invalid jump target in instruction %s at position %d\n", op->name, pos);
717                     return 0;
718                 }
719                 if(!callcode(stats, t->code->pos, stack, scope))
720                     return 0;
721                 t = t->next;
722             }
723         }
724     
725         pos++;
726         if(pos<stats->num) {
727             assert(c->next == stats->stack[pos].code);
728         }
729     }
730     return 1;
731 }
732
733 static currentstats_t* code_get_stats(code_t*code, exception_list_t*exceptions) 
734 {
735     code = code_find_start(code);
736     int num = 0;
737     code_t*c = code;
738     while(c) {
739         num++;
740         c = c->next;
741     }
742     currentstats_t* current = malloc(sizeof(currentstats_t));
743     current->stack = rfx_calloc(sizeof(stackpos_t)*num);
744     current->maxlocal = 0;
745     current->maxstack = 0;
746     current->maxscope = 0;
747     current->num = num;
748     current->flags = 0;
749
750 //#define DEBUG_BYTES
751 #ifdef DEBUG_BYTES
752     int t;
753     c = code;
754     for(t=0;t<num;t++) {
755         opcode_t*op = opcode_get(c->opcode);
756         if(op->flags & (OP_JUMP|OP_BRANCH)) {
757             printf("%5d) %s %08x\n", t, op->name, c->branch);
758         } else if(op->params[0]=='2') {
759             printf("%5d) %s %s\n", t, op->name, multiname_tostring(c->data[0]));
760         } else {
761             printf("%5d) %s\n", t, op->name);
762         }
763         c = c->next;
764     }
765     //printf("%5d) %02x\n", t, tag->data[start+t]);
766 #endif
767
768     num = 0;
769     c = code;
770     while(c) {
771         //crosslink
772         current->stack[num].code = c;
773         c->pos = num;
774         num++;
775         c = c->next;
776     }
777
778     if(!callcode(current, 0, 0, 0)) {
779         free(current);
780         return 0;
781     }
782     exception_list_t*e = exceptions;
783     while(e) {
784         if(e->exception->target)
785             callcode(current, e->exception->target->pos, 1, 0);
786         e = e->next;
787     }
788
789     return current;
790 }
791
792 void stats_free(currentstats_t*stats)
793 {
794     if(stats) {
795         free(stats->stack);stats->stack=0;
796         free(stats);
797     }
798 }
799
800 int code_dump(code_t*c, exception_list_t*exceptions, abc_file_t*file, char*prefix, FILE*fo)
801 {
802     exception_list_t*e = exceptions;
803     c = code_find_start(c);
804     currentstats_t*stats =  code_get_stats(c, exceptions);
805
806     int pos = 0;
807     while(c) {
808         U8 opcode = c->opcode;
809         char found = 0;
810         opcode_t*op = opcode_get(opcode);
811
812         e = exceptions;
813         while(e) {
814             if(c==e->exception->from)
815                 fprintf(fo, "%s   TRY {\n", prefix);
816             if(c==e->exception->target) {
817                 char*s1 = multiname_tostring(e->exception->exc_type);
818                 char*s2 = multiname_tostring(e->exception->var_name);
819                 fprintf(fo, "%s   CATCH(%s %s)\n", prefix, s1, s2);
820                 free(s1);
821                 free(s2);
822             }
823             e = e->next;
824         }
825
826         if(!op) {
827             fprintf(stderr, "Can't parse opcode %02x.\n", opcode);
828             return 0;
829         } else {
830             char*p = op->params;
831             char first = 1;
832             int i=0;
833
834             if(stats) {
835                 fprintf(fo, "%s%5d) %c %d:%d %s ", prefix, c->pos, stats->stack[c->pos].seen?'x':'|', 
836                                        stats->stack[c->pos].stackpos,
837                                        stats->stack[c->pos].scopepos,
838                                        op->name);
839             } else {
840                 fprintf(fo, "%s%5d) ? ?:? %s ", prefix, c->pos, op->name);
841             }
842
843             while(*p) {
844                 void*data = c->data[i];
845                 if(i>0)
846                     printf(", ");
847
848                 if(*p == 'n') {
849                     int n = (ptroff_t)data;
850                     fprintf(fo, "%d params", n);
851                 } else if(*p == '2') {
852                     multiname_t*n = (multiname_t*)data;
853                     char* m = multiname_tostring(n);
854                     fprintf(fo, "%s", m);
855                     free(m);
856                 } else if(*p == 'm') {
857                     abc_method_t*m = (abc_method_t*)data;
858                     fprintf(fo, "[method %s]", m->name);
859                 } else if(*p == 'c') {
860                     abc_class_t*cls = (abc_class_t*)data;
861                     char*classname = multiname_tostring(cls->classname);
862                     fprintf(fo, "[classinfo %s]", classname);
863                     free(classname);
864                 } else if(*p == 'i') {
865                     abc_method_body_t*b = (abc_method_body_t*)data;
866                     fprintf(fo, "[methodbody]");
867                 } else if(*p == 'u' || *p == 'I' || *p == 'U') {
868                     int n = (ptroff_t)data;
869                     fprintf(fo, "%d", n);
870                 } else if(*p == 'f') {
871                     double f = *(double*)data;
872                     fprintf(fo, "%f", f);
873                 } else if(*p == 'r') {
874                     int n = (ptroff_t)data;
875                     fprintf(fo, "r%d", n);
876                 } else if(*p == 'b') {
877                     int b = (ptroff_t)data;
878                     fprintf(fo, "%02x", b);
879                 } else if(*p == 'j') {
880                     if(c->branch)
881                         fprintf(fo, "->%d", c->branch->pos);
882                     else
883                         fprintf(fo, "%08x", c->branch);
884                 } else if(*p == 's') {
885                     fprintf(fo, "\"%s\"", data);
886                 } else if(*p == 'D') {
887                     fprintf(fo, "[register %02x=%s]", (ptroff_t)c->data[1], (char*)c->data[0]);
888                 } else if(*p == 'S') {
889                     lookupswitch_t*l = c->data[0];
890                     fprintf(fo, "[");
891                     if(l->def)
892                         fprintf(fo, "default->%d", l->def->pos);
893                     else
894                         fprintf(fo, "default->00000000", l->def->pos);
895                     code_list_t*t = l->targets;
896                     while(t) {
897                         if(t->code)
898                             fprintf(fo, ",->%d", t->code->pos);
899                         else
900                             fprintf(fo, ",->00000000");
901                         t = t->next;
902                     }
903                     fprintf(fo, "]");
904                 } else {
905                     fprintf(stderr, "Can't parse opcode param type \"%c\"\n", *p);
906                     return 0;
907                 }
908                 p++;
909                 i++;
910                 first = 0;
911             }
912             fprintf(fo, "\n");
913         }
914         
915         e = exceptions;
916         while(e) {
917             if(c==e->exception->to) {
918                 if(e->exception->target)
919                     fprintf(fo, "%s   } // END TRY (HANDLER: %d)\n", prefix, e->exception->target->pos);
920                 else
921                     fprintf(fo, "%s   } // END TRY (HANDLER: 00000000)\n", prefix);
922             }
923             e = e->next;
924         }
925
926         pos++;
927         c = c->next;
928     }
929     stats_free(stats);
930     return 1;
931 }
932
933 codestats_t* code_get_statistics(code_t*code, exception_list_t*exceptions) 
934 {
935     currentstats_t*current = code_get_stats(code, exceptions);
936     if(!current)
937         return 0;
938     codestats_t*stats = rfx_calloc(sizeof(codestats_t));
939     stats->local_count = current->maxlocal;
940     stats->max_stack = current->maxstack;
941     stats->max_scope_depth = current->maxscope;
942     stats->flags = current->flags;
943
944     stats_free(current);current=0;
945     return stats;
946 }
947
948 void codestats_free(codestats_t*s)
949 {
950     free(s);
951 }
952
953 code_t* add_opcode(code_t*atag, U8 op)
954 {
955     code_t*tmp = (code_t*)rfx_calloc(sizeof(code_t));
956     tmp->opcode = op;
957     tmp->next = 0;
958     if(atag) {
959         tmp->prev = atag;
960         tmp->next = atag->next;
961         atag->next = tmp;
962     } else {
963         tmp->prev = 0;
964     }
965     return tmp;
966 }
967     
968 void codestats_print(codestats_t*stats)
969 {
970     printf("max_stack: %d\n", stats->max_stack);
971     printf("local_count: %d\n", stats->local_count);
972     printf("scope_depth: %d\n", stats->max_scope_depth);
973 }
974
975 code_t* code_append(code_t*code, code_t*toappend)
976 {
977     if(!code)
978         return toappend;
979     if(!toappend)
980         return code;
981     //find end of first list
982     while(code->next) {
983         code = code->next;
984     }
985     code_t*start=toappend;
986     //and start of second list
987     while(start->prev) {
988         start = start->prev;
989     }
990     code->next = start;
991     start->prev = code;
992     return toappend;
993 }
994