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