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