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