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