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