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