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