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