several bugfixes
[swftools.git] / lib / as3 / abc.c
1 /* abc.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 <stdarg.h>
25 #include <assert.h>
26 #include "../rfxswf.h"
27 #include "../q.h"
28 #include "abc.h"
29
30 char stringbuffer[2048];
31
32 typedef struct _opcode
33 {
34     unsigned char opcode;
35     char*name;
36     char*params;
37 } opcode_t;
38
39 /* 2 = multiname
40    m = method
41    n = number of params
42    i = method info
43    b = byte
44    s = short
45    c = class
46    s = string
47    S = switch
48 */
49
50 int abc_RegisterNameSpace(abc_file_t*file, const char*name);
51 int abc_RegisterPackageNameSpace(abc_file_t*file, const char*name);
52 int abc_RegisterPackageInternalNameSpace(abc_file_t*file, const char*name);
53 int abc_RegisterProtectedNameSpace(abc_file_t*file, const char*name);
54 int abc_RegisterExplicitNameSpace(abc_file_t*file, const char*name);
55 int abc_RegisterStaticProtectedNameSpace(abc_file_t*file, const char*name);
56 int abc_RegisterPrivateNameSpace(abc_file_t*file, const char*name);
57
58
59 opcode_t opcodes[]={
60 {0xa0, "add", ""},
61 {0xc5, "add_i", ""},
62 {0x86, "atype", "2"},
63 {0x87, "astypelate", ""},
64 {0xA8, "bitand", ""},
65 {0x97, "bitnot", ""},
66 {0xa9, "bitor", ""},
67 {0xaa, "bitxor", ""},
68 {0x41, "call", "n"},
69 {0x43, "callmethod", "mn"},
70 {0x4c, "callproplex", "2n"},
71 {0x46, "callproperty", "2n"},
72 {0x4f, "callpropvoid", "2n"},
73 {0x44, "callstatic", "in"},
74 {0x45, "callsuper", "2n"},
75 {0x4e, "callsupervoid", "2n"},
76 {0x78, "checkfilter", ""},
77 {0x80, "coerce", "2"},
78 {0x82, "coerce_a", ""},
79 {0x85, "coerce_s", ""},
80 {0x42, "construct", "n"},
81 {0x4a, "constructprop", "2n"},
82 {0x49, "constructsuper", "n"},
83 {0x76, "convert_b", ""},
84 {0x73, "convert_i", ""},
85 {0x75, "convert_d", ""},
86 {0x77, "convert_o", ""},
87 {0x74, "convert_u", ""},
88 {0x70, "convert_s", ""},
89 {0xef, "debug", "D"},
90 {0xf1, "debugfile", "s"},
91 {0xf0, "debugline", "u"},
92 {0x94, "declocal", "u"},
93 {0xc3, "declocal_i", "u"},
94 {0x93, "decrement", ""},
95 {0xc1, "decrement_i", ""},
96 {0x6a, "deleteproperty", "2"},
97 {0xa3, "divide", ""},
98 {0x2a, "dup", ""},
99 {0x06, "dxns", "s"},
100 {0x07, "dxnslate", ""},
101 {0xab, "equals", ""},
102 {0x72, "esc_xattr", ""},
103 {0x71, "esc_xelem", ""},
104 {0x5e, "findproperty", "2"},
105 {0x5d, "findpropstrict", "2"},
106 {0x59, "getdescendants", "2"},
107 {0x64, "getglobalscope", ""},
108 {0x6e, "getglobalslot", "u"},
109 {0x60, "getlex", "2"},
110 {0x62, "getlocal", "u"},
111 {0xd0, "getlocal_0", ""},
112 {0xd1, "getlocal_1", ""},
113 {0xd2, "getlocal_2", ""},
114 {0xd3, "getlocal_3", ""},
115 {0x66, "getproperty", "2"},
116 {0x65, "getscopeobject", "u"},
117 {0x6c, "getslot", "u"},
118 {0x04, "getsuper", "2"},
119 {0xaf, "greaterequals", ""},
120 {0x1f, "hasnext", ""},
121 {0x32, "hasnext2", "uu"},
122 {0x13, "ifeq", "j"},
123 {0x12, "iffalse", "j"},
124 {0x18, "ifge", "j"},
125 {0x17, "ifgt", "j"},
126 {0x16, "ifle", "j"},
127 {0x15, "iflt", "j"},
128 {0x0f, "ifnge", "j"},
129 {0x0e, "ifngt", "j"},
130 {0x0d, "ifnle", "j"},
131 {0x0c, "ifnlt", "j"},
132 {0x14, "ifne", "j"},
133 {0x19, "ifstricteq", "j"},
134 {0x1a, "ifstrictne", "j"},
135 {0x11, "iftrue", "j"},
136 {0xb4, "in", ""},
137 {0x92, "inclocal", "u"},
138 {0xc2, "inclocal_i", "u"},
139 {0x91, "increment", ""},
140 {0xc0, "increment_i", ""},
141 {0x68, "initproperty", "2"},
142 {0xb1, "instanceof", ""},
143 {0xb2, "istype", "2"},
144 {0xb3, "istypelate", ""},
145 {0x10, "jump", "j"},
146 {0x08, "kill", "u"},
147 {0x09, "label", ""},
148 {0xae, "lessequals", ""},
149 {0xad, "lessthan", ""},
150 {0x1b, "lookupswitch", "S"},
151 {0xa5, "lshift", ""},
152 {0xa4, "modulo", ""},
153 {0xa2, "multiply", ""},
154 {0xc7, "multiply_i", ""},
155 {0x90, "negate", ""},
156 {0xc4, "negate_i", ""},
157 {0x57, "newactivation", ""},
158 {0x56, "newarray", "u"},
159 {0x5a, "newcatch", "u"}, //index into exception_info
160 {0x58, "newclass", "c"}, //index into class_info
161 {0x40, "newfunction", "u"}, //index into method_info
162 {0x55, "newobject", "u"},
163 {0x1e, "nextname", ""},
164 {0x23, "nextvalue", ""},
165 {0x02, "nop", ""},
166 {0x96, "not", ""},
167 {0x29, "pop", ""},
168 {0x1d, "popscope", ""},
169 {0x24, "pushbyte", "b"},
170 {0x2f, "pushdouble", "u"}, //index into floats
171 {0x27, "pushfalse", ""},
172 {0x2d, "pushint", "u"}, //index into ints
173 {0x31, "pushnamespace", "u"}, //index into namespace
174 {0x28, "pushnan", ""},
175 {0x20, "pushnull", ""},
176 {0x30, "pushscope", ""},
177 {0x25, "pushshort", "u"},
178 {0x2c, "pushstring", "s"},
179 {0x26, "pushtrue", ""},
180 {0x2e, "pushuint", "u"}, //index into uints
181 {0x21, "pushundefined", ""},
182 {0x1c, "pushwith", ""},
183 {0x48, "returnvalue", ""},
184 {0x47, "returnvoid", ""},
185 {0xa6, "rshift", ""},
186 {0x63, "setlocal", "u"},
187 {0xd4, "setlocal_0", ""},
188 {0xd5, "setlocal_1", ""},
189 {0xd6, "setlocal_2", ""},
190 {0xd7, "setlocal_3", ""},
191 {0x6f, "setglobalshot", "u"},
192 {0x61, "setproperty", "2"},
193 {0x6d, "setslot", "u"},
194 {0x05, "setsuper", "2"},
195 {0xac, "strictequals", ""},
196 {0xa1, "subtract", ""},
197 {0xc6, "subtract_i", ""},
198 {0x2b, "swap", ""},
199 {0x03, "throw", ""},
200 {0x95, "typeof", ""},
201 {0xa7, "urshift", ""},
202 {0xb0, "xxx", ""},
203 };
204
205 static U8 op2index[256] = {254};
206
207 opcode_t* opcode_get(U8 op)
208 {
209     int t;
210     if(op2index[0]==254) {
211         memset(op2index, 255, sizeof(op2index));
212         for(t=0;t<sizeof(opcodes)/sizeof(opcodes[0]);t++) {
213             op2index[opcodes[t].opcode] = t;
214         }
215     }
216     if(op2index[op]!=255)
217         return &opcodes[op2index[op]];
218     return 0;
219 }
220
221 static void code_free(abc_code_t*code)
222 {
223     while(code) {
224         abc_code_t*next = code->next;
225         memset(code, 0, sizeof(code));
226         free(code);
227         code = next;
228     }
229 }
230
231 abc_code_t*parse_code(TAG*tag, int len, abc_file_t*file, pool_t*pool)
232 {
233     abc_code_t*head=0;
234     abc_code_t*code=0;
235     int end=tag->pos+len;
236     //printf("-->\n");fflush(stdout);
237     while(tag->pos<end) {
238         U8 opcode = swf_GetU8(tag);
239         opcode_t*op = opcode_get(opcode);
240         if(!op) {
241             fprintf(stderr, "Can't parse opcode %02x\n", opcode);
242             return head;
243         }
244         //printf("%s\n", op->name);fflush(stdout);
245         NEW(abc_code_t,c);
246         if(!head) {
247             head = code = c;
248         } else {
249             code->next = c;
250             code = c;
251         }
252
253         c->opcode = opcode;
254
255         char*p = op->params;
256         int pos = 0;
257         while(*p) {
258             void*data = 0;
259             if(*p == 'n') { // number
260                 data = (void*)(ptroff_t)swf_GetU30(tag);
261             } else if(*p == '2') { //multiname
262                 data = array_getvalue(pool->multinames, swf_GetU30(tag));
263             } else if(*p == 'm') { //method
264                 data = array_getvalue(file->methods, swf_GetU30(tag));
265             } else if(*p == 'c') { //classinfo
266                 data = array_getvalue(file->classes, swf_GetU30(tag));
267             } else if(*p == 'i') { //methodbody TODO
268                 data = array_getvalue(file->method_bodies, swf_GetU30(tag));
269             } else if(*p == 'u') { // lookoup TODO
270                 data = (void*)(ptroff_t)swf_GetU30(tag);
271             } else if(*p == 'b') { // byte
272                 data = (void*)(ptroff_t)swf_GetU8(tag);
273             } else if(*p == 'j') { // jump TODO
274                 data = (void*)(ptroff_t)swf_GetS24(tag);
275             } else if(*p == 's') { // string
276                 data = (void*)array_getkey(pool->strings, swf_GetU30(tag));
277             } else if(*p == 'D') { // debug
278                 /*type, usually 1*/
279                 U8 type = swf_GetU8(tag);
280                 if(type!=1) 
281                     fprintf(stderr, "Unknown debug type: %02x\n", type);
282                 /*register name*/
283                 code->params[0] = (void*)array_getkey(pool->strings, swf_GetU30(tag));
284                 /*register index*/
285                 code->params[1] = (void*)(ptroff_t)swf_GetU8(tag);
286                 /*unused*/
287                 swf_GetU30(tag);
288             } else if(*p == 'S') { // switch statement TODO
289                 /* I hate these things */
290                 swf_GetU24(tag); //default
291                 int num = swf_GetU30(tag)+1;
292                 int t;
293                 for(t=0;t<num;t++) 
294                     swf_GetU24(tag);
295                 data = 0;
296             } else {
297                 printf("Can't parse opcode param type \"%c\"\n", *p);
298                 return 0;
299             }
300             if(data)
301                 code->params[pos++] = data;
302             p++;
303         }
304     }
305     return head;
306 }
307
308 static int dump_code(abc_code_t*c, abc_file_t*file, char*prefix, FILE*fo)
309 {
310     pool_t*pool = pool_new();
311
312     while(c) {
313         U8 opcode = c->opcode;
314         int t;
315         char found = 0;
316         opcode_t*op = opcode_get(opcode);
317         if(!op) {
318             fprintf(stderr, "Can't parse opcode %02x.\n", opcode);
319             return 0;
320         } else {
321             fprintf(fo, "%s%s ", prefix, op->name);
322             char*p = op->params;
323             char first = 1;
324             int pos=0;
325             while(*p) {
326                 void*data = c->params[pos];
327                 if(pos>0)
328                     printf(", ");
329
330                 if(*p == 'n') {
331                     int n = (ptroff_t)data;
332                     fprintf(fo, "%d params", n);
333                 } else if(*p == '2') {
334                     multiname_t*n = (multiname_t*)data;
335                     char* m = multiname_to_string(n);
336                     fprintf(fo, "%s", m);
337                     free(m);
338                 } else if(*p == 'm') {
339                     abc_method_t*m = (abc_method_t*)data;
340                     fprintf(fo, "[method %s]", m->name);
341                 } else if(*p == 'c') {
342                     abc_class_t*cls = (abc_class_t*)data;
343                     fprintf(fo, "[classinfo %s]", cls->classname->name);
344                 } else if(*p == 'i') {
345                     abc_method_body_t*b = (abc_method_body_t*)data;
346                     fprintf(fo, "[methodbody]");
347                 } else if(*p == 'u') {
348                     int n = (ptroff_t)data;
349                     fprintf(fo, "%d", n);
350                 } else if(*p == 'b') {
351                     int b = (ptroff_t)data;
352                     fprintf(fo, "%02x", b);
353                 } else if(*p == 'j') {
354                     int n = (ptroff_t)data;
355                     fprintf(fo, "%d", n);
356                 } else if(*p == 's') {
357                     fprintf(fo, "\"%s\"", data);
358                 } else if(*p == 'D') {
359                     fprintf(fo, "[register %02x=%s]", (ptroff_t)c->params[1], (char*)c->params[0]);
360                 } else if(*p == 'S') {
361                     fprintf(fo, "[switch data]");
362                 } else {
363                     fprintf(stderr, "Can't parse opcode param type \"%c\"\n", *p);
364                     return 0;
365                 }
366                 p++;
367                 pos++;
368                 first = 0;
369             }
370             fprintf(fo, "\n");
371         }
372         c = c->next;
373     }
374     return 1;
375 }
376
377 static int opcode_write(TAG*tag, abc_code_t*code, pool_t*pool, abc_file_t*file)
378 {
379     opcode_t*c = opcode_get(code->opcode);
380     char*p = c->params;
381     int pos = 0;
382     int len = 0;
383     
384     if(tag)
385         swf_SetU8(tag, code->opcode);
386     len++;
387
388     while(*p) {
389         void*data = code->params[pos++];
390         assert(pos<=2);
391         if(*p == 'n') { // number
392             len += swf_SetU30(tag, (ptroff_t)data);
393         } else if(*p == '2') { //multiname
394             multiname_t*m = (multiname_t*)data;
395             len += swf_SetU30(tag, pool_register_multiname(pool, m));
396         } else if(*p == 'm') { //method
397             abc_method_t*m = (abc_method_t*)data;
398             len += swf_SetU30(tag, m->index);
399         } else if(*p == 'c') { //classinfo 
400             abc_class_t*cls = (abc_class_t*)data;
401             len += swf_SetU30(tag, cls->index);
402         } else if(*p == 'i') { //methodbody
403             abc_method_body_t*m = (abc_method_body_t*)data;
404             len += swf_SetU30(tag, m->index);
405         } else if(*p == 'u') { // integer
406             len += swf_SetU30(tag, (ptroff_t)data);
407         } else if(*p == 'b') { // byte
408             if(tag)
409                 swf_SetU8(tag, (ptroff_t)data);
410             len++;
411         } else if(*p == 'j') { // jump
412             len += swf_SetS24(tag, (ptroff_t)data);
413         } else if(*p == 's') { // string
414             int index = pool_register_string(pool, data);
415             len += swf_SetU30(tag, index);
416         } else if(*p == 'D') { // debug statement
417             if(tag)
418                 swf_SetU8(tag, 1);
419             len++;
420             len+=swf_SetU30(tag, pool_register_string(pool,code->params[0]));
421             if(tag)
422                 swf_SetU8(tag, (ptroff_t)code->params[1]);
423             len++;
424             len+=swf_SetU30(tag, 0);
425         } else if(*p == 'S') { // switch statement
426             len+=swf_SetU24(tag, 0); //default
427             len+=swf_SetU30(tag, 0); //nr-1
428             len+=swf_SetU24(tag, 0); //first
429         } else {
430             printf("Can't parse opcode param type \"%c\"\n", *p);
431         }
432         p++;
433     }
434     return len;
435 }
436
437
438 static char* params_to_string(multiname_list_t*list)
439 {
440     multiname_list_t*l;
441     int n;
442
443     l = list;
444     n = 0;
445     while(list) {
446         n++;list=list->next;
447     }
448
449     char**names = (char**)malloc(sizeof(char*)*n);
450     
451     l = list;
452     n = 0;
453     int size = 0;
454     while(list) {
455         names[n] = multiname_to_string(list->multiname);
456         size += strlen(names[n]) + 2;
457         n++;list=list->next;
458     }
459
460     char* params = malloc(size+5);
461     params[0]='(';
462     params[1]=0;
463     l = list;
464     int s=0;
465     n = 0;
466     while(list) {
467         if(s)
468             strcat(params, ", ");
469         strcat(params, names[n]);
470         free(names[n]);
471         n++;
472         s=1;
473     }
474     free(names);
475     strcat(params, ")");
476     int t;
477     return params;
478 }
479
480 //#define DEBUG
481 #define DEBUG if(0)
482
483 static void parse_metadata(TAG*tag, abc_file_t*file, pool_t*pool)
484 {
485     int t;
486     int num_metadata = swf_GetU30(tag);
487
488     DEBUG printf("%d metadata\n");
489     for(t=0;t<num_metadata;t++) {
490         const char*entry_name = array_getkey(pool->strings, swf_GetU30(tag));
491         int num = swf_GetU30(tag);
492         int s;
493         DEBUG printf("  %s\n", entry_name);
494         array_t*items = array_new();
495         for(s=0;s<num;s++) {
496             int i1 = swf_GetU30(tag);
497             int i2 = swf_GetU30(tag);
498             const char*key = i1?array_getkey(pool->strings, i1):"";
499             const char*value = i2?array_getkey(pool->strings, i2):"";
500             DEBUG printf("    %s=%s\n", key, value);
501             array_append(items, key, value);
502         }
503         array_append(file->metadata, entry_name, items);
504     }
505 }
506
507 void swf_CopyData(TAG*to, TAG*from, int len)
508 {
509     unsigned char*data = malloc(len);
510     swf_GetBlock(from, data, len);
511     swf_SetBlock(to, data, len);
512     free(data);
513 }
514
515 abc_file_t*abc_file_new()
516 {
517     abc_file_t*f = malloc(sizeof(abc_file_t));
518     memset(f, 0, sizeof(abc_file_t));
519     f->metadata = array_new();
520     f->methods = array_new();
521     f->classes = array_new();
522     f->scripts = array_new();
523     f->method_bodies = array_new();
524
525     return f;
526 }
527
528 static namespace_t* namespace_new(U8 access, const char*name)
529 {
530     namespace_t*ns = malloc(sizeof(namespace_t));
531     memset(ns, 0, sizeof(namespace_t));
532
533     if(access==0) { // autodetect access
534         char*n = strdup(name);
535         if(n[0] == '[') {
536             char*bracket = strchr(n, ']');
537             if(bracket) {
538                 *bracket = 0;
539                 char*a = n+1;
540                 name += (bracket-n)+1;
541                 if(!strcmp(a, "")) access=0x16;
542                 else if(!strcmp(a, "package")) access=0x16;
543                 else if(!strcmp(a, "packageinternal")) access=0x17;
544                 else if(!strcmp(a, "protected")) access=0x18;
545                 else if(!strcmp(a, "explicit")) access=0x19;
546                 else if(!strcmp(a, "staticprotected")) access=0x1a;
547                 else if(!strcmp(a, "private")) access=0x05;
548                 else {
549                     fprintf(stderr, "Undefined access level: [%s]\n", a);
550                     return 0;
551                 }
552             }
553         } else {
554             access = 0x16;
555         }
556         free(n);
557     }
558     ns->access = access;
559     ns->name = strdup(name);
560     return ns;
561 }
562 namespace_t* namespace(abc_file_t*file, const char*name) {
563     return namespace_new(0x08, name);
564 }
565 namespace_t* abc_packagenamespace(abc_file_t*file, const char*name) {
566     return namespace_new(0x16 , name);
567 }
568 namespace_t* abc_packageinternalnamespace(abc_file_t*file, const char*name) {
569     return namespace_new(0x17, name);
570 }
571 namespace_t* abc_protectednamespace(abc_file_t*file, const char*name) {
572     return namespace_new(0x18, name);
573 }
574 namespace_t* abc_explicitnamespace(abc_file_t*file, const char*name) {
575     return namespace_new(0x19, name);
576 }
577 namespace_t* abc_staticprotectednamespace(abc_file_t*file, const char*name) {
578     return namespace_new(0x1a, name);
579 }
580 namespace_t* abc_privatenamespace(abc_file_t*file, const char*name) {
581     return namespace_new(0x05, name);
582 }
583
584 #define CLASS_SEALED 1
585 #define CLASS_FINAL 2
586 #define CLASS_INTERFACE 4
587 #define CLASS_PROTECTED_NS 8
588
589 abc_class_t* abc_class_new(abc_file_t*pool, char*classname, char*superclass) {
590     abc_class_t* c = malloc(sizeof(abc_class_t));
591     memset(c, 0, sizeof(abc_class_t));
592     c->index = array_append(pool->classes, classname, c);
593     c->pool = pool;
594     c->classname = multiname_fromstring(classname);
595     c->superclass = superclass?multiname_fromstring(superclass):0;
596     c->flags = 0;
597     c->constructor = 0;
598     c->static_constructor = 0;
599     c->traits = list_new();
600     return c;
601 }
602
603 void abc_class_sealed(abc_class_t*c)
604 {
605     c->flags |= CLASS_SEALED;
606 }
607 void abc_class_final(abc_class_t*c)
608 {
609     c->flags |= CLASS_FINAL;
610 }
611 void abc_class_interface(abc_class_t*c)
612 {
613     c->flags |= CLASS_INTERFACE;
614 }
615 void abc_class_protectedNS(abc_class_t*c, char*namespace)
616 {
617     c->protectedNS = namespace;
618     c->flags |= CLASS_PROTECTED_NS;
619 }
620
621 abc_method_body_t* add_method(abc_file_t*pool, abc_class_t*cls, char*returntype, int num_params, va_list va)
622 {
623     /* construct code (method body) object */
624     abc_method_body_t* c = malloc(sizeof(abc_method_body_t));
625     memset(c, 0, sizeof(abc_method_body_t));
626     c->index = array_append(pool->method_bodies, 0, c);
627     c->pool = pool;
628     c->traits = list_new();
629     c->code = 0;
630
631     /* construct method object */
632     NEW(abc_method_t,m);
633     m->index = array_append(pool->methods, 0, m);
634     if(returntype && strcmp(returntype, "void")) {
635         m->return_type = multiname_fromstring(returntype);
636     } else {
637         m->return_type = 0;
638     }
639     int t;
640     for(t=0;t<num_params;t++) {
641         const char*param = va_arg(va, const char*);
642         list_append(m->parameters, multiname_fromstring(param));
643     }
644
645     /* crosslink the two objects */
646     m->body = c;
647     c->method = m;
648
649     return c;
650 }
651
652 abc_method_body_t* abc_class_constructor(abc_class_t*cls, char*returntype, int num_params, ...) 
653 {
654     va_list va;
655     va_start(va, num_params);
656     abc_method_body_t* c = add_method(cls->pool, cls, returntype, num_params, va);
657     va_end(va);
658     cls->constructor = c->method;
659     return c;
660 }
661
662 abc_method_body_t* abc_class_staticconstructor(abc_class_t*cls, char*returntype, int num_params, ...) 
663 {
664     va_list va;
665     va_start(va, num_params);
666     abc_method_body_t* c = add_method(cls->pool, cls, returntype, num_params, va);
667     va_end(va);
668     cls->static_constructor = c->method;
669     return c;
670 }
671
672 trait_t*trait_new(int type, multiname_t*name, int data1, int data2, int vindex, int vkind)
673 {
674     trait_t*trait = malloc(sizeof(trait_t));
675     memset(trait, 0, sizeof(trait_t));
676     trait->kind = type&0x0f;
677     trait->attributes = type&0xf0;
678     trait->name = name;
679     trait->data1 = data1;
680     trait->data2 = data2;
681     trait->vindex = vindex;
682     trait->vkind = vkind;
683     return trait;
684 }
685
686 abc_method_body_t* abc_class_method(abc_class_t*cls, char*returntype, char*name, int num_params, ...)
687 {
688     abc_file_t*pool = cls->pool;
689     va_list va;
690     va_start(va, num_params);
691     abc_method_body_t* c = add_method(cls->pool, cls, returntype, num_params, va);
692     va_end(va);
693     list_append(cls->traits, trait_new(TRAIT_METHOD, multiname_fromstring(name), 0, c->method->index, 0, 0));
694     return c;
695 }
696
697 void abc_AddSlot(abc_class_t*cls, char*name, int slot, char*multiname)
698 {
699     abc_file_t*pool = cls->pool;
700     multiname_t*m = multiname_fromstring(multiname);
701     list_append(cls->traits, trait_new(TRAIT_SLOT, m, slot, 0, 0, 0));
702 }
703
704 void abc_method_body_addClassTrait(abc_method_body_t*code, char*multiname, int slotid, abc_class_t*cls)
705 {
706     abc_file_t*pool = code->pool;
707     multiname_t*m = multiname_fromstring(multiname);
708     trait_t*trait = trait_new(TRAIT_CLASS, m, slotid, 0, 0, 0);
709     trait->cls = cls;
710     list_append(code->traits, trait);
711 }
712
713 /* notice: traits of a method (body) belonging to an init script
714    and traits of the init script are *not* the same thing */
715 void abc_initscript_addClassTrait(abc_script_t*script, char*multiname, int slotid, abc_class_t*cls)
716 {
717     abc_file_t*pool = script->pool;
718     multiname_t*m = multiname_fromstring(multiname);
719     trait_t*trait = trait_new(TRAIT_CLASS, m, slotid, 0, 0, 0);
720     trait->cls = cls;
721     list_append(script->traits, trait);
722 }
723
724 abc_script_t* abc_initscript(abc_file_t*pool, char*returntype, int num_params, ...) 
725 {
726     va_list va;
727     va_start(va, num_params);
728     abc_method_body_t* c = add_method(pool, 0, returntype, num_params, va);
729     abc_script_t* s = malloc(sizeof(abc_script_t));
730     s->method = c->method;
731     s->traits = list_new();
732     s->pool = pool;
733     array_append(pool->scripts, 0, s);
734     va_end(va);
735     return s;
736 }
737
738 static void dump_traits(FILE*fo, const char*prefix, trait_list_t*traits, abc_file_t*file);
739
740 static void dump_method(FILE*fo, const char*prefix, const char*type, const char*name, abc_method_t*m, abc_file_t*file)
741 {
742     const char*return_type = "";
743     if(m->return_type)
744         return_type = multiname_to_string(m->return_type);
745
746     char*paramstr = params_to_string(m->parameters);
747
748     fprintf(fo, "%s%s %s %s=%s %s\n", prefix, type, return_type, name, m->name, paramstr);
749
750     abc_method_body_t*c = m->body;
751     if(!c) {
752         return;
753     }
754     
755     fprintf(fo, "%s[%d %d %d %d %d]\n", prefix, c->max_stack, c->local_count, c->init_scope_depth, c->max_scope_depth, c->exception_count);
756
757     char prefix2[80];
758     sprintf(prefix2, "%s    ", prefix);
759     if(c->traits)
760         dump_traits(fo, prefix, c->traits, file);
761     fprintf(fo, "%s{\n", prefix);
762     dump_code(c->code, file, prefix2, fo);
763     fprintf(fo, "%s}\n\n", prefix);
764 }
765
766 static void traits_free(trait_list_t*traits) 
767 {
768     trait_list_t*t = traits;
769     while(t) {
770         free(t->trait);t->trait = 0;
771         t = t->next;
772     }
773     list_free(traits);
774 }
775
776 static trait_list_t* traits_parse(TAG*tag, pool_t*pool, abc_file_t*file)
777 {
778     int num_traits = swf_GetU30(tag);
779     trait_list_t*traits = list_new();
780     int t;
781     if(num_traits) {
782         DEBUG printf("%d traits\n", num_traits);
783     }
784     
785     for(t=0;t<num_traits;t++) {
786         trait_t*trait = malloc(sizeof(trait_t));
787         memset(trait, 0, sizeof(trait_t));
788         list_append(traits, trait);
789
790         trait->name = pool_lookup_multiname(pool, swf_GetU30(tag)); // always a QName (ns,name)
791
792         const char*name = 0;
793         DEBUG name = multiname_to_string(trait->name);
794         U8 kind = swf_GetU8(tag);
795         U8 attributes = kind&0xf0;
796         kind&=0x0f;
797         trait->kind = kind;
798         trait->attributes = attributes;
799         DEBUG printf("  trait %d) %s type=%02x\n", t, name, kind);
800         if(kind == TRAIT_METHOD || kind == TRAIT_GETTER || kind == TRAIT_SETTER) { // method / getter / setter
801             trait->disp_id = swf_GetU30(tag);
802             trait->method = (abc_method_t*)array_getvalue(file->methods, swf_GetU30(tag));
803             DEBUG printf("  method/getter/setter\n");
804         } else if(kind == TRAIT_FUNCTION) { // function
805             trait->slot_id =  swf_GetU30(tag);
806             trait->method = (abc_method_t*)array_getvalue(file->methods, swf_GetU30(tag));
807         } else if(kind == TRAIT_CLASS) { // class
808             trait->slot_id = swf_GetU30(tag);
809             trait->cls = (abc_class_t*)array_getvalue(file->classes, swf_GetU30(tag));
810             DEBUG printf("  class %s %d %d\n", name, trait->slot_id, trait->cls);
811         } else if(kind == TRAIT_SLOT || kind == TRAIT_CONST) { // slot, const
812             /* a slot is a variable in a class that is shared amonst all instances
813                of the same type, but which has a unique location in each object 
814                (in other words, slots are non-static, traits are static)
815              */
816             trait->slot_id = swf_GetU30(tag);
817             trait->type_name = (multiname_t*)array_getvalue(pool->multinames, swf_GetU30(tag));
818             trait->vindex = swf_GetU30(tag);
819             if(trait->vindex) {
820                 trait->vkind = swf_GetU8(tag);
821             }
822             DEBUG printf("  slot %s %d %s (vindex=%d)\n", name, trait->slot_id, trait->type_name->name, trait->vindex);
823         } else {
824             fprintf(stderr, "Can't parse trait type %d\n", kind);
825         }
826         if(attributes&0x40) {
827             int num = swf_GetU30(tag);
828             int s;
829             for(s=0;s<num;s++) {
830                 swf_GetU30(tag); //index into metadata array
831             }
832         }
833     }
834     return traits;
835 }
836
837 void traits_skip(TAG*tag)
838 {
839     int num_traits = swf_GetU30(tag);
840     int t;
841     for(t=0;t<num_traits;t++) {
842         swf_GetU30(tag);
843         U8 kind = swf_GetU8(tag);
844         U8 attributes = kind&0xf0;
845         kind&=0x0f;
846         swf_GetU30(tag);
847         swf_GetU30(tag);
848         if(kind == TRAIT_SLOT || kind == TRAIT_CONST) {
849             if(swf_GetU30(tag)) swf_GetU8(tag);
850         } else if(kind>TRAIT_CONST) {
851             fprintf(stderr, "Can't parse trait type %d\n", kind);
852         }
853         if(attributes&0x40) {
854             int s, num = swf_GetU30(tag);
855             for(s=0;s<num;s++) swf_GetU30(tag);
856         }
857     }
858 }
859
860
861 static void traits_write(pool_t*pool, TAG*tag, trait_list_t*traits)
862 {
863     if(!traits) {
864         swf_SetU30(tag, 0);
865         return;
866     }
867     swf_SetU30(tag, list_length(traits));
868     int s;
869
870     while(traits) {
871         trait_t*trait = traits->trait;
872
873         swf_SetU30(tag, pool_register_multiname(pool, trait->name));
874         swf_SetU8(tag, trait->kind|trait->attributes);
875
876         swf_SetU30(tag, trait->data1);
877
878         if(trait->kind == TRAIT_CLASS) {
879             swf_SetU30(tag, trait->cls->index);
880         } else if(trait->kind == TRAIT_GETTER ||
881                   trait->kind == TRAIT_SETTER ||
882                   trait->kind == TRAIT_METHOD) {
883             swf_SetU30(tag, trait->method->index);
884         } else if(trait->kind == TRAIT_SLOT ||
885                   trait->kind == TRAIT_CONST) {
886             int index = pool_register_multiname(pool, trait->type_name);
887             swf_SetU30(tag, index);
888         } else  {
889             swf_SetU30(tag, trait->data2);
890         }
891
892         if(trait->kind == TRAIT_SLOT || trait->kind == TRAIT_CONST) {
893             swf_SetU30(tag, trait->vindex);
894             if(trait->vindex) {
895                 swf_SetU8(tag, trait->vkind);
896             }
897         }
898         if(trait->attributes&0x40) {
899             // metadata
900             swf_SetU30(tag, 0);
901         }
902         traits = traits->next;
903     }
904 }
905
906
907 static void dump_traits(FILE*fo, const char*prefix, trait_list_t*traits, abc_file_t*file)
908 {
909     int t;
910     while(traits) {
911         trait_t*trait = traits->trait;
912         char*name = multiname_to_string(trait->name);
913         U8 kind = trait->kind;
914         U8 attributes = trait->attributes;
915         if(kind == TRAIT_METHOD) {
916             abc_method_t*m = trait->method;
917             dump_method(fo, prefix, "method", name, m, file);
918         } else if(kind == TRAIT_GETTER) {
919             abc_method_t*m = trait->method;
920             dump_method(fo, prefix, "getter", name, m, file);
921         } else if(kind == TRAIT_SETTER) {
922             abc_method_t*m = trait->method;
923             dump_method(fo, prefix, "setter", name, m, file);
924         } else if(kind == TRAIT_FUNCTION) { // function
925             abc_method_t*m = trait->method;
926             dump_method(fo, prefix, "function", name, m, file);
927         } else if(kind == TRAIT_CLASS) { // class
928             abc_class_t*cls = trait->cls;
929             if(!cls) {
930                 fprintf(fo, "%sslot %d: class %s=class%d\n", prefix, trait->slot_id, name);
931             } else {
932                 fprintf(fo, "%sslot %d: class %s=%s\n", prefix, trait->slot_id, name, cls->classname->name);
933             }
934         } else if(kind == TRAIT_SLOT || kind == TRAIT_CONST) { // slot, const
935             int slot_id = trait->slot_id;
936             char*type_name = multiname_to_string(trait->type_name);
937             fprintf(fo, "%sslot %s %d %s (vindex=%d)\n", prefix, name, trait->slot_id, type_name, trait->vindex);
938             free(type_name);
939         } else {
940             fprintf(fo, "%s    can't dump trait type %d\n", prefix, kind);
941         }
942         free(name);
943         traits=traits->next;
944     }
945 }
946
947 void* swf_DumpABC(FILE*fo, void*code, char*prefix)
948 {
949     abc_file_t* file = (abc_file_t*)code;
950         
951     if(file->name)
952         fprintf(fo, "%s#\n", prefix);
953         fprintf(fo, "%s#name: %s\n", prefix, file->name);
954         fprintf(fo, "%s#\n", prefix);
955
956     int t;
957     for(t=0;t<file->metadata->num;t++) {
958         const char*entry_name = array_getkey(file->metadata, t);
959         fprintf(fo, "%s#Metadata \"%s\":\n", prefix, entry_name);
960         int s;
961         array_t*items = (array_t*)array_getvalue(file->metadata, t);
962         for(s=0;s<items->num;s++) {
963             fprintf(fo, "%s#  %s=%s\n", prefix, array_getkey(items, s), array_getvalue(items,s));
964         }
965         fprintf(fo, "%s#\n", prefix);
966     }
967
968     for(t=0;t<file->classes->num;t++) {
969         abc_class_t*cls = (abc_class_t*)array_getvalue(file->classes, t);
970         char prefix2[80];
971         sprintf(prefix2, "%s    ", prefix);
972
973         fprintf(fo, "%s", prefix);
974         if(cls->flags&1) fprintf(fo, "sealed ");
975         if(cls->flags&2) fprintf(fo, "final ");
976         if(cls->flags&4) fprintf(fo, "interface ");
977         if(cls->flags&8) {
978             fprintf(fo, "protectedNS<%s> ", cls->protectedNS);
979         }
980
981         fprintf(fo, "class %s", cls->classname->name);
982         if(cls->superclass) {
983             fprintf(fo, " extends %s", cls->superclass->name);
984             multiname_list_t*ilist = cls->interfaces;
985             if(ilist)
986                 fprintf(fo, " implements");
987             while(ilist) {
988                 char*s = multiname_to_string(ilist->multiname);
989                 fprintf(fo, " %s", s);
990                 free(s);
991                 ilist = ilist->next;
992             }
993             ilist->next;
994         }
995         if(cls->flags&0xf0) 
996             fprintf(fo, "extra flags=%02x\n", cls->flags&0xf0);
997         fprintf(fo, "%s{\n", prefix);
998
999         if(cls->static_constructor)
1000             dump_method(fo, prefix2,"staticconstructor", "", cls->static_constructor, file);
1001         dump_traits(fo, prefix2, cls->static_constructor_traits, file);
1002         
1003         char*n = multiname_to_string(cls->classname);
1004         if(cls->constructor)
1005             dump_method(fo, prefix2, "constructor", n, cls->constructor, file);
1006         free(n);
1007         dump_traits(fo, prefix2,cls->traits, file);
1008         fprintf(fo, "%s}\n", prefix);
1009     }
1010     fprintf(fo, "%s\n", prefix);
1011
1012     for(t=0;t<file->scripts->num;t++) {
1013         abc_script_t*s = (abc_script_t*)array_getvalue(file->scripts, t);
1014         dump_method(fo, prefix,"initmethod", "init", s->method, file);
1015         dump_traits(fo, prefix, s->traits, file);
1016     }
1017     return file;
1018 }
1019
1020 void* swf_ReadABC(TAG*tag)
1021 {
1022     abc_file_t* file = abc_file_new();
1023     pool_t*pool = pool_new();
1024
1025     swf_SetTagPos(tag, 0);
1026     int t;
1027     if(tag->id == ST_DOABC) {
1028         U32 abcflags = swf_GetU32(tag);
1029         DEBUG printf("flags=%08x\n", abcflags);
1030         char*name= swf_GetString(tag);
1031         file->name = name?strdup(name):0;
1032     }
1033     U32 version = swf_GetU32(tag);
1034     if(version!=0x002e0010) {
1035         fprintf(stderr, "Warning: unknown AVM2 version %08x\n", version);
1036     }
1037
1038     pool_read(pool, tag);
1039
1040     int num_methods = swf_GetU30(tag);
1041     DEBUG printf("%d methods\n", num_methods);
1042     for(t=0;t<num_methods;t++) {
1043         NEW(abc_method_t,m);
1044         int param_count = swf_GetU30(tag);
1045         int return_type_index = swf_GetU30(tag);
1046         m->return_type = pool_lookup_multiname(pool, return_type_index);
1047
1048         int s;
1049         for(s=0;s<param_count;s++) {
1050             int type_index = swf_GetU30(tag);
1051             multiname_t*param = (multiname_t*)pool_lookup_multiname(pool, type_index);
1052             /* type_index might be 0, which probably means "..." (varargs) */
1053             list_append(m->parameters, param);
1054         }
1055
1056         int namenr = swf_GetU30(tag);
1057         m->name = "";
1058         if(namenr)
1059             m->name = array_getkey(pool->strings, namenr);
1060
1061         m->flags = swf_GetU8(tag);
1062         
1063         DEBUG printf("method %d) %s flags=%02x\n", t, params_to_string(m->parameters), m->flags);
1064
1065         if(m->flags&0x08) {
1066             /* optional parameters */
1067             int num = swf_GetU30(tag);
1068             int s;
1069             for(s=0;s<num;s++) {
1070                 int val = swf_GetU30(tag);
1071                 U8 kind = swf_GetU8(tag); // specifies index type for "val"
1072             }
1073         }
1074         if(m->flags&0x80) {
1075             /* debug information- not used by avm2 */
1076             multiname_list_t*l = m->parameters;
1077             while(l) {
1078                 char*name = (char*)array_getkey(pool->strings, swf_GetU30(tag));
1079                 l = l->next;
1080             }
1081         }
1082         array_append(file->methods, m->name, m);
1083     }
1084             
1085     parse_metadata(tag, file, pool);
1086         
1087     /* skip classes, and scripts for now, and do the real parsing later */
1088     int num_classes = swf_GetU30(tag);
1089     int classes_pos = tag->pos;
1090     DEBUG printf("%d classes\n", num_classes);
1091     for(t=0;t<num_classes;t++) {
1092         abc_class_t*cls = malloc(sizeof(abc_class_t));
1093         memset(cls, 0, sizeof(abc_class_t));
1094         array_append(file->classes, 0, cls);
1095         
1096         DEBUG printf("class %d\n", t);
1097         swf_GetU30(tag); //classname
1098         swf_GetU30(tag); //supername
1099         cls->flags = swf_GetU8(tag);
1100         if(cls->flags&8) 
1101             swf_GetU30(tag); //protectedNS
1102         int s;
1103         int inum = swf_GetU30(tag); //interface count
1104         cls->interfaces = 0;
1105         for(s=0;s<inum;s++) {
1106             int interface_index = swf_GetU30(tag);
1107             multiname_t* m = (multiname_t*)array_getvalue(pool->multinames, interface_index);
1108             list_append(cls->interfaces, m);
1109             DEBUG printf("  class %d interface: %s\n", t, m->name);
1110         }
1111
1112         swf_GetU30(tag); //iinit
1113         traits_skip(tag);
1114     }
1115     for(t=0;t<num_classes;t++) {
1116         abc_class_t*cls = (abc_class_t*)array_getvalue(file->classes, t);
1117         int cinit = swf_GetU30(tag);
1118         cls->static_constructor = (abc_method_t*)array_getvalue(file->methods, cinit);
1119         traits_skip(tag);
1120     }
1121     int num_scripts = swf_GetU30(tag);
1122     DEBUG printf("%d scripts\n", num_scripts);
1123     for(t=0;t<num_scripts;t++) {
1124         int init = swf_GetU30(tag);
1125         traits_skip(tag);
1126     }
1127
1128     int num_method_bodies = swf_GetU30(tag);
1129     DEBUG printf("%d method bodies\n", num_method_bodies);
1130     for(t=0;t<num_method_bodies;t++) {
1131         int methodnr = swf_GetU30(tag);
1132         if(methodnr >= file->methods->num) {
1133             printf("Invalid method number: %d\n", methodnr);
1134             return 0;
1135         }
1136         abc_method_t*m = (abc_method_t*)array_getvalue(file->methods, methodnr);
1137         abc_method_body_t*c = malloc(sizeof(abc_method_body_t));
1138         memset(c, 0, sizeof(abc_method_body_t));
1139         c->max_stack = swf_GetU30(tag);
1140         c->local_count = swf_GetU30(tag);
1141         c->init_scope_depth = swf_GetU30(tag);
1142         c->max_scope_depth = swf_GetU30(tag);
1143         int code_length = swf_GetU30(tag);
1144
1145         c->method = m;
1146         m->body = c;
1147
1148         int pos = tag->pos + code_length;
1149         c->code = parse_code(tag, code_length, file, pool);
1150         tag->pos = pos;
1151
1152         int exception_count = swf_GetU30(tag);
1153         int s;
1154         for(s=0;s<exception_count;s++) {
1155             swf_GetU30(tag); //from
1156             swf_GetU30(tag); //to
1157             swf_GetU30(tag); //target
1158             swf_GetU30(tag); //exc_type
1159             swf_GetU30(tag); //var_name
1160         }
1161         c->traits = traits_parse(tag, pool, file);
1162
1163         DEBUG printf("method_body %d) (method %d), %d bytes of code", t, methodnr, code_length);
1164
1165         array_append(file->method_bodies, 0, c);
1166     }
1167     if(tag->len - tag->pos) {
1168         fprintf(stderr, "%d unparsed bytes remaining in ABC block\n", tag->len - tag->pos);
1169         return 0;
1170     }
1171
1172     swf_SetTagPos(tag, classes_pos);
1173     for(t=0;t<num_classes;t++) {
1174         abc_class_t*cls = (abc_class_t*)array_getvalue(file->classes, t);
1175
1176         int classname_index = swf_GetU30(tag);
1177         int superclass_index = swf_GetU30(tag);
1178         cls->classname = (multiname_t*)array_getvalue(pool->multinames, classname_index);
1179         cls->superclass = (multiname_t*)array_getvalue(pool->multinames, superclass_index);
1180         cls->flags = swf_GetU8(tag);
1181         const char*ns = "";
1182         if(cls->flags&8) {
1183             int ns_index = swf_GetU30(tag);
1184             cls->protectedNS = array_getkey(pool->namespaces, ns_index);
1185         }
1186         
1187         int num_interfaces = swf_GetU30(tag); //interface count
1188         int s;
1189         for(s=0;s<num_interfaces;s++) {
1190             swf_GetU30(tag); // multiname index TODO
1191         }
1192         int iinit = swf_GetU30(tag);
1193         cls->constructor = (abc_method_t*)array_getvalue(file->methods, iinit);
1194         cls->traits = traits_parse(tag, pool, file);
1195     }
1196     for(t=0;t<num_classes;t++) {
1197         abc_class_t*cls = (abc_class_t*)array_getvalue(file->classes, t);
1198         /* SKIP */
1199         swf_GetU30(tag); // cindex
1200         cls->static_constructor_traits = traits_parse(tag, pool, file);
1201     }
1202     int num_scripts2 = swf_GetU30(tag);
1203     for(t=0;t<num_scripts2;t++) {
1204         int init = swf_GetU30(tag);
1205         abc_method_t*m = (abc_method_t*)array_getvalue(file->methods, init);
1206         
1207         abc_script_t*s = malloc(sizeof(abc_script_t));
1208         memset(s, 0, sizeof(abc_script_t));
1209         s->method = m;
1210         s->traits = traits_parse(tag, pool, file);
1211         array_append(file->scripts, 0, s);
1212         if(!s->traits) {
1213             fprintf(stderr, "Can't parse script traits\n");
1214             return 0;
1215         }
1216     }
1217
1218     //pool_destroy(pool);
1219     return file;
1220 }
1221
1222 static void code_write(TAG*tag, abc_code_t*code, pool_t*pool, abc_file_t*file)
1223 {
1224     int len = 0;
1225     abc_code_t*c = code;
1226     while(c) {
1227         len += opcode_write(0, c, pool, file);
1228         c = c->next;
1229     }
1230     swf_SetU30(tag, len);
1231     int pos = tag->len;
1232     c = code;
1233     while(c) {
1234         opcode_write(tag, c, pool, file);
1235         c = c->next;
1236     }
1237     assert(tag->len - pos == len);
1238 }
1239
1240 void swf_WriteABC(TAG*abctag, void*code)
1241 {
1242     abc_file_t*file = (abc_file_t*)code;
1243     pool_t*pool = pool_new();
1244
1245     TAG*tmp = swf_InsertTag(0,0);
1246     TAG*tag = tmp;
1247     int t;
1248
1249     swf_SetU30(tag, file->methods->num);
1250    
1251     /* enumerate classes, methods and method bodies */
1252     for(t=0;t<file->methods->num;t++) {
1253         abc_method_t*m = (abc_method_t*)array_getvalue(file->methods, t);
1254         m->index = t;
1255     }
1256     for(t=0;t<file->classes->num;t++) {
1257         abc_class_t*c = (abc_class_t*)array_getvalue(file->classes, t);
1258         c->index = t;
1259     }
1260     for(t=0;t<file->method_bodies->num;t++) {
1261         abc_method_body_t*m = (abc_method_body_t*)array_getvalue(file->method_bodies, t);
1262         m->index = t;
1263     }
1264
1265     for(t=0;t<file->methods->num;t++) {
1266         abc_method_t*m = (abc_method_t*)array_getvalue(file->methods, t);
1267         int n = 0;
1268         multiname_list_t*l = m->parameters;
1269         int num_params = list_length(m->parameters);
1270         swf_SetU30(tag, num_params);
1271         if(m->return_type) 
1272             swf_SetU30(tag, pool_register_multiname(pool, m->return_type));
1273         else
1274             swf_SetU30(tag, 0);
1275         int s;
1276         while(l) {
1277             swf_SetU30(tag, pool_register_multiname(pool, l->multiname));
1278             l = l->next;
1279         }
1280         if(m->name) {
1281             swf_SetU30(tag, pool_register_string(pool, m->name));
1282         } else {
1283             swf_SetU30(tag, 0);
1284         }
1285
1286         swf_SetU8(tag, 0); //flags
1287     }
1288    
1289     /* write metadata */
1290     swf_SetU30(tag, file->metadata->num);
1291     for(t=0;t<file->metadata->num;t++) {
1292         const char*entry_name = array_getkey(file->metadata, t);
1293         swf_SetU30(tag, pool_register_string(pool, entry_name));
1294         array_t*items = (array_t*)array_getvalue(file->metadata, t);
1295         swf_SetU30(tag, items->num);
1296         int s;
1297         for(s=0;s<items->num;s++) {
1298             int i1 = pool_register_string(pool, array_getkey(items, s));
1299             int i2 = pool_register_string(pool, array_getvalue(items, s));
1300             swf_SetU30(tag, i1);
1301             swf_SetU30(tag, i2);
1302         }
1303     }
1304
1305     swf_SetU30(tag, file->classes->num);
1306     for(t=0;t<file->classes->num;t++) {
1307         abc_class_t*c = (abc_class_t*)array_getvalue(file->classes, t);
1308    
1309         int classname_index = pool_register_multiname(pool, c->classname);
1310         int superclass_index = pool_register_multiname(pool, c->superclass);
1311
1312         swf_SetU30(tag, classname_index);
1313         swf_SetU30(tag, superclass_index);
1314
1315         swf_SetU8(tag, c->flags); // flags
1316         if(c->flags&0x08) {
1317             namespace_t*ns = abc_protectednamespace(file, c->protectedNS);
1318             int ns_index = pool_register_namespace(pool, ns);
1319             swf_SetU30(tag, ns_index);
1320         }
1321
1322         swf_SetU30(tag, list_length(c->interfaces));
1323         multiname_list_t*interface= c->interfaces;
1324         while(interface) {
1325             swf_SetU30(tag, pool_register_multiname(pool, interface->multiname));
1326             interface = interface->next;
1327         }
1328
1329         if(!c->constructor) {
1330             fprintf(stderr, "Error: Class %s has no constructor\n", c->classname);
1331             return;
1332         }
1333         swf_SetU30(tag, c->constructor->index);
1334         traits_write(pool, tag, c->traits);
1335     }
1336     for(t=0;t<file->classes->num;t++) {
1337         abc_class_t*c = (abc_class_t*)array_getvalue(file->classes, t);
1338         if(!c->static_constructor) {
1339             fprintf(stderr, "Error: Class %s has no static constructor\n", c->classname);
1340             return;
1341         }
1342         swf_SetU30(tag, c->static_constructor->index);
1343         traits_write(pool, tag, c->static_constructor_traits);
1344     }
1345
1346     swf_SetU30(tag, file->scripts->num);
1347     for(t=0;t<file->scripts->num;t++) {
1348         abc_script_t*s = (abc_script_t*)array_getvalue(file->scripts, t);
1349         swf_SetU30(tag, s->method->index); //!=t!
1350         traits_write(pool, tag, s->traits);
1351     }
1352
1353     swf_SetU30(tag, file->method_bodies->num);
1354     for(t=0;t<file->method_bodies->num;t++) {
1355         abc_method_body_t*c = (abc_method_body_t*)array_getvalue(file->method_bodies, t);
1356         abc_method_t*m = c->method;
1357         swf_SetU30(tag, m->index);
1358         swf_SetU30(tag, c->max_stack);
1359         swf_SetU30(tag, c->local_count);
1360         swf_SetU30(tag, c->init_scope_depth);
1361         swf_SetU30(tag, c->max_scope_depth);
1362
1363         code_write(tag, c->code, pool, file);
1364
1365         swf_SetU30(tag, c->exception_count);
1366         traits_write(pool, tag, c->traits);
1367     }
1368
1369
1370     for(t=1;t<pool->multinames->num;t++) {
1371         multiname_t*m = (multiname_t*)array_getvalue(pool->multinames, t);
1372         if(m->ns) {
1373             pool_register_namespace(pool, m->ns);
1374         }
1375         if(m->namespace_set) {
1376             pool_register_namespace_set(pool, m->namespace_set);
1377         }
1378         if(m->name) {
1379             pool_register_string(pool, m->name);
1380         }
1381     }
1382     for(t=1;t<pool->namespace_sets->num;t++) {
1383         namespace_set_t*set = (namespace_set_t*)array_getvalue(pool->namespace_sets, t);
1384         namespace_list_t*i = set->namespaces;
1385         while(i) {
1386             pool_register_namespace(pool, i->namespace);
1387             i = i->next;
1388         }
1389     }
1390     for(t=1;t<pool->namespaces->num;t++) {
1391         namespace_t*ns= (namespace_t*)array_getvalue(pool->namespaces, t);
1392         array_append_if_new(pool->strings, ns->name, 0);
1393     }
1394
1395     // --- start to write real tag --
1396     
1397     tag = abctag;
1398
1399     if(tag->id == ST_DOABC) {
1400         swf_SetU32(tag, 1); // flags
1401         swf_SetString(tag, file->name);
1402     }
1403
1404     swf_SetU16(tag, 0x10); //version
1405     swf_SetU16(tag, 0x2e);
1406
1407     swf_SetU30(tag, pool->ints->num>1?pool->ints->num:0);
1408     for(t=1;t<pool->ints->num;t++) {
1409         S32 val = (ptroff_t)array_getvalue(pool->ints, t);
1410         swf_SetS30(tag, val);
1411     }
1412     swf_SetU30(tag, pool->uints->num>1?pool->uints->num:0);
1413     for(t=1;t<pool->uints->num;t++) {
1414         swf_SetU30(tag, (ptroff_t)array_getvalue(pool->uints, t));
1415     }
1416     swf_SetU30(tag, pool->floats->num>1?pool->floats->num:0);
1417     for(t=1;t<pool->floats->num;t++) {
1418         array_getvalue(pool->floats, t);
1419         swf_SetD64(tag, 0.0); // fixme
1420     }
1421     swf_SetU30(tag, pool->strings->num>1?pool->strings->num:0);
1422     for(t=1;t<pool->strings->num;t++) {
1423         swf_SetU30String(tag, array_getkey(pool->strings, t));
1424     }
1425     swf_SetU30(tag, pool->namespaces->num>1?pool->namespaces->num:0);
1426     for(t=1;t<pool->namespaces->num;t++) {
1427         namespace_t*ns= (namespace_t*)array_getvalue(pool->namespaces, t);
1428         const char*name = ns->name;
1429         int i = pool_find_string(pool, name);
1430         swf_SetU8(tag, ns->access);
1431         swf_SetU30(tag, i);
1432     }
1433     swf_SetU30(tag, pool->namespace_sets->num>1?pool->namespace_sets->num:0);
1434     for(t=1;t<pool->namespace_sets->num;t++) {
1435         namespace_set_t*set = (namespace_set_t*)array_getvalue(pool->namespace_sets, t);
1436         namespace_list_t*i = set->namespaces; 
1437         int len = list_length(i);
1438         swf_SetU30(tag, len);
1439         while(i) {
1440             int index = pool_find_namespace(pool, i->namespace);
1441             swf_SetU30(tag, index);
1442             i = i->next;
1443         }
1444     }
1445
1446     swf_SetU30(tag, pool->multinames->num>1?pool->multinames->num:0);
1447     for(t=1;t<pool->multinames->num;t++) {
1448         multiname_t*m = (multiname_t*)array_getvalue(pool->multinames, t);
1449         swf_SetU8(tag, m->type);
1450
1451         if(m->ns) {
1452             assert(m->type==0x07 || m->type==0x0d);
1453             int i = pool_find_namespace(pool, m->ns);
1454             if(i<0) fprintf(stderr, "internal error: unregistered namespace %02x %s %s\n", m->ns->access, access2str(m->ns->access), m->ns->name);
1455             swf_SetU30(tag, i);
1456         } else {
1457             assert(m->type!=0x07 && m->type!=0x0d);
1458         }
1459         if(m->name) {
1460             assert(m->type==0x09 || m->type==0x0e || m->type==0x07 || m->type==0x0d || m->type==0x0f || m->type==0x10);
1461             int i = pool_find_string(pool, m->name);
1462             if(i<0) fprintf(stderr, "internal error: unregistered name\n");
1463             swf_SetU30(tag, i);
1464         } else {
1465             assert(m->type!=0x09 && m->type!=0x0e && m->type!=0x07 && m->type!=0x0d && m->type!=0x0f && m->type!=0x10);
1466         }
1467         if(m->namespace_set) {
1468             assert(m->type==0x09 || m->type==0x0e || m->type==0x1c || m->type==0x1b);
1469             int i = pool_find_namespace_set(pool, m->namespace_set);
1470             if(i<0) fprintf(stderr, "internal error: unregistered namespace set\n");
1471             swf_SetU30(tag, i);
1472         } else {
1473             assert(m->type!=0x09 && m->type!=0x0e && m->type!=0x1c && m->type!=0x1b);
1474         }
1475
1476     }
1477
1478     swf_SetBlock(tag, tmp->data, tmp->len);
1479
1480     swf_DeleteTag(0, tmp);
1481     pool_destroy(pool);
1482 }
1483
1484 void swf_FreeABC(void*code)
1485 {
1486     abc_file_t*file= (abc_file_t*)code;
1487
1488     int t;
1489     for(t=0;t<file->metadata->num;t++) {
1490         array_t*items = (array_t*)array_getvalue(file->metadata, t);
1491         array_free(items);
1492     }
1493     array_free(file->metadata);
1494
1495     for(t=0;t<file->methods->num;t++) {
1496         abc_method_t*m = (abc_method_t*)array_getvalue(file->methods, t);
1497         list_free(m->parameters);m->parameters=0;
1498         free(m);
1499     }
1500     array_free(file->methods);
1501
1502     for(t=0;t<file->classes->num;t++) {
1503         abc_class_t*cls = (abc_class_t*)array_getvalue(file->classes, t);
1504         list_free(cls->interfaces);cls->interfaces=0;
1505         traits_free(cls->traits);cls->traits=0;
1506         traits_free(cls->static_constructor_traits);cls->static_constructor_traits=0;
1507         free(cls);
1508     }
1509     array_free(file->classes);
1510
1511     for(t=0;t<file->scripts->num;t++) {
1512         abc_script_t*s = (abc_script_t*)array_getvalue(file->scripts, t);
1513         traits_free(s->traits);s->traits=0;
1514         free(s);
1515     }
1516     array_free(file->scripts);
1517
1518     for(t=0;t<file->method_bodies->num;t++) {
1519         abc_method_body_t*body = (abc_method_body_t*)array_getvalue(file->method_bodies, t);
1520         code_free(body->code);body->code=0;
1521         traits_free(body->traits);body->traits=0;
1522         free(body);
1523     }
1524     array_free(file->method_bodies);
1525
1526     free(file);
1527 }
1528
1529 abc_code_t* add_opcode(abc_code_t*atag, U8 op)
1530 {
1531     abc_code_t*tmp = (abc_code_t*)malloc(sizeof(abc_code_t));
1532     tmp->opcode = op;
1533     tmp->next = 0;
1534     if(atag) {
1535         tmp->prev = atag;
1536         atag->next = tmp;
1537         tmp->parent = atag->parent;
1538     } else {
1539         tmp->prev = 0;
1540         tmp->parent = tmp;
1541     }
1542     return tmp;
1543 }
1544
1545 #include "abc_ops.c"
1546
1547 void swf_AddButtonLinks(SWF*swf, char stop_each_frame, char events)
1548 {
1549     int num_frames = 0;
1550     int has_buttons = 0;
1551     TAG*tag=swf->firstTag;
1552     while(tag) {
1553         if(tag->id == ST_SHOWFRAME)
1554             num_frames++;
1555         if(tag->id == ST_DEFINEBUTTON || tag->id == ST_DEFINEBUTTON2)
1556             has_buttons = 1;
1557         tag = tag->next;
1558     }
1559
1560     abc_file_t*file = abc_file_new();
1561     abc_method_body_t*c = 0;
1562    
1563     abc_class_t*cls = abc_class_new(file, "rfx::MainTimeline", "flash.display::MovieClip");
1564     abc_class_protectedNS(cls, "rfx:MainTimeline");
1565   
1566     TAG*abctag = swf_InsertTagBefore(swf, swf->firstTag, ST_DOABC);
1567     
1568     tag = swf_InsertTag(abctag, ST_SYMBOLCLASS);
1569     swf_SetU16(tag, 1);
1570     swf_SetU16(tag, 0);
1571     swf_SetString(tag, "rfx.MainTimeline");
1572
1573     c = abc_class_staticconstructor(cls, 0, 0);
1574     c->max_stack = 1;
1575     c->local_count = 1;
1576     c->init_scope_depth = 9;
1577     c->max_scope_depth = 10;
1578
1579     __ getlocal_0(c);
1580     __ pushscope(c);
1581     __ returnvoid(c);
1582
1583     c = abc_class_constructor(cls, 0, 0);
1584     c->max_stack = 3;
1585     c->local_count = 1;
1586     c->init_scope_depth = 10;
1587     c->max_scope_depth = 11;
1588     
1589     debugfile(c, "constructor.as");
1590
1591     __ getlocal_0(c);
1592     __ pushscope(c);
1593
1594     __ getlocal_0(c);
1595     __ constructsuper(c,0);
1596
1597     __ getlex(c, "[package]flash.system::Security");
1598     __ pushstring(c, "*");
1599     __ callpropvoid(c, "[package]::allowDomain", 1);
1600     
1601     if(stop_each_frame || has_buttons) {
1602         int frame = 0;
1603         tag = swf->firstTag;
1604         abc_method_body_t*f = 0; //frame script
1605         while(tag && tag->id!=ST_END) {
1606             char framename[80];
1607             char needs_framescript=0;
1608             char buttonname[80];
1609             char functionname[80];
1610             sprintf(framename, "[packageinternal]rfx::frame%d", frame);
1611             
1612             if(!f && (tag->id == ST_DEFINEBUTTON || tag->id == ST_DEFINEBUTTON2 || stop_each_frame)) {
1613                 /* make the contructor add a frame script */
1614                 __ findpropstrict(c,"[package]::addFrameScript");
1615                 __ pushbyte(c,frame);
1616                 __ getlex(c,framename);
1617                 __ callpropvoid(c,"[package]::addFrameScript",2);
1618
1619                 f = abc_class_method(cls, 0, framename, 0);
1620                 f->max_stack = 3;
1621                 f->local_count = 1;
1622                 f->init_scope_depth = 10;
1623                 f->max_scope_depth = 11;
1624                 __ debugfile(f, "framescript.as");
1625                 __ debugline(f, 1);
1626                 __ getlocal_0(f);
1627                 __ pushscope(f);
1628             }
1629
1630             if(tag->id == ST_DEFINEBUTTON || tag->id == ST_DEFINEBUTTON2) {
1631                 U16 id = swf_GetDefineID(tag);
1632                 sprintf(buttonname, "::button%d", swf_GetDefineID(tag));
1633                 __ getlex(f,buttonname);
1634                 __ getlex(f,"flash.events::MouseEvent");
1635                 __ getproperty(f, "::CLICK");
1636                 sprintf(functionname, "::clickbutton%d", swf_GetDefineID(tag));
1637                 __ getlex(f,functionname);
1638                 __ callpropvoid(f, "::addEventListener" ,2);
1639
1640                 if(stop_each_frame) {
1641                     __ findpropstrict(f, "[package]::stop");
1642                     __ callpropvoid(f, "[package]::stop", 0);
1643                 }
1644                 needs_framescript = 1;
1645
1646                 abc_method_body_t*h =
1647                     abc_class_method(cls, "::void", functionname, 1, "flash.events::MouseEvent");
1648                 h->max_stack = 6;
1649                 h->local_count = 2;
1650                 h->init_scope_depth = 10;
1651                 h->max_scope_depth = 11;
1652                 __ getlocal_0(h);
1653                 __ pushscope(h);
1654
1655                 ActionTAG*oldaction = swf_ButtonGetAction(tag);
1656                 if(oldaction && oldaction->op == ACTION__GOTOFRAME) {
1657                     int framenr = GET16(oldaction->data);
1658                     if(framenr>254) {
1659                         fprintf(stderr, "Warning: Couldn't translate jump to frame %d to flash 9 actionscript\n", framenr);
1660                     }
1661                     if(!events) {
1662                         __ findpropstrict(h,"[package]::gotoAndStop");
1663                         __ pushbyte(h,framenr+1);
1664                         __ callpropvoid(h,"[package]::gotoAndStop", 1);
1665                     } else {
1666                         char framename[80];
1667                         sprintf(framename, "frame%d", framenr);
1668                         __ getlocal_0(h); //this
1669                         __ findpropstrict(h, "[package]flash.events::TextEvent");
1670                         __ pushstring(h, "link");
1671                         __ pushtrue(h);
1672                         __ pushtrue(h);
1673                         __ pushstring(h, framename);
1674                         __ constructprop(h,"[package]flash.events::TextEvent", 4);
1675                         __ callpropvoid(h,"[package]::dispatchEvent", 1);
1676                     }
1677                 } else if(oldaction && oldaction->op == ACTION__GETURL) {
1678                     if(!events) {
1679                         __ findpropstrict(h,"flash.net::navigateToURL");
1680                         __ findpropstrict(h,"flash.net::URLRequest");
1681                         // TODO: target _blank
1682                         __ pushstring(h,oldaction->data); //url
1683                         __ constructprop(h,"flash.net::URLRequest", 1);
1684                         __ callpropvoid(h,"flash.net::navigateToURL", 1);
1685                     } else {
1686                         __ getlocal_0(h); //this
1687                         __ findpropstrict(h, "[package]flash.events::TextEvent");
1688                         __ pushstring(h, "link");
1689                         __ pushtrue(h);
1690                         __ pushtrue(h);
1691                         __ pushstring(h,oldaction->data); //url
1692                         __ constructprop(h,"[package]flash.events::TextEvent", 4);
1693                         __ callpropvoid(h,"[package]::dispatchEvent", 1);
1694                     }
1695                 } else if(oldaction) {
1696                     fprintf(stderr, "Warning: Couldn't translate button code of button %d to flash 9 abc action\n", id);
1697                 }
1698                 __ returnvoid(h);
1699                 swf_ActionFree(oldaction);
1700             }
1701             if(tag->id == ST_SHOWFRAME) {
1702                 if(f) {
1703                     __ returnvoid(f);
1704                     f = 0;
1705                 }
1706                 frame++;
1707             }
1708             tag = tag->next;
1709         }
1710         if(f) {
1711             __ returnvoid(f);
1712         }
1713     }
1714     __ returnvoid(c);
1715
1716     tag = swf->firstTag;
1717     while(tag) {
1718         if(tag->id == ST_DEFINEBUTTON || tag->id == ST_DEFINEBUTTON2) {
1719             char buttonname[80];
1720             sprintf(buttonname, "::button%d", swf_GetDefineID(tag));
1721             abc_AddSlot(cls, buttonname, 0, "flash.display::SimpleButton");
1722         }
1723         tag = tag->next;
1724     }
1725
1726
1727     abc_script_t*s = abc_initscript(file, 0, 0);
1728     c = s->method->body;
1729     c->max_stack = 2;
1730     c->local_count = 1;
1731     c->init_scope_depth = 1;
1732     c->max_scope_depth = 9;
1733
1734     __ getlocal_0(c);
1735     __ pushscope(c);
1736     __ getscopeobject(c, 0);
1737     __ getlex(c,"::Object");
1738     __ pushscope(c);
1739     __ getlex(c,"flash.events::EventDispatcher");
1740     __ pushscope(c);
1741     __ getlex(c,"flash.display::DisplayObject");
1742     __ pushscope(c);
1743     __ getlex(c,"flash.display::InteractiveObject");
1744     __ pushscope(c);
1745     __ getlex(c,"flash.display::DisplayObjectContainer");
1746     __ pushscope(c);
1747     __ getlex(c,"flash.display::Sprite");
1748     __ pushscope(c);
1749     __ getlex(c,"flash.display::MovieClip");
1750     __ pushscope(c);
1751     __ getlex(c,"flash.display::MovieClip");
1752     __ newclass(c,cls);
1753     __ popscope(c);
1754     __ popscope(c);
1755     __ popscope(c);
1756     __ popscope(c);
1757     __ popscope(c);
1758     __ popscope(c);
1759     __ popscope(c);
1760     __ initproperty(c,"rfx::MainTimeline");
1761     __ returnvoid(c);
1762
1763     //abc_method_body_addClassTrait(c, "rfx:MainTimeline", 1, cls);
1764     abc_initscript_addClassTrait(s, "rfx::MainTimeline", 1, cls);
1765
1766     swf_WriteABC(abctag, file);
1767 }
1768