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