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