moved OPCODE definitions to opcodes.h
[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- followed by 0x01 (might be the number of stack params)
200 {0x53, "xxx1", "",             -1, 0, 0, 0},
201 {0x01, "xxx2", "",              0, 0, 0, 0},
202
203 /* dummy instruction. Warning: this one is not actually supported by flash */
204 {0xff, "__break__", "",             0, 0, 0, OP_RETURN},
205 };
206
207 static U8 op2index[256] = {254};
208
209 opcode_t* opcode_get(U8 op)
210 {
211     int t;
212     if(op2index[0]==254) {
213         memset(op2index, 255, sizeof(op2index));
214         for(t=0;t<sizeof(opcodes)/sizeof(opcodes[0]);t++) {
215             op2index[opcodes[t].opcode] = t;
216         }
217     }
218     if(op2index[op]!=255)
219         return &opcodes[op2index[op]];
220     return 0;
221 }
222
223 static code_t*pos2code(code_t**bytepos, code_t*c, int pos, int len)
224 {
225     if(c) {
226         pos+=c->pos;
227     }
228     if(pos < 0 ||
229        pos > len ||
230       (pos!=len && !bytepos[pos])) {
231         /* flex likes to generate these. yuck. */
232         if(c) {
233             opcode_t*op = opcode_get(c->opcode);
234             fprintf(stderr, "Warning: Invalid jump instruction \"%s\" from %d to %d (%d)\n", op->name, c->pos, pos, len);
235         } else {
236             fprintf(stderr, "Warning: Invalid jump to %d (%d)\n", pos, len);
237         }
238         return 0;
239     } else {
240         if(pos==len) {
241             //opcode_t*op = opcode_get(c->opcode);
242             //fprintf(stderr, "Warning: jump beyond end of code in instruction %s at position %d\n", op->name, c->pos);
243             return 0;
244         } else {
245             return bytepos[pos];
246         }
247     }
248 }
249 code_t* code_atposition(codelookup_t*l, int pos)
250 {
251     return pos2code(l->bytepos, 0, pos, l->len);
252 }
253
254 void lookupswitch_print(lookupswitch_t*l)
255 {
256     printf("default: %08x\n", l->def);
257     code_list_t*t = l->targets;
258     while(t) {
259         printf("target: %08x\n", t->code);
260         t = t->next;
261     }
262 }
263
264 code_t*code_parse(TAG*tag, int len, abc_file_t*file, pool_t*pool, codelookup_t**codelookup)
265 {
266     code_t*head=0;
267     code_t*code=0;
268     int start=tag->pos;
269     int end=tag->pos+len;
270     //printf("-->\n");fflush(stdout);
271
272     code_t**bytepos = rfx_calloc(sizeof(code_t*)*len);
273         
274     while(tag->pos<end) {
275         int codepos = tag->pos-start;
276         U8 opcode = swf_GetU8(tag);
277         opcode_t*op = opcode_get(opcode);
278         if(!op) {
279             fprintf(stderr, "Can't parse opcode %02x\n", opcode);
280             continue;
281         }
282         //printf("%s\n", op->name);fflush(stdout);
283         NEW(code_t,c);
284         c->pos = codepos;
285
286         bytepos[codepos] = c;
287
288         if(!head) {
289             head = code = c;
290         } else {
291             code->next = c;
292             code = c;
293         }
294
295         c->opcode = opcode;
296
297         char*p = op->params;
298         int pos = 0;
299         while(*p) {
300             void*data = 0;
301             if(*p == 'n') { // number
302                 data = (void*)(ptroff_t)swf_GetU30(tag);
303             } else if(*p == '2') { //multiname
304                 data = multiname_clone(pool_lookup_multiname(pool, swf_GetU30(tag)));
305             } else if(*p == 'U') { //uint
306                 data = (void*)(ptroff_t)pool_lookup_uint(pool, swf_GetU30(tag));
307             } else if(*p == 'I') { //int
308                 data = (void*)(ptroff_t)pool_lookup_int(pool, swf_GetU30(tag));
309             } else if(*p == 'f') { //int
310                 double*fp = malloc(sizeof(double));
311                 *fp = pool_lookup_float(pool, swf_GetU30(tag));
312                 data = fp;
313             } else if(*p == 'm') { //method
314                 data = array_getvalue(file->methods, swf_GetU30(tag));
315             } else if(*p == 'c') { //classinfo
316                 data = array_getvalue(file->classes, swf_GetU30(tag));
317             } else if(*p == 'i') {
318                 data = array_getvalue(file->method_bodies, swf_GetU30(tag));
319             } else if(*p == 'u') { // generic integer
320                 data = (void*)(ptroff_t)swf_GetU30(tag);
321             } else if(*p == 'r') { // local register
322                 data = (void*)(ptroff_t)swf_GetU30(tag);
323             } else if(*p == 'b') { // byte
324                 data = (void*)(ptroff_t)swf_GetU8(tag);
325             } else if(*p == 'j') { // jump
326                 int j = swf_GetS24(tag);
327                 data = (void*)(ptroff_t)j;
328             } else if(*p == 's') { // string
329                 data = strdup((char*)pool_lookup_string(pool, swf_GetU30(tag)));
330             } else if(*p == 'D') { // debug
331                 /*type, usually 1*/
332                 U8 type = swf_GetU8(tag);
333                 if(type!=1) 
334                     fprintf(stderr, "Unknown debug type: %02x\n", type);
335                 /*register name*/
336                 code->data[0] = strdup((char*)pool_lookup_string(pool, swf_GetU30(tag)));
337                 /*register index*/
338                 code->data[1] = (void*)(ptroff_t)swf_GetU8(tag);
339                 /*unused*/
340                 swf_GetU30(tag);
341             } else if(*p == 'S') { // switch statement
342                 lookupswitch_t*l = malloc(sizeof(lookupswitch_t));
343                 l->def = (code_t*)(ptroff_t)swf_GetS24(tag);
344                 l->targets = list_new();
345                 int num = swf_GetU30(tag)+1;
346                 int t;
347                 for(t=0;t<num;t++) 
348                     list_append(l->targets, (code_t*)(ptroff_t)swf_GetS24(tag));
349                 data = l;
350             } else {
351                 printf("Can't parse opcode param type \"%c\" (for op %02x %s).\n", *p, code->opcode, op->name);
352                 return 0;
353             }
354             if(data)
355                 code->data[pos++] = data;
356             p++;
357         }
358     }
359
360 //#define DEBUG_BYTES
361 #ifdef DEBUG_BYTES
362     int t;
363     for(t=0;t<len;t++) {
364         code_t*c = bytepos[t];
365         if(c) {
366             opcode_t*op = opcode_get(c->opcode);
367             if(op->flags & (OP_JUMP|OP_BRANCH)) {
368                 printf("%5d) %02x %s %d\n", t, tag->data[start+t], op->name, c->data[0]);
369             } else {
370                 printf("%5d) %02x %s\n", t, tag->data[start+t], op->name);
371             }
372         } else {
373             printf("%5d) %02x\n", t, tag->data[start+t]);
374         }
375     }
376     //printf("%5d) %02x\n", t, tag->data[start+t]);
377 #endif
378
379     code_t*c = head;
380     while(c) {
381         opcode_t*op = opcode_get(c->opcode);
382         if(op->flags & (OP_JUMP|OP_BRANCH)) {
383             int j = ((int)(ptroff_t)c->data[0]);
384             c->branch = pos2code(bytepos,c,j+4,len);
385         } else if(op->flags & (OP_LOOKUPSWITCH)) {
386             lookupswitch_t*l = (lookupswitch_t*)c->data[0];
387             int offset = 0;
388             l->def = pos2code(bytepos,c,(ptroff_t)l->def+offset,len);
389             code_list_t*t=l->targets;
390             while(t) {
391                 t->code = pos2code(bytepos,c,(ptroff_t)t->code+offset,len);
392                 t = t->next;
393             }
394         }
395         c = c->next;
396     } 
397
398     if(codelookup) {
399         (*codelookup) = malloc(sizeof(codelookup_t));
400         (*codelookup)->bytepos = bytepos;
401         (*codelookup)->len = len;
402     } else {
403         free(bytepos);
404     }
405
406     return head;
407 }
408
409 void codelookup_free(codelookup_t*codelookup)
410 {
411     free(codelookup->bytepos);codelookup->bytepos=0;
412     free(codelookup);
413 }
414
415 code_t*code_find_start(code_t*c)
416 {
417     while(c && c->prev) 
418         c=c->prev;
419     return c;
420 }
421
422 void code_free(code_t*c)
423 {
424     c = code_find_start(c);
425     while(c) {
426         code_t*next = c->next;
427         opcode_t*op = opcode_get(c->opcode);
428         char*p = op?op->params:"";
429         int pos=0;
430         while(*p) {
431             void*data = c->data[pos];
432             if(*p == '2') { //multiname
433                 multiname_destroy(data);
434             } else if(strchr("sDf", *p)) {
435                 free(data);
436             } else if(strchr("S", *p)) {
437                 lookupswitch_t*l = (lookupswitch_t*)data;
438                 list_free(l->targets);l->targets=0;
439                 free(l);
440             }
441             c->data[pos]=0;
442             p++;pos++;
443         }
444         memset(c, 0, sizeof(c));
445         free(c);
446         c = next;
447     }
448 }
449
450 static int opcode_write(TAG*tag, code_t*c, pool_t*pool, abc_file_t*file, int length)
451 {
452     opcode_t*op = opcode_get(c->opcode);
453     char*p = op->params;
454     int pos = 0;
455     int len = 0;
456
457     if(tag)
458         swf_SetU8(tag, c->opcode);
459     len++;
460
461     while(*p) {
462         void*data = c->data[pos++];
463         assert(pos<=2);
464         if(*p == 'n') { // number
465             len += swf_SetU30(tag, (ptroff_t)data);
466         } else if(*p == '2') { //multiname
467             multiname_t*m = (multiname_t*)data;
468             len += swf_SetU30(tag, pool_register_multiname(pool, m));
469         } else if(*p == 'm') { //method
470             abc_method_t*m = (abc_method_t*)data;
471             len += swf_SetU30(tag, m->index);
472         } else if(*p == 'c') { //classinfo 
473             abc_class_t*cls = (abc_class_t*)data;
474             len += swf_SetU30(tag, cls->index);
475         } else if(*p == 'i') { //methodbody
476             abc_method_body_t*m = (abc_method_body_t*)data;
477             len += swf_SetU30(tag, m->index);
478         } else if(*p == 'I') { // int
479             len += swf_SetU30(tag, pool_register_int(pool, (ptroff_t)data));
480         } else if(*p == 'U') { // uint
481             len += swf_SetU30(tag, pool_register_uint(pool, (ptroff_t)data));
482         } else if(*p == 'f') { //  float
483             len += swf_SetU30(tag, pool_register_float(pool, *(double*)data));
484         } else if(*p == 'u') { // integer
485             len += swf_SetU30(tag, (ptroff_t)data);
486         } else if(*p == 'r') { // integer
487             len += swf_SetU30(tag, (ptroff_t)data);
488         } else if(*p == 'b') { // byte
489             if(tag)
490                 swf_SetU8(tag, (ptroff_t)data);
491             len++;
492         } else if(*p == 'j') { // jump
493             int skip = length-c->pos-4;
494             if(c->branch) 
495                 skip = (c->branch->pos) - c->pos - 4;
496             len += swf_SetS24(tag, skip);
497         } else if(*p == 's') { // string
498             int index = pool_register_string(pool, data);
499             len += swf_SetU30(tag, index);
500         } else if(*p == 'D') { // debug statement
501             if(tag)
502                 swf_SetU8(tag, 1);
503             len++;
504             len+=swf_SetU30(tag, pool_register_string(pool,c->data[0]));
505             if(tag)
506                 swf_SetU8(tag, (ptroff_t)c->data[1]);
507             len++;
508             len+=swf_SetU30(tag, 0);
509         } else if(*p == 'S') { // switch statement
510             lookupswitch_t*l = (lookupswitch_t*)data;
511             int offset = 0;
512             len+=swf_SetS24(tag, l->def->pos-c->pos+offset); //default
513             code_list_t*t = l->targets;
514             if(list_length(t)) {
515                 len+=swf_SetU30(tag, list_length(t)-1); //nr-1
516                 code_list_t*t = l->targets;
517                 while(t) {
518                     len+=swf_SetS24(tag, t->code->pos - c->pos+offset);
519                     t = t->next;
520                 }
521             } else {
522                 len+=swf_SetU30(tag, 0); //nr-1
523                 len+=swf_SetS24(tag, l->def->pos-c->pos+offset);
524             }
525         } else {
526             printf("Can't parse opcode param type \"%c\"\n", *p);
527         }
528         p++;
529     }
530     return len;
531 }
532
533 void code_write(TAG*tag, code_t*code, pool_t*pool, abc_file_t*file)
534 {
535     code = code_find_start(code);
536     int pos = 0;
537     int length = 0;
538     code_t*c = code;
539     while(c) {
540         c->pos = pos;
541         pos += opcode_write(0, c, pool, file, 0);
542         c = c->next;
543     }
544     length = pos;
545     swf_SetU30(tag, pos);
546     int start = tag->len;
547     c = code;
548     pos = 0;
549     while(c) {
550         opcode_t*op = opcode_get(code->opcode);
551         if(op->flags&(OP_BRANCH|OP_JUMP)) {
552             int skip = 0;
553         }
554         pos += opcode_write(tag, c, pool, file, length);
555         c = c->next;
556     }
557     assert(tag->len - start == pos);
558 }
559
560 typedef struct {
561     int stackpos;
562     int scopepos;
563     code_t*code;
564     char flags;
565     char error;
566 } stackpos_t;
567
568 typedef struct {
569     stackpos_t*stack;
570     int num;
571     int maxlocal;
572     int maxstack;
573     int maxscope;
574     int flags;
575 } currentstats_t;
576
577 static int stack_minus(code_t*c)
578 {
579     opcode_t*op = opcode_get(c->opcode);
580     if(op->stack_minus>0) {
581         fprintf(stderr, "Invalid opcode entry %02x %s\n", c->opcode, op->name);
582     }
583     int stack = op->stack_minus;
584     if(op->flags&OP_STACK_NS) {
585         multiname_t*m = (multiname_t*)c->data[0];
586         if(multiname_late_namespace(m))
587             stack--;
588         if(multiname_late_name(m))
589             stack--;
590     } 
591     if(op->flags&OP_STACK_ARGS || op->flags&OP_STACK_ARGS2) {
592         assert(strchr(op->params, 'n'));
593         int nr = (ptroff_t)(op->params[0]=='n'?c->data[0]:c->data[1]);
594         stack-=nr;
595         if(op->flags&OP_STACK_ARGS2)
596             stack-=nr;
597     }
598     return stack;
599 }
600 static void handleregister(currentstats_t*stats, int reg)
601 {
602     if(reg+1 > stats->maxlocal)
603         stats->maxlocal = reg+1;
604 }
605
606 #define FLAG_SEEN 1
607 #define FLAG_ERROR 2
608
609 static void dumpstack(currentstats_t*stats)
610 {
611     int t;
612     for(t=0;t<stats->num;t++) {
613         code_t*c = stats->stack[t].code;
614         opcode_t*op = opcode_get(c->opcode);
615         printf("%5d) %c %d:%d %s", t, (stats->stack[t].flags&FLAG_SEEN)?'x':'|', 
616                                stats->stack[t].stackpos,
617                                stats->stack[t].scopepos,
618                                op->name);
619
620         if(op->flags&(OP_BRANCH|OP_JUMP)) {
621             if(c->branch)
622                 printf(" ->%d\n", c->branch->pos);
623             else
624                 printf(" 00000000\n");
625         }
626         if(op->params[0]=='2') {
627             printf(" %s", multiname_tostring(c->data[0]));
628         }
629         printf("\n");
630     }
631 }
632
633 static char callcode(currentstats_t*stats, int pos, int stack, int scope)
634 {
635     while(pos<stats->num) {
636         if(stats->stack[pos].flags&FLAG_SEEN) {
637             if(stats->stack[pos].stackpos != stack ||
638                stats->stack[pos].scopepos != scope) {
639                 //dumpstack(stats);
640                 stats->stack[pos].flags |= FLAG_ERROR;
641                 fprintf(stderr, "Stack mismatch at pos %d\n", pos);
642                 fprintf(stderr, "Should be: %d:%d, is: %d:%d\n", stack, scope,
643                     stats->stack[pos].stackpos, stats->stack[pos].scopepos);
644                
645                 /* return error here if we do verification */
646                 //return 0;
647             }
648             return 1;
649         }
650     
651         stats->stack[pos].flags |= FLAG_SEEN;
652         stats->stack[pos].stackpos = stack;
653         stats->stack[pos].scopepos = scope;
654
655         code_t*c = stats->stack[pos].code;
656         opcode_t*op = opcode_get(c->opcode);
657         
658         //printf("Walking %s at position %d, stack=%d, scope=%d\n", op->name, pos, stack, scope);
659
660         stack += stack_minus(c);
661
662         if(stack<0) {
663             stats->stack[pos].flags |= FLAG_ERROR;
664             fprintf(stderr, "error: stack underflow at %d (%s)\n", pos, op->name);
665            
666             /* if we would do true verification (if we would be a vm), this is 
667                where we would return the error 
668                return 0;
669              */
670         }
671
672         stack += op->stack_plus;
673         scope += op->scope_stack_plus;
674
675         if(stack > stats->maxstack)
676             stats->maxstack = stack;
677         if(scope > stats->maxscope)
678             stats->maxscope = scope;
679
680         if(op->flags & OP_SET_DXNS)
681             stats->flags |= FLAGS_SET_DXNS;
682         if(op->flags & OP_NEED_ACTIVATION)
683             stats->flags |= FLAGS_ACTIVATION;
684
685         if(c->opcode == OPCODE_NEWCLASS) {
686             abc_class_t*cls = (abc_class_t*)(c->data[0]);
687             if(scope > cls->init_scope_depth)
688                 cls->init_scope_depth = scope;
689         }
690         if(c->opcode == OPCODE_NEWFUNCTION) {
691             abc_method_t*m = (abc_method_t*)(c->data[0]);
692             if(m->body && scope > m->body->init_scope_depth)
693                 m->body->init_scope_depth = scope;
694         }
695         
696         if(op->flags & OP_REGISTER) {
697             char*p = op->params;
698             int pos = 0;
699             char ok=0;
700             while(*p) {
701                 if(*p=='r') {
702                     handleregister(stats, (ptroff_t)c->data[pos]);
703                     ok = 1;
704                 }
705                 p++;
706             }
707             if(!ok) {
708                 handleregister(stats, c->opcode&3);
709             }
710         }
711         if(op->flags&OP_RETURN) {
712             if(OP_RETURN==0x48/*returnvalue*/) {
713                 if(stack!=1) {
714                     stats->stack[pos].flags |= FLAG_ERROR;
715                     fprintf(stderr, "return(value) with stackposition %d\n", stack);
716                 }
717             } else if(OP_RETURN==0x47) {
718                 if(stack!=0) {
719                     stats->stack[pos].flags |= FLAG_ERROR;
720                     fprintf(stderr, "return(void) with stackposition %d\n", stack);
721                 }
722             }
723         }
724         if(op->flags & (OP_THROW|OP_RETURN))
725             return 1;
726         if(op->flags & OP_JUMP) {
727             if(!c->branch) {
728                 stats->stack[pos].flags |= FLAG_ERROR;
729                 fprintf(stderr, "Error: Invalid jump target in instruction %s at position %d.\n", op->name, pos);
730                 return 0;
731             }
732             c = c->branch;
733             pos = c->pos;
734             continue;
735         }
736         if(op->flags & OP_BRANCH) {
737             if(!c->branch) {
738                 stats->stack[pos].flags |= FLAG_ERROR;
739                 fprintf(stderr, "Error: Invalid jump target in instruction %s at position %d\n", op->name, pos);
740                 return 0;
741             }
742             int newpos = c->branch->pos;
743             if(!callcode(stats, newpos, stack, scope))
744                 return 0;
745         }
746         if(op->flags & OP_LOOKUPSWITCH) {
747             lookupswitch_t*l = c->data[0];
748             if(!l->def) {
749                 stats->stack[pos].flags |= FLAG_ERROR;
750                 fprintf(stderr, "Error: Invalid jump target in instruction %s at position %d\n", op->name, pos);
751                 return 0;
752             }
753             if(!callcode(stats, l->def->pos, stack, scope))
754                 return 0;
755             code_list_t*t = l->targets;
756             while(t) {
757                 if(!t->code) {
758                     stats->stack[pos].flags |= FLAG_ERROR;
759                     fprintf(stderr, "Error: Invalid jump target in instruction %s at position %d\n", op->name, pos);
760                     return 0;
761                 }
762                 if(!callcode(stats, t->code->pos, stack, scope))
763                     return 0;
764                 t = t->next;
765             }
766         }
767     
768         pos++;
769         if(pos<stats->num) {
770             assert(c->next == stats->stack[pos].code);
771         }
772     }
773     return 1;
774 }
775
776 static currentstats_t* code_get_stats(code_t*code, abc_exception_list_t*exceptions) 
777 {
778     code = code_find_start(code);
779     int num = 0;
780     code_t*c = code;
781     while(c) {
782         num++;
783         c = c->next;
784     }
785     currentstats_t* current = malloc(sizeof(currentstats_t));
786     current->stack = rfx_calloc(sizeof(stackpos_t)*num);
787     current->maxlocal = 0;
788     current->maxstack = 0;
789     current->maxscope = 0;
790     current->num = num;
791     current->flags = 0;
792
793 //#define DEBUG_BYTES
794 #ifdef DEBUG_BYTES
795     int t;
796     c = code;
797     for(t=0;t<num;t++) {
798         opcode_t*op = opcode_get(c->opcode);
799         if(op->flags & (OP_JUMP|OP_BRANCH)) {
800             printf("%5d) %s %08x\n", t, op->name, c->branch);
801         } else if(op->params[0]=='2') {
802             printf("%5d) %s %s\n", t, op->name, multiname_tostring(c->data[0]));
803         } else {
804             printf("%5d) %s\n", t, op->name);
805         }
806         c = c->next;
807     }
808     //printf("%5d) %02x\n", t, tag->data[start+t]);
809 #endif
810
811     num = 0;
812     c = code;
813     while(c) {
814         //crosslink
815         current->stack[num].code = c;
816         c->pos = num;
817         num++;
818         c = c->next;
819     }
820
821     if(!callcode(current, 0, 0, 0)) {
822         free(current);
823         return 0;
824     }
825     abc_exception_list_t*e = exceptions;
826     while(e) {
827         if(e->abc_exception->target)
828             callcode(current, e->abc_exception->target->pos, 1, 0);
829         e = e->next;
830     }
831
832     return current;
833 }
834
835 void stats_free(currentstats_t*stats)
836 {
837     if(stats) {
838         free(stats->stack);stats->stack=0;
839         free(stats);
840     }
841 }
842
843 int code_dump(code_t*c, abc_exception_list_t*exceptions, abc_file_t*file, char*prefix, FILE*fo)
844 {
845     abc_exception_list_t*e = exceptions;
846     c = code_find_start(c);
847     currentstats_t*stats =  code_get_stats(c, exceptions);
848
849     int pos = 0;
850     while(c) {
851         U8 opcode = c->opcode;
852         char found = 0;
853         opcode_t*op = opcode_get(opcode);
854
855         e = exceptions;
856         while(e) {
857             if(c==e->abc_exception->from)
858                 fprintf(fo, "%s   TRY {\n", prefix);
859             if(c==e->abc_exception->target) {
860                 char*s1 = multiname_tostring(e->abc_exception->exc_type);
861                 char*s2 = multiname_tostring(e->abc_exception->var_name);
862                 fprintf(fo, "%s   CATCH(%s %s)\n", prefix, s1, s2);
863                 free(s1);
864                 free(s2);
865             }
866             e = e->next;
867         }
868
869         if(!op) {
870             fprintf(stderr, "Can't parse opcode %02x.\n", opcode);
871             return 0;
872         } else {
873             char*p = op->params;
874             char first = 1;
875             int i=0;
876
877             if(stats) {
878                 int f = stats->stack[c->pos].flags;
879                 fprintf(fo, "%s%5d) %c %d:%d %s ", prefix, c->pos, 
880                                        (f&FLAG_ERROR)?'E':((f&FLAG_SEEN)?'+':'|'),
881                                        stats->stack[c->pos].stackpos,
882                                        stats->stack[c->pos].scopepos,
883                                        op->name);
884             } else {
885                 fprintf(fo, "%s%5d) ? ?:? %s ", prefix, c->pos, op->name);
886             }
887
888             while(*p) {
889                 void*data = c->data[i];
890                 if(i>0)
891                     printf(", ");
892
893                 if(*p == 'n') {
894                     int n = (ptroff_t)data;
895                     fprintf(fo, "%d params", n);
896                 } else if(*p == '2') {
897                     multiname_t*n = (multiname_t*)data;
898                     char* m = multiname_tostring(n);
899                     fprintf(fo, "%s", m);
900                     free(m);
901                 } else if(*p == 'm') {
902                     abc_method_t*m = (abc_method_t*)data;
903                     fprintf(fo, "[method %s]", m->name);
904                 } else if(*p == 'c') {
905                     abc_class_t*cls = (abc_class_t*)data;
906                     char*classname = multiname_tostring(cls->classname);
907                     fprintf(fo, "[classinfo %s]", classname);
908                     free(classname);
909                 } else if(*p == 'i') {
910                     abc_method_body_t*b = (abc_method_body_t*)data;
911                     fprintf(fo, "[methodbody]");
912                 } else if(*p == 'u' || *p == 'I' || *p == 'U') {
913                     int n = (ptroff_t)data;
914                     fprintf(fo, "%d", n);
915                 } else if(*p == 'f') {
916                     double f = *(double*)data;
917                     fprintf(fo, "%f", f);
918                 } else if(*p == 'r') {
919                     int n = (ptroff_t)data;
920                     fprintf(fo, "r%d", n);
921                 } else if(*p == 'b') {
922                     int b = (ptroff_t)data;
923                     fprintf(fo, "%02x", b);
924                 } else if(*p == 'j') {
925                     if(c->branch)
926                         fprintf(fo, "->%d", c->branch->pos);
927                     else
928                         fprintf(fo, "%08x", c->branch);
929                 } else if(*p == 's') {
930                     fprintf(fo, "\"%s\"", data);
931                 } else if(*p == 'D') {
932                     fprintf(fo, "[register %02x=%s]", (ptroff_t)c->data[1], (char*)c->data[0]);
933                 } else if(*p == 'S') {
934                     lookupswitch_t*l = c->data[0];
935                     fprintf(fo, "[");
936                     if(l->def)
937                         fprintf(fo, "default->%d", l->def->pos);
938                     else
939                         fprintf(fo, "default->00000000", l->def->pos);
940                     code_list_t*t = l->targets;
941                     while(t) {
942                         if(t->code)
943                             fprintf(fo, ",->%d", t->code->pos);
944                         else
945                             fprintf(fo, ",->00000000");
946                         t = t->next;
947                     }
948                     fprintf(fo, "]");
949                 } else {
950                     fprintf(stderr, "Can't parse opcode param type \"%c\"\n", *p);
951                     return 0;
952                 }
953                 p++;
954                 i++;
955                 first = 0;
956             }
957             fprintf(fo, "\n");
958         }
959         
960         e = exceptions;
961         while(e) {
962             if(c==e->abc_exception->to) {
963                 if(e->abc_exception->target)
964                     fprintf(fo, "%s   } // END TRY (HANDLER: %d)\n", prefix, e->abc_exception->target->pos);
965                 else
966                     fprintf(fo, "%s   } // END TRY (HANDLER: 00000000)\n", prefix);
967             }
968             e = e->next;
969         }
970
971         pos++;
972         c = c->next;
973     }
974     stats_free(stats);
975     return 1;
976 }
977
978 codestats_t* code_get_statistics(code_t*code, abc_exception_list_t*exceptions) 
979 {
980     currentstats_t*current = code_get_stats(code, exceptions);
981     if(!current)
982         return 0;
983     codestats_t*stats = rfx_calloc(sizeof(codestats_t));
984     stats->local_count = current->maxlocal;
985     stats->max_stack = current->maxstack;
986     stats->max_scope_depth = current->maxscope;
987     stats->flags = current->flags;
988
989     stats_free(current);current=0;
990     return stats;
991 }
992
993 void codestats_free(codestats_t*s)
994 {
995     free(s);
996 }
997
998 code_t* add_opcode(code_t*atag, U8 op)
999 {
1000     code_t*tmp = (code_t*)rfx_calloc(sizeof(code_t));
1001     tmp->opcode = op;
1002     tmp->next = 0;
1003     if(atag) {
1004         tmp->prev = atag;
1005         tmp->next = atag->next;
1006         atag->next = tmp;
1007     } else {
1008         tmp->prev = 0;
1009     }
1010     return tmp;
1011 }
1012     
1013 void codestats_print(codestats_t*stats)
1014 {
1015     printf("max_stack: %d\n", stats->max_stack);
1016     printf("local_count: %d\n", stats->local_count);
1017     printf("scope_depth: %d\n", stats->max_scope_depth);
1018 }
1019
1020 code_t* code_end(code_t*code)
1021 {
1022     if(!code)
1023         return 0;
1024     while(code->next)
1025         code = code->next;
1026     return code;
1027 }
1028
1029 code_t* code_append(code_t*code, code_t*toappend)
1030 {
1031     if(!code)
1032         return code_end(toappend);
1033     if(!toappend)
1034         return code_end(code);
1035     //find end of first list
1036     while(code->next) {
1037         code = code->next;
1038     }
1039     code_t*start=toappend;
1040     //and start of second list
1041     while(start->prev) {
1042         start = start->prev;
1043     }
1044     code->next = start;
1045     start->prev = code;
1046     return code_end(toappend);
1047 }
1048