-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathswffile.py
1583 lines (1348 loc) · 49.7 KB
/
swffile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
swffile.py - SWF file parser module
(C) 2015-2016 by Tillmann Werner, <tillmann.werner@gmx.de>
'''
__author__ = 'Tillmann Werner'
__version__ = '0.2.0.0'
import pylzma
import zlib
from struct import *
# AVM2 opcodes
opcodes = {}
opcodes[0x02] = { "name" : "nop", "argtypes" : [] }
opcodes[0x03] = { "name" : "throw", "argtypes" : [] }
opcodes[0x04] = { "name" : "getsuper", "argtypes" : [ "u30" ] }
opcodes[0x07] = { "name" : "dxnslate", "argtypes" : [] }
opcodes[0x08] = { "name" : "kill", "argtypes" : [ "register" ] }
opcodes[0x09] = { "name" : "label", "argtypes" : [] }
opcodes[0x0c] = { "name" : "ifnlt", "argtypes" : [ "offset" ] }
opcodes[0x0d] = { "name" : "ifnle", "argtypes" : [ "offset" ] }
opcodes[0x0e] = { "name" : "ifngt", "argtypes" : [ "offset" ] }
opcodes[0x0f] = { "name" : "ifnge", "argtypes" : [ "offset" ] }
opcodes[0x10] = { "name" : "jump", "argtypes" : [ "offset" ] }
opcodes[0x11] = { "name" : "iftrue", "argtypes" : [ "offset" ] }
opcodes[0x12] = { "name" : "iffalse", "argtypes" : [ "offset" ] }
opcodes[0x13] = { "name" : "ifeq", "argtypes" : [ "offset" ] }
opcodes[0x14] = { "name" : "ifne", "argtypes" : [ "offset" ] }
opcodes[0x15] = { "name" : "iflt", "argtypes" : [ "offset" ] }
opcodes[0x16] = { "name" : "ifle", "argtypes" : [ "offset" ] }
opcodes[0x17] = { "name" : "ifgt", "argtypes" : [ "offset" ] }
opcodes[0x18] = { "name" : "ifge", "argtypes" : [ "offset" ] }
opcodes[0x19] = { "name" : "ifstricteq", "argtypes" : [ "offset" ] }
opcodes[0x1a] = { "name" : "ifstrictne", "argtypes" : [ "offset" ] }
opcodes[0x1b] = { "name" : "lookupswitch", "argtypes" : [ "s24", "u30" ] } # + a varying number of s24's
opcodes[0x1c] = { "name" : "pushwith", "argtypes" : [] }
opcodes[0x1d] = { "name" : "popscope", "argtypes" : [] }
opcodes[0x1e] = { "name" : "nextname", "argtypes" : [] }
opcodes[0x1f] = { "name" : "hasnext", "argtypes" : [] }
opcodes[0x20] = { "name" : "pushnull", "argtypes" : [] }
opcodes[0x21] = { "name" : "pushundefined", "argtypes" : [] }
opcodes[0x23] = { "name" : "nextvalue", "argtypes" : [] }
opcodes[0x24] = { "name" : "pushbyte", "argtypes" : [ "u8" ] }
opcodes[0x25] = { "name" : "pushshort", "argtypes" : [ "u30" ] }
opcodes[0x26] = { "name" : "pushtrue", "argtypes" : [] }
opcodes[0x27] = { "name" : "pushfalse", "argtypes" : [] }
opcodes[0x28] = { "name" : "pushnan", "argtypes" : [] }
opcodes[0x29] = { "name" : "pop", "argtypes" : [] }
opcodes[0x2a] = { "name" : "dup", "argtypes" : [] }
opcodes[0x2b] = { "name" : "swap", "argtypes" : [] }
opcodes[0x2c] = { "name" : "pushstring", "argtypes" : [ "string" ] }
opcodes[0x2d] = { "name" : "pushint", "argtypes" : [ "integer" ] }
opcodes[0x2e] = { "name" : "pushuint", "argtypes" : [ "uinteger" ] }
opcodes[0x2f] = { "name" : "pushdouble", "argtypes" : [ "double" ] }
opcodes[0x30] = { "name" : "pushscope", "argtypes" : [] }
opcodes[0x31] = { "name" : "pushnamespace", "argtypes" : [ "u30" ] }
opcodes[0x32] = { "name" : "hasnext2", "argtypes" : [ "register", "register" ] }
opcodes[0x40] = { "name" : "newfunction", "argtypes" : [ "method" ] }
opcodes[0x41] = { "name" : "call", "argtypes" : [ "u30" ] }
opcodes[0x46] = { "name" : "callproperty", "argtypes" : [ "multiname", "u30" ] }
opcodes[0x47] = { "name" : "returnvoid", "argtypes" : [] }
opcodes[0x48] = { "name" : "returnvalue", "argtypes" : [] }
opcodes[0x42] = { "name" : "construct", "argtypes" : [ "u30" ] }
opcodes[0x49] = { "name" : "constructsuper", "argtypes" : [ "u30" ] }
opcodes[0x4a] = { "name" : "constructprop", "argtypes" : [ "multiname", "u30" ] }
opcodes[0x4c] = { "name" : "callproplex", "argtypes" : [ "multiname", "u30" ] }
opcodes[0x4e] = { "name" : "callsupervoid", "argtypes" : [ "multiname", "u30" ] }
opcodes[0x4f] = { "name" : "callpropvoid", "argtypes" : [ "multiname", "u30" ] }
opcodes[0x53] = { "name" : "applytype", "argtypes" : [ "u30" ] }
opcodes[0x55] = { "name" : "newobject", "argtypes" : [ "u30" ] }
opcodes[0x56] = { "name" : "newarray", "argtypes" : [ "u30" ] }
opcodes[0x57] = { "name" : "newactivation", "argtypes" : [] }
opcodes[0x58] = { "name" : "newclass", "argtypes" : [ "u30" ] }
opcodes[0x59] = { "name" : "getdescendants", "argtypes" : [ "u30" ] }
opcodes[0x5a] = { "name" : "newcatch", "argtypes" : [ "u30" ] }
opcodes[0x5d] = { "name" : "findpropstrict", "argtypes" : [ "multiname" ] }
opcodes[0x5e] = { "name" : "findproperty", "argtypes" : [ "multiname" ] }
opcodes[0x5f] = { "name" : "finddef", "argtypes" : [ "multiname" ] }
opcodes[0x60] = { "name" : "getlex", "argtypes" : [ "multiname" ] }
opcodes[0x61] = { "name" : "setproperty", "argtypes" : [ "multiname" ] }
opcodes[0x62] = { "name" : "getlocal", "argtypes" : [ "register" ] }
opcodes[0x63] = { "name" : "setlocal", "argtypes" : [ "register" ] }
opcodes[0x64] = { "name" : "getglobalscope", "argtypes" : [] }
opcodes[0x65] = { "name" : "getscopeobject", "argtypes" : [ "u8" ] }
opcodes[0x66] = { "name" : "getproperty", "argtypes" : [ "multiname" ] }
opcodes[0x68] = { "name" : "initproperty", "argtypes" : [ "multiname" ] }
opcodes[0x6a] = { "name" : "deleteproperty", "argtypes" : [ "multiname" ] }
opcodes[0x6c] = { "name" : "getslot", "argtypes" : [ "u30" ] }
opcodes[0x6d] = { "name" : "setslot", "argtypes" : [ "u30" ] }
opcodes[0x70] = { "name" : "convert_s", "argtypes" : [] }
opcodes[0x73] = { "name" : "convert_i", "argtypes" : [] }
opcodes[0x74] = { "name" : "convert_u", "argtypes" : [] }
opcodes[0x75] = { "name" : "convert_d", "argtypes" : [] }
opcodes[0x76] = { "name" : "convert_b", "argtypes" : [] }
opcodes[0x77] = { "name" : "convert_o", "argtypes" : [] }
opcodes[0x78] = { "name" : "checkfilter", "argtypes" : [] }
opcodes[0x80] = { "name" : "coerce", "argtypes" : [ "multiname" ] }
opcodes[0x82] = { "name" : "coerce_a", "argtypes" : [] }
opcodes[0x85] = { "name" : "coerce_s", "argtypes" : [] }
opcodes[0x87] = { "name" : "astypelate", "argtypes" : [] }
opcodes[0x90] = { "name" : "negate", "argtypes" : [] }
opcodes[0x91] = { "name" : "increment", "argtypes" : [] }
opcodes[0x92] = { "name" : "inclocal", "argtypes" : [ "u30" ] }
opcodes[0x93] = { "name" : "decrement", "argtypes" : [] }
opcodes[0x94] = { "name" : "declocal", "argtypes" : [ "u30" ] }
opcodes[0x95] = { "name" : "typeof", "argtypes" : [] }
opcodes[0x96] = { "name" : "not", "argtypes" : [] }
opcodes[0x97] = { "name" : "bitnot", "argtypes" : [] }
opcodes[0xa0] = { "name" : "add", "argtypes" : [] }
opcodes[0xa1] = { "name" : "subtract", "argtypes" : [] }
opcodes[0xa2] = { "name" : "multiply", "argtypes" : [] }
opcodes[0xa3] = { "name" : "divide", "argtypes" : [] }
opcodes[0xa4] = { "name" : "modulo", "argtypes" : [] }
opcodes[0xa5] = { "name" : "lshift", "argtypes" : [] }
opcodes[0xa6] = { "name" : "rshift", "argtypes" : [] }
opcodes[0xa7] = { "name" : "urshift", "argtypes" : [] }
opcodes[0xa8] = { "name" : "bitand", "argtypes" : [] }
opcodes[0xa9] = { "name" : "bitor", "argtypes" : [] }
opcodes[0xab] = { "name" : "equals", "argtypes" : [] }
opcodes[0xaa] = { "name" : "bitxor", "argtypes" : [] }
opcodes[0xac] = { "name" : "strictequals", "argtypes" : [] }
opcodes[0xad] = { "name" : "lessthan", "argtypes" : [] }
opcodes[0xae] = { "name" : "lessequals", "argtypes" : [] }
opcodes[0xaf] = { "name" : "greaterthan", "argtypes" : [] }
opcodes[0xb0] = { "name" : "greaterequals", "argtypes" : [] }
opcodes[0xb1] = { "name" : "instanceof", "argtypes" : [] }
opcodes[0xb2] = { "name" : "istype", "argtypes" : [ "multiname" ] }
opcodes[0xb3] = { "name" : "istypelate", "argtypes" : [] }
opcodes[0xb4] = { "name" : "in", "argtypes" : [] }
opcodes[0xc0] = { "name" : "increment_i", "argtypes" : [] }
opcodes[0xc1] = { "name" : "decrement_i", "argtypes" : [] }
opcodes[0xc2] = { "name" : "inclocal_i", "argtypes" : [ "u30" ] }
opcodes[0xc3] = { "name" : "declocal_i", "argtypes" : [ "u30" ] }
opcodes[0xc4] = { "name" : "negate_i", "argtypes" : [] }
opcodes[0xc5] = { "name" : "add_i", "argtypes" : [] }
opcodes[0xc6] = { "name" : "subtract_i", "argtypes" : [] }
opcodes[0xc7] = { "name" : "multiply_i", "argtypes" : [] }
opcodes[0xd0] = { "name" : "getlocal_0", "argtypes" : [] }
opcodes[0xd1] = { "name" : "getlocal_1", "argtypes" : [] }
opcodes[0xd2] = { "name" : "getlocal_2", "argtypes" : [] }
opcodes[0xd3] = { "name" : "getlocal_3", "argtypes" : [] }
opcodes[0xd4] = { "name" : "setlocal_0", "argtypes" : [] }
opcodes[0xd5] = { "name" : "setlocal_1", "argtypes" : [] }
opcodes[0xd6] = { "name" : "setlocal_2", "argtypes" : [] }
opcodes[0xd7] = { "name" : "setlocal_3", "argtypes" : [] }
opcodes[0xf0] = { "name" : "debugline", "argtypes" : [ "u30" ] }
opcodes[0xf1] = { "name" : "debugfile", "argtypes" : [ "string" ] }
class SwfHeader():
def __init__(self, data):
self.Signature = data[:3]
self.Version = ord(data[3])
self.FileLength, = unpack('<I', data[4:8])
# frame size: varying, depending on nbits, byte-aligned
self.FrameSize = lambda:0
self.FrameSize.Nbits = ord(data[8]) >> 3
totalbits = 5 + 4 * self.FrameSize.Nbits
off = (totalbits / 8) + (1 if totalbits % 8 != 0 else 0)
bitstr = ''.join(['{:08b}'.format(ord(b)) for b in data[8:8+off]])
self.FrameSize.Xmin = int(bitstr[5+(0*self.FrameSize.Nbits):5+(1*self.FrameSize.Nbits)], 2)
self.FrameSize.Xmax = int(bitstr[5+(1*self.FrameSize.Nbits):5+(2*self.FrameSize.Nbits)], 2)
self.FrameSize.Ymin = int(bitstr[5+(2*self.FrameSize.Nbits):5+(3*self.FrameSize.Nbits)], 2)
self.FrameSize.Ymax = int(bitstr[5+(3*self.FrameSize.Nbits):5+(4*self.FrameSize.Nbits)], 2)
self.MovieWidth = (self.FrameSize.Xmax - self.FrameSize.Xmin) / 20.0
self.MovieHeight = (self.FrameSize.Ymax - self.FrameSize.Ymin) / 20.0
self.FrameRate = unpack('<H', data[8+off:8+off+2])[0] / 256.0
self.FrameCount, = unpack('<H', data[8+off+2:8+off+4])
self.HeaderSize = 8+off+4
return
class SwfTag():
def __init__(self, data):
recordhdr, = unpack('<H', data[:2])
self.Type = recordhdr >> 6
self.Length = recordhdr & 0x3f
off = 2
if self.Length == 0x3f:
self.Length, = unpack('<I', data[2:6])
off += 4
self.Data = data[off:off+self.Length]
self.TotalSize = self.Length + off
return
class RGB():
def __init__(self, data):
self.Red = ord(data[0])
self.Green = ord(data[1])
self.Blue = ord(data[2])
return
class SwfFormatError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Flash():
def __init__(self, filename=None, data=None, unpack=True):
if filename == None and data == None:
return None
if not filename == None:
self.__orgdata__ = open(filename, 'rb').read()
else:
self.__orgdata__ = data
if unpack == False:
self.__data__ = self.__orgdata__
else:
self.__data__ = self.uncompress(data=self.__orgdata__)
self.header = self.parseHeader(self.__data__)
self.tags = self.parseTagList()
self.tagParser = {
0x09 : self.parseSetBackgroundColor,
0x29 : self.parseProductInfo,
0x3f : self.parseDebugId,
0x41 : self.parseScriptLimits,
0x45 : self.parseFileAttributes,
0x4C : self.parseSymbolClass,
0x52 : self.parseDoABC,
}
self.DoABC = []
self.parseTags()
return
def parseHeader(self, data):
return SwfHeader(data)
def __getS24__(self, data):
if len(data) == 0: return 0
b = ByteArray(data)
return b.readS24()
def __getU30len__(self, data):
if len(data) == 0: return 0
i = 0
while (ord(data[i]) & 0x80):
i += 1
return i + 1
def __getU30__(self, data):
if len(data) == 0: return 0
b = ByteArray(data)
return b.readU30()
def uncompress(self, filename=None, data=None):
# if data has already been uncompressed, return it
if hasattr(self, '__data__'):
return self.__data__
if filename == None and data == None:
return None
if not filename == None:
self.__data__ = open(filename, 'rb').read()
else:
self.__data__ = data
if self.__data__[:3] == 'FWS':
self.compressed = False
return self.__data__
if self.__data__[:3] == 'ZWS':
self.compressed = True
rawdata = pylzma.decompress(self.__data__[12:])
elif self.__data__[:3] == 'CWS':
self.compressed = True
rawdata = zlib.decompress(self.__data__[8:])
else:
raise SwfFormatError('Unexpected magic string, not a Flash file.')
swfdata = 'FWS' + self.__data__[3] + pack('I', len(rawdata) + 8) + rawdata
return swfdata
def getTagListOffset(self):
return
def getFirstTagOfType(self, tagtype):
if self.tags is not None:
for t in self.tags:
if t['type'] == tagtype:
return t['data']
return None
def parseTagList(self):
tagListData = self.__data__[self.header.HeaderSize:]
off = 0
tags = []
# process list of tags
while len(tagListData[off:]) > 0:
tag = SwfTag(tagListData[off:])
tags.append(tag)
off += tag.TotalSize
# end tag reached?
if tag.Type == 0: break;
return tags
def parseTags(self):
if self.tags is not None:
for tag in self.tags:
if tag.Type not in self.tagParser.keys(): continue
self.tagParser[tag.Type](tag)
return
def getActionConstantPool(self):
tagData = []
tagList = self.__data__[self.__tagListOffset__:]
# walk list of tags
while len(tagList) > 0:
recordhdr = unpack('<I', tagList[:4])[0]
tagList = tagList[4:]
print "%04d - %d" % (tagtype, taglen)
if tagtype == 0x88:
# binaryData tag: skip 2 bytes character ID and 4 reserved bytes
tagData.append(tagList[:taglen])
tagList = tagList[taglen:]
return tagData
# tag 0x09
def parseSetBackgroundColor(self, tag):
self.SetBackgroundColor = lambda:0
self.SetBackgroundColor.BackgroundColor = RGB(tag.Data)
return
# tag 0x29
def parseProductInfo(self, tag):
self.ProductInfo = lambda:0
self.ProductInfo.ProductId, = unpack('<I', tag.Data[:4])
self.ProductInfo.Edition, = unpack('<I', tag.Data[4:8])
self.ProductInfo.MajorVersion = ord(tag.Data[8])
self.ProductInfo.MinorVersion = ord(tag.Data[9])
self.ProductInfo.BuildLow, = unpack('<I', tag.Data[10:14])
self.ProductInfo.BuildHigh, = unpack('<I', tag.Data[14:18])
self.ProductInfo.CompilationDate, = unpack('<Q', tag.Data[18:26])
from datetime import datetime
self.ProductInfo.CompilationDateString = datetime.utcfromtimestamp(self.ProductInfo.CompilationDate/1000.0).strftime("%Y-%m-%d %H:%M:%S UTC")
return
# tag 0x3f
def parseDebugId(self, tag):
return
# tag 0x41
def parseScriptLimits(self, tag):
self.ScriptLimits = lambda:0
self.ScriptLimits.MaxRecursionDepth, = unpack('<H', tag.Data[0:2])
self.ScriptLimits.ScriptTimeoutSeconds, = unpack('<H', tag.Data[2:4])
return
# tag 0x45
def parseFileAttributes(self, tag):
if self.header.Version < 7:
raise SwfFormatError('FileAttributes tag not supported by this SWF version.')
if tag.Length != 4 or len(tag.Data) != 4:
raise SwfFormatError('FileAttributes tag has an invalid size.')
self.Flags = lambda:0
self.Flags.Value, = unpack('<I', tag.Data)
self.Flags.UseDirectBlit = 0 != self.Flags.Value & (1 << 5)
self.Flags.UseGPU = 0 != self.Flags.Value & (1 << 6)
self.Flags.HasMetadata = 0 != self.Flags.Value & (1 << 4)
self.Flags.ActionScript3 = 0 != self.Flags.Value & (1 << 3)
self.Flags.UseNetwork = 0 != self.Flags.Value & (1 << 0)
return
# tag 0c4c
def parseSymbolClass(self, tag):
self.SymbolClass = lambda:0
self.SymbolClass.NumSymbols, = unpack('<H', tag.Data[0:2])
off = 2
self.SymbolClass.Tags = []
self.SymbolClass.Names = []
for i in range(self.SymbolClass.NumSymbols):
TagId, = unpack('<H', tag.Data[off:off+2])
Name = tag.Data[off+2:off+2+tag.Data[off+2:].find('\0')]
self.SymbolClass.Tags.append(TagId)
self.SymbolClass.Names.append(Name)
off += 2 + len(Name) + 1
return
# tag 0x52
def parseDoABC(self, tag):
if self.header.Version < 9:
raise SwfFormatError('DoABC tag found in SWF version that does not support it.')
DoABC = lambda:0
DoABC.Flags = lambda:0
DoABC.Flags.Value, = unpack('<I', tag.Data[:4])
DoABC.Flags.kDoAbcLazyInitializeFlag = 0 != (DoABC.Flags.Value & 1)
DoABC.Name = tag.Data[4:5+tag.Data[4:].find('\0')]
DoABC.ABCData = tag.Data[4+len(DoABC.Name):]
self.DoABC.append(DoABC)
def __disas_method__(self, abc, method):
if method.kind == 1:
Params = ''
if len(method.paramNames):
for i in range(len(method.paramNames)):
if Params != '':
Params += ", "
if method.paramNames[i] == '':
if isinstance(method.paramTypes[i].name, str):
Params += "param" + str(i+1) + ":" + method.paramTypes[i].name
elif hasattr(method.paramTypes[i].name, 'name'):
Params += "param" + str(i+1) + ":" + method.paramTypes[i].name.name
else:
if method.paramTypes[i].name != None:
Params += method.paramNames[i] + ":" + method.paramTypes[i].name
return self.parseAvm2Data(abc, method.code)
else:
# FIXME: add support for other kinds
return None
def disassembleABC(self, DoABC):
if not hasattr(DoABC, 'ABCData'):
raise SwfFormatError('DoABC tag without data.')
abc = Abc(DoABC.ABCData, DoABC.Name)
if abc.major != 46 or abc.minor != 16:
raise SwfFormatError('Unsupported AVM2 version.')
for c in abc.classes:
c.disassembly = {}
c.disassembly['class initializer'] = self.parseAvm2Data(abc, c.init.code)
c.disassembly['instance initializer'] = self.parseAvm2Data(abc, c.itraits.init.code)
for name, method in c.itraits.names.iteritems():
if method.kind == 1:
c.disassembly[name] = self.__disas_method__(abc, method)
for name, method in c.names.iteritems():
if method.kind == 1:
c.disassembly[name] = self.__disas_method__(abc, method)
return abc
def parseAvm2Data(self, abc, code, ignoreUnknown=False):
disas = {}
insns = []
disas['insns'] = insns
disas['rawdata'] = code
if code == None: return disas
off = 0
while off < len(code):
try:
opcode = opcodes[ord(code[off])]['name']
except KeyError:
if ignoreUnknown == False:
raise SwfFormatError('Unsupported opcode: 0x%02x' % ord(code[off]))
else:
# ignore unknown bytes
off += 1
continue
else:
pass
size = 1
args = []
argtypes = opcodes[ord(code[off])]['argtypes']
# 'lookupswitch' is the only variable-length instruction
if opcode == 'lookupswitch':
# default offset
args.append(self.__getS24__(code[off+size:off+size+3]) + off + size + 3)
size += 3
# number of cases
args.append(ord(code[off+size]))
size += 1
# skip over offsets
for i in range(0, args[-1]+1):
args.append(self.__getS24__(code[off+size:off+size+3]) + off + size + 3)
argtypes.append('offset')
size += 3
else:
for argtype in argtypes:
if argtype in ['u8']:
args.append(ord(code[off+size]))
size += 1
if argtype in ['offset']:
args.append(self.__getS24__(code[off+size:off+size+3]) + off + size + 3)
size += 3
if argtype in ['u30', 'register', 'multiname', 'method']:
args.append(self.__getU30__(code[off+size:]))
size += self.__getU30len__(code[off+size:])
if argtype in ['integer']:
i = self.__getU30__(code[off+size:])
args.append(abc.ints[i])
size += self.__getU30len__(code[off+size:])
if argtype in ['uinteger']:
i = self.__getU30__(code[off+size:])
args.append(abc.uints[i])
size += self.__getU30len__(code[off+size:])
if argtype in ['double']:
i = self.__getU30__(code[off+size:])
args.append(abc.doubles[i])
size += self.__getU30len__(code[off+size:])
if argtype in ['string']:
i = self.__getU30__(code[off+size:])
args.append('"' + abc.strings[i] + '"')
size += self.__getU30len__(code[off+size:])
hexcode = ''.join("{:02x} ".format(ord(b)) for b in code[off:off+size])
insn = {}
insn['args'] = args
insn['argtypes'] = argtypes
insn['hexcode'] = hexcode
insn['offset'] = int(off)
insn['opcode'] = opcode
insn['rawbytes'] = code[int(off):int(off)+size]
insn['size'] = size
insns.append(insn)
off += size
return disas
''' start of 3rd-party code'''
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is [Open Source Virtual Machine].
#
# The Initial Developer of the Original Code is
# Adobe System Incorporated.
# Portions created by the Initial Developer are Copyright (C) 2007
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Adobe AS3 Team
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
from struct import *
from math import floor
NEED_ARGUMENTS = 0x01
NEED_ACTIVATION = 0x02
NEED_REST = 0x04
HAS_OPTIONAL = 0x08
IGNORE_REST = 0x10
NATIVE = 0x20
HAS_ParamNames = 0x80
CONSTANT_Utf8 = 0x01
CONSTANT_Int = 0x03
CONSTANT_UInt = 0x04
CONSTANT_PrivateNs = 0x05
CONSTANT_Double = 0x06
CONSTANT_Qname = 0x07
CONSTANT_Namespace = 0x08
CONSTANT_Multiname = 0x09
CONSTANT_False = 0x0A
CONSTANT_True = 0x0B
CONSTANT_Null = 0x0C
CONSTANT_QnameA = 0x0D
CONSTANT_MultinameA = 0x0E
CONSTANT_RTQname = 0x0F
CONSTANT_RTQnameA = 0x10
CONSTANT_RTQnameL = 0x11
CONSTANT_RTQnameLA = 0x12
CONSTANT_NameL = 0x13
CONSTANT_NameLA = 0x14
CONSTANT_NamespaceSet = 0x15
CONSTANT_PackageNs = 0x16
CONSTANT_PackageInternalNs = 0x17
CONSTANT_ProtectedNs = 0x18
CONSTANT_ExplicitNamespace = 0x19
CONSTANT_StaticProtectedNs = 0x1A
CONSTANT_MultinameL = 0x1B
CONSTANT_MultinameLA = 0x1C
CONSTANT_TypeName = 0x1D
TRAIT_Slot = 0x00
TRAIT_Method = 0x01
TRAIT_Getter = 0x02
TRAIT_Setter = 0x03
TRAIT_Class = 0x04
TRAIT_Const = 0x06
TRAIT_mask = 15
ATTR_final = 0x10
ATTR_override = 0x20
ATTR_metadata = 0x40
CTYPE_VOID = 0
CTYPE_ATOM = 1
CTYPE_BOOLEAN = 2
CTYPE_INT = 3
CTYPE_UINT = 4
CTYPE_DOUBLE = 5
CTYPE_STRING = 6
CTYPE_NAMESPACE = 7
CTYPE_OBJECT = 8
MPL_HEADER = "/* ***** BEGIN LICENSE BLOCK *****\n" \
" * Version: MPL 1.1/GPL 2.0/LGPL 2.1\n" \
" *\n" \
" * The contents of this file are subject to the Mozilla Public License Version\n" \
" * 1.1 (the \"License\"); you may not use this file except in compliance with\n" \
" * the License. You may obtain a copy of the License at\n" \
" * http://www.mozilla.org/MPL/\n" \
" *\n" \
" * Software distributed under the License is distributed on an \"AS IS\" basis,\n" \
" * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n" \
" * for the specific language governing rights and limitations under the\n" \
" * License.\n" \
" *\n" \
" * The Original Code is [Open Source Virtual Machine].\n" \
" *\n" \
" * The Initial Developer of the Original Code is\n" \
" * Adobe System Incorporated.\n" \
" * Portions created by the Initial Developer are Copyright (C) 2008\n" \
" * the Initial Developer. All Rights Reserved.\n" \
" *\n" \
" * Contributor(s):\n" \
" * Adobe AS3 Team\n" \
" *\n" \
" * Alternatively, the contents of this file may be used under the terms of\n" \
" * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n" \
" * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n" \
" * in which case the provisions of the GPL or the LGPL are applicable instead\n" \
" * of those above. If you wish to allow use of your version of this file only\n" \
" * under the terms of either the GPL or the LGPL, and not to allow others to\n" \
" * use your version of this file under the terms of the MPL, indicate your\n" \
" * decision by deleting the provisions above and replace them with the notice\n" \
" * and other provisions required by the GPL or the LGPL. If you do not delete\n" \
" * the provisions above, a recipient may use your version of this file under\n" \
" * the terms of any one of the MPL, the GPL or the LGPL.\n" \
" *\n" \
" * ***** END LICENSE BLOCK ***** */"
# Python 2.5 and earlier didn't reliably handle float("nan") and friends uniformly
# across all platforms. This is a workaround that appears to be more reliable.
# if/when we require Python 2.6 or later we can use a less hack-prone approach
kPosInf = 1e300000
kNegInf = -1e300000
kNaN = kPosInf / kPosInf
def is_nan(val):
strValLower = str(val).lower()
return strValLower == "nan"
def is_pos_inf(val):
# [-]1.#INF on Windows in Python 2.5.2!
strValLower = str(val).lower()
return strValLower.endswith("inf") and not strValLower.startswith("-")
def is_neg_inf(val):
# [-]1.#INF on Windows in Python 2.5.2!
strValLower = str(val).lower()
return strValLower.endswith("inf") and strValLower.startswith("-")
class Error(Exception):
nm = ""
def __init__(self, n):
self.nm = n
def __str__(self):
return self.nm
TMAP = {
CTYPE_OBJECT: ("o", "AvmObject"),
CTYPE_ATOM: ("a", "AvmBox"),
CTYPE_VOID: ("v", "void"),
CTYPE_BOOLEAN: ("b", "AvmBool32"),
CTYPE_INT: ("i", "int32_t"),
CTYPE_UINT: ("u", "uint32_t"),
CTYPE_DOUBLE: ("d", "double"),
CTYPE_STRING: ("s", "AvmString"),
CTYPE_NAMESPACE: ("n", "AvmNamespace")
};
def uint(i):
return int(i) & 0xffffffff
def sigchar_from_enum(ct, allowObject):
if ct == CTYPE_OBJECT and not allowObject:
ct = CTYPE_ATOM
return TMAP[ct][0]
def sigchar_from_traits(t, allowObject):
return sigchar_from_enum(t.ctype, allowObject)
def ctype_from_enum(ct, allowObject):
if ct == CTYPE_OBJECT and not allowObject:
ct = CTYPE_ATOM
return TMAP[ct][1]
def ctype_from_traits(t, allowObject):
return ctype_from_enum(t.ctype, allowObject)
def to_cname(nm):
nm = str(nm)
nm = nm.replace("+", "_");
nm = nm.replace("-", "_");
nm = nm.replace("?", "_");
nm = nm.replace("!", "_");
nm = nm.replace("<", "_");
nm = nm.replace(">", "_");
nm = nm.replace("=", "_");
nm = nm.replace("(", "_");
nm = nm.replace(")", "_");
nm = nm.replace("\"", "_");
nm = nm.replace("'", "_");
nm = nm.replace("*", "_");
nm = nm.replace(" ", "_");
nm = nm.replace(".", "_");
nm = nm.replace("$", "_");
nm = nm.replace("::", "_");
nm = nm.replace(":", "_");
nm = nm.replace("/", "_");
return nm
def ns_prefix(ns, iscls):
if not ns.isPublic() and not ns.isInternal():
if ns.isPrivate() and not iscls:
return "private_";
if ns.isProtected():
return "protected_";
if ns.srcname != None:
return to_cname(str(ns.srcname)) + "_"
p = to_cname(ns.uri);
if len(p) > 0:
p += "_"
return p
class Namespace:
uri = ""
kind = 0
srcname = None
def __init__(self, uri, kind):
self.uri = uri
self.kind = kind
def __str__(self):
return self.uri
def isPublic(self):
return self.kind in [CONSTANT_Namespace, CONSTANT_PackageNs] and self.uri == ""
def isInternal(self):
return self.kind in [CONSTANT_PackageInternalNs]
def isPrivate(self):
return self.kind in [CONSTANT_PrivateNs]
def isProtected(self):
return self.kind in [CONSTANT_ProtectedNs, CONSTANT_StaticProtectedNs]
class QName:
ns = None
name = ""
def __init__(self, ns, name):
self.ns = ns
self.name = name
def __str__(self):
if str(self.ns) == "":
return self.name
if self.ns == None:
return "*::" + self.name
return str(self.ns) + "::" + self.name
class Multiname:
nsset = None
name = ""
def __init__(self, nsset, name):
self.nsset = nsset
self.name = name
def __str__(self):
nsStrings = map(lambda ns: u'"' + ns.decode("utf8") + u'"', self.nsset)
stringForNSSet = u'[' + u', '.join(nsStrings) + u']'
return stringForNSSet + u'::' + unicode(self.name.decode("utf8"))
def stripVersion(ns):
# version markers are 3 bytes beginning with 0xE0 or greater
if len(ns.uri) < 3:
return ns
if ns.uri[len(ns.uri)-3] > chr(0xE0):
ns.uri = ns.uri[0:len(ns.uri)-3]
return ns
def isVersionedNamespace(ns):
# version markers are 3 bytes beginning with 0xE0 or greater
if len(ns.uri) < 3:
return False
if ns.uri[len(ns.uri)-3] > chr(0xE0):
ns.uri = ns.uri[0:len(ns.uri)-3]
return True
return False
def isVersionedName(name):
if isinstance(name, QName):
return isVersionedNamespace(name.ns)
for ns in name.nsset:
if isVersionedNamespace(ns):
return True
return False
class TypeName:
name = ""
types = None
def __init__(self, name, types):
self.name = name
self.types = types
def __str__(self):
# @todo horrible special-casing, improve someday
s = str(self.name)
t = str(self.types[0])
if t == "int":
s += "$int"
elif t == "uint":
s += "$uint"
elif t == "Number":
s += "$double"
else:
s += "$object"
return s
class MetaData:
name = ""
attrs = {}
def __init__(self, name):
self.name = name
self.attrs = {}
class MemberInfo:
id = -1
kind = -1
name = ""
metadata = None
class MethodInfo(MemberInfo):
flags = 0
debugName = ""
paramTypes = None
paramNames = None
optional_count = 0
optionalValues = None
returnType = None
local_count = 0
max_scope = 0
max_stack = 0
code_length = 0
code = None
activation = None
native_id_name = None
native_method_name = None
final = False
override = False
receiver = None
unbox_this = -1 # -1 == undetermined, 0 = no, 1 = yes
def isNative(self):
return (self.flags & NATIVE) != 0
def needRest(self):
return (self.flags & NEED_REST) != 0
def hasOptional(self):
return (self.flags & HAS_OPTIONAL) != 0
def assign_names(self, traits, prefix):
self.receiver = traits
if not self.isNative():
return
if self == traits.init:
raise Error("ctors cannot be native")
assert(isinstance(self.name, QName))
self.native_id_name = prefix + ns_prefix(self.name.ns, False) + self.name.name
self.native_method_name = self.name.name
if self.kind == TRAIT_Getter:
self.native_id_name += "_get"
self.native_method_name = "get_" + self.native_method_name
elif self.kind == TRAIT_Setter:
self.native_id_name += "_set"
self.native_method_name = "set_" + self.native_method_name
if self.name.ns.srcname != None:
self.native_method_name = str(self.name.ns.srcname) + "_" + self.native_method_name
# if we are an override, prepend the classname to the C method name.
# (native method implementations must not be virtual, and some compilers
# will be unhappy if a subclass overrides a method with the same name and signature
# without it being virtual.) Note that we really only need to do this if the ancestor
# implementation is native, rather than pure AS3, but we currently do it regardless.
if self.override:
self.native_method_name = traits.name.name + "_" + self.native_method_name
self.native_method_name = to_cname(self.native_method_name)
class SlotInfo(MemberInfo):
type = ""