Merge swf-rs into ruffle repo

git-subtree-dir: swf
git-subtree-mainline: 2740f3ccc1
git-subtree-split: 1b04015326
This commit is contained in:
Mike Welsh 2019-10-02 17:25:02 -07:00
commit 0de44d61b3
153 changed files with 14246 additions and 0 deletions

4
swf/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
target
Cargo.lock
rustfmt.toml
*.bk

18
swf/.travis.yml Normal file
View File

@ -0,0 +1,18 @@
language: rust
rust:
- stable
- beta
- nightly
cache: cargo
matrix:
allow_failures:
- rust: nightly
before_script:
- export PATH="$PATH:$HOME/.cargo/bin"
- (test $TRAVIS_RUST_VERSION != "nightly" || cargo install rustfmt-nightly || true)
script:
- (test $TRAVIS_RUST_VERSION != "nightly" || cargo fmt -- --write-mode=diff)
- (test $TRAVIS_RUST_VERSION != "nightly" || cargo build --features "clippy")
- (test $TRAVIS_RUST_VERSION != "nightly" || cargo test --features "clippy")
- (test $TRAVIS_RUST_VERSION == "nightly" || cargo build)
- (test $TRAVIS_RUST_VERSION == "nightly" || cargo test)

22
swf/Cargo.toml Normal file
View File

@ -0,0 +1,22 @@
[package]
name = "swf"
version = "0.1.2"
edition = "2018"
authors = ["Mike Welsh"]
repository = "https://github.com/ruffle-rs/swf-rs.git"
homepage = "https://github.com/ruffle-rs/swf-rs.git"
license = "MIT OR Apache-2.0"
readme = "README.md"
description = "Read and write the Adobe Flash SWF file format."
[dependencies]
byteorder = "1.0"
num-derive = "0.2"
num-traits = "0.2"
libflate = {version = "0.1", optional = true}
flate2 = {version = "1.0", optional = true}
xz2 = {version = "0.1.5", optional = true}
[features]
default = ["libflate"]
lzma-support = ["xz2"]

201
swf/LICENSE-APACHE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
swf/LICENSE-MIT Normal file
View File

@ -0,0 +1,25 @@
Copyright (c) 2010 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

68
swf/README.md Normal file
View File

@ -0,0 +1,68 @@
# swf
[![crates.io](https://img.shields.io/crates/v/swf.svg)](https://crates.io/crates/swf)
[![docs.rs](https://docs.rs/swf/badge.svg)](https://docs.rs/swf)
[![TravisCI](https://travis-ci.org/Herschel/swf-rs.svg?branch=master)](https://travis-ci.org/Herschel/swf-rs)
A Rust library for reading and writing the Adobe Flash SWF file format.
```toml
# Cargo.toml
[dependencies]
swf = "0.1"
```
## Reading
```rust
use std::io::BufReader;
use std::fs::File;
let file = File::open("file.swf").unwrap();
let reader = BufReader::new(file);
let swf = swf::read_swf(reader).unwrap();
println!("The SWF has {} frames", swf.header.num_frames);
```
Try `cargo run --example reading` in this repository to run this example.
## Writing
```rust,no_run
use swf::*;
let swf = Swf {
header: Header {
version: 6,
compression: Compression::Zlib,
stage_size: Rectangle {
x_min: Twips::from_pixels(0.0), x_max: Twips::from_pixels(400.0),
y_min: Twips::from_pixels(0.0), y_max: Twips::from_pixels(400.0)
},
frame_rate: 60.0,
num_frames: 1,
},
tags: vec![
Tag::SetBackgroundColor(Color { r: 255, g: 0, b: 0, a: 255 }),
Tag::ShowFrame
]
};
let file = std::fs::File::create("file.swf").unwrap();
let writer = std::io::BufWriter::new(file);
swf::write_swf(&swf, writer).unwrap();
```
Try `cargo run --example writing` in this repository to run this example.
## License
Licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.

10
swf/examples/reading.rs Normal file
View File

@ -0,0 +1,10 @@
use std::io::BufReader;
use std::fs::File;
fn main() {
let file = File::open("tests/swfs/SimpleRedBackground.swf").unwrap();
let reader = BufReader::new(file);
let swf = swf::read_swf(reader).unwrap();
println!("The SWF has {} frame(s).", swf.header.num_frames);
println!("The SWF has {} tag(s).", swf.tags.len());
}

23
swf/examples/writing.rs Normal file
View File

@ -0,0 +1,23 @@
use swf::*;
fn main() {
let swf = Swf {
header: Header {
version: 6,
compression: Compression::Zlib,
stage_size: Rectangle {
x_min: Twips::from_pixels(0.0), x_max: Twips::from_pixels(400.0),
y_min: Twips::from_pixels(0.0), y_max: Twips::from_pixels(400.0)
},
frame_rate: 60.0,
num_frames: 1,
},
tags: vec![
Tag::SetBackgroundColor(Color { r: 255, g: 0, b: 0, a: 255 }),
Tag::ShowFrame
]
};
let file = std::fs::File::create("tests/swfs/SimpleRedBackground.swf").unwrap();
let writer = std::io::BufWriter::new(file);
swf::write_swf(&swf, writer).unwrap();
}

4
swf/src/avm1.rs Normal file
View File

@ -0,0 +1,4 @@
mod opcode;
pub mod read;
pub mod types;
pub mod write;

120
swf/src/avm1/opcode.rs Normal file
View File

@ -0,0 +1,120 @@
#![allow(clippy::useless_attribute)]
#[allow(dead_code)]
#[derive(Debug, PartialEq, Clone, Copy, FromPrimitive)]
pub enum OpCode {
End = 0x00,
NextFrame = 0x04,
PreviousFrame = 0x05,
Play = 0x06,
Stop = 0x07,
ToggleQuality = 0x08,
StopSounds = 0x09,
Add = 0x0A,
Subtract = 0x0B,
Multiply = 0x0C,
Divide = 0x0D,
Equals = 0x0E,
Less = 0x0F,
And = 0x10,
Or = 0x11,
Not = 0x12,
StringEquals = 0x13,
StringLength = 0x14,
StringExtract = 0x15,
Pop = 0x17,
ToInteger = 0x18,
GetVariable = 0x1C,
SetVariable = 0x1D,
SetTarget2 = 0x20,
StringAdd = 0x21,
GetProperty = 0x22,
SetProperty = 0x23,
CloneSprite = 0x24,
RemoveSprite = 0x25,
Trace = 0x26,
StartDrag = 0x27,
EndDrag = 0x28,
StringLess = 0x29,
Throw = 0x2A,
CastOp = 0x2B,
ImplementsOp = 0x2C,
RandomNumber = 0x30,
MBStringLength = 0x31,
CharToAscii = 0x32,
AsciiToChar = 0x33,
GetTime = 0x34,
MBStringExtract = 0x35,
MBCharToAscii = 0x36,
MBAsciiToChar = 0x37,
Delete = 0x3A,
Delete2 = 0x3B,
DefineLocal = 0x3C,
CallFunction = 0x3D,
Return = 0x3E,
Modulo = 0x3F,
NewObject = 0x40,
DefineLocal2 = 0x41,
InitArray = 0x42,
InitObject = 0x43,
TypeOf = 0x44,
TargetPath = 0x45,
Enumerate = 0x46,
Add2 = 0x47,
Less2 = 0x48,
Equals2 = 0x49,
ToNumber = 0x4A,
ToString = 0x4B,
PushDuplicate = 0x4C,
StackSwap = 0x4D,
GetMember = 0x4E,
SetMember = 0x4F,
Increment = 0x50,
Decrement = 0x51,
CallMethod = 0x52,
NewMethod = 0x53,
InstanceOf = 0x54,
Enumerate2 = 0x55,
BitAnd = 0x60,
BitOr = 0x61,
BitXor = 0x62,
BitLShift = 0x63,
BitRShift = 0x64,
BitURShift = 0x65,
StrictEquals = 0x66,
Greater = 0x67,
StringGreater = 0x68,
Extends = 0x69,
GotoFrame = 0x81,
GetUrl = 0x83,
StoreRegister = 0x87,
ConstantPool = 0x88,
WaitForFrame = 0x8A,
SetTarget = 0x8B,
GotoLabel = 0x8C,
WaitForFrame2 = 0x8D,
DefineFunction2 = 0x8E,
Try = 0x8F,
With = 0x94,
Push = 0x96,
Jump = 0x99,
GetUrl2 = 0x9A,
DefineFunction = 0x9B,
If = 0x9D,
Call = 0x9E,
GotoFrame2 = 0x9F,
}

415
swf/src/avm1/read.rs Normal file
View File

@ -0,0 +1,415 @@
#![allow(clippy::unreadable_literal)]
use crate::avm1::opcode::OpCode;
use crate::avm1::types::*;
use crate::read::SwfRead;
use std::io::{Cursor, Error, ErrorKind, Result};
#[allow(dead_code)]
pub struct Reader<'a> {
inner: Cursor<&'a [u8]>,
version: u8,
}
impl<'a> SwfRead<Cursor<&'a [u8]>> for Reader<'a> {
fn get_inner(&mut self) -> &mut Cursor<&'a [u8]> {
&mut self.inner
}
}
impl<'a> Reader<'a> {
pub fn new(input: &'a [u8], version: u8) -> Self {
Self {
inner: Cursor::new(input),
version,
}
}
#[inline]
pub fn pos(&self) -> usize {
self.inner.position() as usize
}
#[inline]
pub fn seek(&mut self, relative_offset: isize) {
let new_pos = self.inner.position() as i64 + relative_offset as i64;
self.inner.set_position(new_pos as u64);
}
#[inline]
fn read_slice(&mut self, len: usize) -> &'a [u8] {
let pos = self.pos();
let slice = &self.inner.get_ref()[pos..pos + len];
self.inner.set_position(pos as u64 + len as u64);
slice
}
#[inline]
fn read_c_string(&mut self) -> Result<&'a str> {
// Find zero terminator.
let str_slice = {
let start_pos = self.pos();
loop {
let byte = self.read_u8()?;
if byte == 0 {
break;
}
}
&self.inner.get_ref()[start_pos..self.pos() - 1]
};
// TODO: What does Flash do on invalid UTF8?
// Do we silently let it pass?
// TODO: Verify ANSI for SWF 5 and earlier.
std::str::from_utf8(str_slice)
.map_err(|_| Error::new(ErrorKind::InvalidData, "Invalid string data"))
}
#[inline]
pub fn read_action(&mut self) -> Result<Option<Action<'a>>> {
use num_traits::FromPrimitive;
let (opcode, length) = self.read_opcode_and_length()?;
let action = if let Some(op) = OpCode::from_u8(opcode) {
match op {
OpCode::End => return Ok(None),
OpCode::Add => Action::Add,
OpCode::Add2 => Action::Add2,
OpCode::And => Action::And,
OpCode::AsciiToChar => Action::AsciiToChar,
OpCode::BitAnd => Action::BitAnd,
OpCode::BitLShift => Action::BitLShift,
OpCode::BitOr => Action::BitOr,
OpCode::BitRShift => Action::BitRShift,
OpCode::BitURShift => Action::BitURShift,
OpCode::BitXor => Action::BitXor,
OpCode::Call => Action::Call,
OpCode::CallFunction => Action::CallFunction,
OpCode::CallMethod => Action::CallMethod,
OpCode::CastOp => Action::CastOp,
OpCode::CharToAscii => Action::CharToAscii,
OpCode::CloneSprite => Action::CloneSprite,
OpCode::ConstantPool => {
let mut constants = vec![];
for _ in 0..self.read_u16()? {
constants.push(self.read_c_string()?);
}
Action::ConstantPool(constants)
}
OpCode::Decrement => Action::Decrement,
OpCode::DefineFunction => self.read_define_function()?,
OpCode::DefineFunction2 => self.read_define_function_2()?,
OpCode::DefineLocal => Action::DefineLocal,
OpCode::DefineLocal2 => Action::DefineLocal2,
OpCode::Delete => Action::Delete,
OpCode::Delete2 => Action::Delete2,
OpCode::Divide => Action::Divide,
OpCode::EndDrag => Action::EndDrag,
OpCode::Enumerate => Action::Enumerate,
OpCode::Enumerate2 => Action::Enumerate2,
OpCode::Equals => Action::Equals,
OpCode::Equals2 => Action::Equals2,
OpCode::Extends => Action::Extends,
OpCode::GetMember => Action::GetMember,
OpCode::GetProperty => Action::GetProperty,
OpCode::GetTime => Action::GetTime,
OpCode::GetUrl => Action::GetUrl {
url: self.read_c_string()?,
target: self.read_c_string()?,
},
OpCode::GetUrl2 => {
let flags = self.read_u8()?;
Action::GetUrl2 {
is_target_sprite: flags & 0b10 != 0,
is_load_vars: flags & 0b1 != 0,
send_vars_method: match flags >> 6 {
0 => SendVarsMethod::None,
1 => SendVarsMethod::Get,
2 => SendVarsMethod::Post,
_ => {
return Err(Error::new(
ErrorKind::InvalidData,
"Invalid HTTP method in ActionGetUrl2",
))
}
},
}
}
OpCode::GetVariable => Action::GetVariable,
OpCode::GotoFrame => {
let frame = self.read_u16()?;
Action::GotoFrame(frame)
}
OpCode::GotoFrame2 => {
let flags = self.read_u8()?;
Action::GotoFrame2 {
set_playing: flags & 0b1 != 0,
scene_offset: if flags & 0b10 != 0 {
self.read_u16()?
} else {
0
},
}
}
OpCode::GotoLabel => Action::GotoLabel(self.read_c_string()?),
OpCode::Greater => Action::Greater,
OpCode::If => Action::If {
offset: self.read_i16()?,
},
OpCode::ImplementsOp => Action::ImplementsOp,
OpCode::Increment => Action::Increment,
OpCode::InitArray => Action::InitArray,
OpCode::InitObject => Action::InitObject,
OpCode::InstanceOf => Action::InstanceOf,
OpCode::Jump => Action::Jump {
offset: self.read_i16()?,
},
OpCode::Less => Action::Less,
OpCode::Less2 => Action::Less2,
OpCode::MBAsciiToChar => Action::MBAsciiToChar,
OpCode::MBCharToAscii => Action::MBCharToAscii,
OpCode::MBStringExtract => Action::MBStringExtract,
OpCode::MBStringLength => Action::MBStringLength,
OpCode::Modulo => Action::Modulo,
OpCode::Multiply => Action::Multiply,
OpCode::NewMethod => Action::NewMethod,
OpCode::NewObject => Action::NewObject,
OpCode::NextFrame => Action::NextFrame,
OpCode::Not => Action::Not,
OpCode::Or => Action::Or,
OpCode::Play => Action::Play,
OpCode::Pop => Action::Pop,
OpCode::PreviousFrame => Action::PreviousFrame,
// TODO: Verify correct version for complex types.
OpCode::Push => self.read_push(length)?,
OpCode::PushDuplicate => Action::PushDuplicate,
OpCode::RandomNumber => Action::RandomNumber,
OpCode::RemoveSprite => Action::RemoveSprite,
OpCode::Return => Action::Return,
OpCode::SetMember => Action::SetMember,
OpCode::SetProperty => Action::SetProperty,
OpCode::SetTarget => Action::SetTarget(self.read_c_string()?),
OpCode::SetTarget2 => Action::SetTarget2,
OpCode::SetVariable => Action::SetVariable,
OpCode::StackSwap => Action::StackSwap,
OpCode::StartDrag => Action::StartDrag,
OpCode::Stop => Action::Stop,
OpCode::StopSounds => Action::StopSounds,
OpCode::StoreRegister => Action::StoreRegister(self.read_u8()?),
OpCode::StrictEquals => Action::StrictEquals,
OpCode::StringAdd => Action::StringAdd,
OpCode::StringEquals => Action::StringEquals,
OpCode::StringExtract => Action::StringExtract,
OpCode::StringGreater => Action::StringGreater,
OpCode::StringLength => Action::StringLength,
OpCode::StringLess => Action::StringLess,
OpCode::Subtract => Action::Subtract,
OpCode::TargetPath => Action::TargetPath,
OpCode::Throw => Action::Throw,
OpCode::ToggleQuality => Action::ToggleQuality,
OpCode::ToInteger => Action::ToInteger,
OpCode::ToNumber => Action::ToNumber,
OpCode::ToString => Action::ToString,
OpCode::Trace => Action::Trace,
OpCode::Try => self.read_try()?,
OpCode::TypeOf => Action::TypeOf,
OpCode::WaitForFrame => Action::WaitForFrame {
frame: self.read_u16()?,
num_actions_to_skip: self.read_u8()?,
},
OpCode::With => {
let code_length = self.read_u16()?;
Action::With {
actions: self.read_slice(code_length.into()),
}
}
OpCode::WaitForFrame2 => Action::WaitForFrame2 {
num_actions_to_skip: self.read_u8()?,
},
}
} else {
self.read_unknown_action(opcode, length)?
};
Ok(Some(action))
}
pub fn read_opcode_and_length(&mut self) -> Result<(u8, usize)> {
let opcode = self.read_u8()?;
let length = if opcode >= 0x80 {
self.read_u16()? as usize
} else {
0
};
Ok((opcode, length))
}
fn read_unknown_action(&mut self, opcode: u8, length: usize) -> Result<Action<'a>> {
Ok(Action::Unknown {
opcode,
data: self.read_slice(length),
})
}
fn read_push(&mut self, length: usize) -> Result<Action<'a>> {
let end_pos = self.pos() + length;
let mut values = Vec::with_capacity(end_pos);
while self.pos() < end_pos {
values.push(self.read_push_value()?);
}
Ok(Action::Push(values))
}
fn read_push_value(&mut self) -> Result<Value<'a>> {
let value = match self.read_u8()? {
0 => Value::Str(self.read_c_string()?),
1 => Value::Float(self.read_f32()?),
2 => Value::Null,
3 => Value::Undefined,
4 => Value::Register(self.read_u8()?),
5 => Value::Bool(self.read_u8()? != 0),
6 => Value::Double(self.read_f64()?),
7 => Value::Int(self.read_i32()?),
8 => Value::ConstantPool(self.read_u8()?.into()),
9 => Value::ConstantPool(self.read_u16()?),
_ => {
return Err(Error::new(
ErrorKind::InvalidData,
"Invalid value type in ActionPush",
))
}
};
Ok(value)
}
fn read_define_function(&mut self) -> Result<Action<'a>> {
let name = self.read_c_string()?;
let num_params = self.read_u16()?;
let mut params = Vec::with_capacity(num_params as usize);
for _ in 0..num_params {
params.push(self.read_c_string()?);
}
// code_length isn't included in the DefineFunction's action length.
let code_length = self.read_u16()?;
Ok(Action::DefineFunction {
name,
params,
actions: self.read_slice(code_length.into()),
})
}
fn read_define_function_2(&mut self) -> Result<Action<'a>> {
let name = self.read_c_string()?;
let num_params = self.read_u16()?;
let num_registers = self.read_u8()?; // Number of registers
let flags = self.read_u16()?;
let mut params = Vec::with_capacity(num_params as usize + num_registers as usize);
for _ in 0..num_params {
let register = self.read_u8()?;
params.push(FunctionParam {
name: self.read_c_string()?,
register_index: if register == 0 { None } else { Some(register) },
});
}
// code_length isn't included in the DefineFunction's length.
let code_length = self.read_u16()?;
Ok(Action::DefineFunction2(Function {
name,
params,
preload_global: flags & 0b1_00000000 != 0,
preload_parent: flags & 0b10000000 != 0,
preload_root: flags & 0b1000000 != 0,
suppress_super: flags & 0b100000 != 0,
preload_super: flags & 0b10000 != 0,
suppress_arguments: flags & 0b1000 != 0,
preload_arguments: flags & 0b100 != 0,
suppress_this: flags & 0b10 != 0,
preload_this: flags & 0b1 != 0,
actions: self.read_slice(code_length.into()),
}))
}
fn read_try(&mut self) -> Result<Action<'a>> {
let flags = self.read_u8()?;
let try_length = self.read_u16()?;
let catch_length = self.read_u16()?;
let finally_length = self.read_u16()?;
let catch_var = if flags & 0b100 != 0 {
CatchVar::Var(self.read_c_string()?)
} else {
CatchVar::Register(self.read_u8()?)
};
let try_actions = self.read_slice(try_length.into());
let catch_actions = self.read_slice(catch_length.into());
let finally_actions = self.read_slice(finally_length.into());
Ok(Action::Try(TryBlock {
try_actions,
catch: if flags & 0b1 != 0 {
Some((catch_var, catch_actions))
} else {
None
},
finally: if flags & 0b10 != 0 {
Some(finally_actions)
} else {
None
},
}))
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::test_data;
#[test]
fn read_action() {
for (swf_version, expected_action, action_bytes) in test_data::avm1_tests() {
let mut reader = Reader::new(&action_bytes[..], swf_version);
let parsed_action = reader.read_action().unwrap().unwrap();
if parsed_action != expected_action {
// Failed, result doesn't match.
panic!(
"Incorrectly parsed action.\nRead:\n{:?}\n\nExpected:\n{:?}",
parsed_action, expected_action
);
}
}
}
#[test]
fn read_define_function() {
// Ensure we read a function properly along with the function data.
let action_bytes = vec![
0x9b, 0x08, 0x00, 0x66, 0x6f, 0x6f, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x96, 0x06, 0x00,
0x00, 0x74, 0x65, 0x73, 0x74, 0x00, 0x26, 0x00,
];
let mut reader = Reader::new(&action_bytes[..], 5);
let action = reader.read_action().unwrap().unwrap();
assert_eq!(
action,
Action::DefineFunction {
name: "foo",
params: vec![],
actions: &[0x96, 0x06, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x00, 0x26],
}
);
if let Action::DefineFunction { actions, .. } = action {
let mut reader = Reader::new(actions, 5);
let action = reader.read_action().unwrap().unwrap();
assert_eq!(action, Action::Push(vec![Value::Str("test")]));
}
}
#[test]
fn read_push_to_end_of_action() {
// ActionPush doesn't provide an explicit # of values, but instead reads values
// until the end of the action. Ensure we don't read extra values.
let action_bytes = [0x96, 2, 0, 2, 3, 3]; // Extra 3 at the end shouldn't be read.
let mut reader = Reader::new(&action_bytes[..], 5);
let action = reader.read_action().unwrap().unwrap();
assert_eq!(action, Action::Push(vec![Value::Null, Value::Undefined]));
}
}

186
swf/src/avm1/types.rs Normal file
View File

@ -0,0 +1,186 @@
#[derive(Clone, Debug, PartialEq)]
pub enum Action<'a> {
Add,
Add2,
And,
AsciiToChar,
BitAnd,
BitLShift,
BitOr,
BitRShift,
BitURShift,
BitXor,
Call,
CallFunction,
CallMethod,
CastOp,
CharToAscii,
CloneSprite,
ConstantPool(Vec<&'a str>),
Decrement,
DefineFunction {
name: &'a str,
params: Vec<&'a str>,
actions: &'a [u8],
},
DefineFunction2(Function<'a>),
DefineLocal,
DefineLocal2,
Delete,
Delete2,
Divide,
EndDrag,
Enumerate,
Enumerate2,
Equals,
Equals2,
Extends,
GetMember,
GetProperty,
GetTime,
GetUrl {
url: &'a str,
target: &'a str,
},
GetUrl2 {
send_vars_method: SendVarsMethod,
is_target_sprite: bool,
is_load_vars: bool,
},
GetVariable,
GotoFrame(u16),
GotoFrame2 {
set_playing: bool,
scene_offset: u16,
},
GotoLabel(&'a str),
Greater,
If {
offset: i16,
},
ImplementsOp,
Increment,
InitArray,
InitObject,
InstanceOf,
Jump {
offset: i16,
},
Less,
Less2,
MBAsciiToChar,
MBCharToAscii,
MBStringExtract,
MBStringLength,
Modulo,
Multiply,
NewMethod,
NewObject,
NextFrame,
Not,
Or,
Play,
Pop,
PreviousFrame,
Push(Vec<Value<'a>>),
PushDuplicate,
RandomNumber,
RemoveSprite,
Return,
SetMember,
SetProperty,
SetTarget(&'a str),
SetTarget2,
SetVariable,
StackSwap,
StartDrag,
Stop,
StopSounds,
StoreRegister(u8),
StrictEquals,
StringAdd,
StringEquals,
StringExtract,
StringGreater,
StringLength,
StringLess,
Subtract,
TargetPath,
Throw,
ToInteger,
ToNumber,
ToString,
ToggleQuality,
Trace,
Try(TryBlock<'a>),
TypeOf,
WaitForFrame {
frame: u16,
num_actions_to_skip: u8,
},
WaitForFrame2 {
num_actions_to_skip: u8,
},
With {
actions: &'a [u8],
},
Unknown {
opcode: u8,
data: &'a [u8],
},
}
#[derive(Clone, Debug, PartialEq)]
pub enum Value<'a> {
Undefined,
Null,
Bool(bool),
Int(i32),
Float(f32),
Double(f64),
Str(&'a str),
Register(u8),
ConstantPool(u16),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SendVarsMethod {
None,
Get,
Post,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Function<'a> {
pub name: &'a str,
pub params: Vec<FunctionParam<'a>>,
pub preload_parent: bool,
pub preload_root: bool,
pub suppress_super: bool,
pub preload_super: bool,
pub suppress_arguments: bool,
pub preload_arguments: bool,
pub suppress_this: bool,
pub preload_this: bool,
pub preload_global: bool,
pub actions: &'a [u8],
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FunctionParam<'a> {
pub name: &'a str,
pub register_index: Option<u8>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TryBlock<'a> {
pub try_actions: &'a [u8],
pub catch: Option<(CatchVar<'a>, &'a [u8])>,
pub finally: Option<&'a [u8]>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CatchVar<'a> {
Var(&'a str),
Register(u8),
}

423
swf/src/avm1/write.rs Normal file
View File

@ -0,0 +1,423 @@
#![allow(clippy::cognitive_complexity, clippy::unreadable_literal)]
use crate::avm1::opcode::OpCode;
use crate::avm1::types::*;
use crate::write::SwfWrite;
use std::io::{Result, Write};
#[allow(dead_code)]
pub struct Writer<W: Write> {
inner: W,
version: u8,
}
impl<W: Write> SwfWrite<W> for Writer<W> {
fn get_inner(&mut self) -> &mut W {
&mut self.inner
}
}
impl<W: Write> Writer<W> {
pub fn new(inner: W, version: u8) -> Writer<W> {
Writer { inner, version }
}
pub fn write_action(&mut self, action: &Action) -> Result<()> {
match *action {
Action::Add => self.write_action_header(OpCode::Add, 0)?,
Action::Add2 => self.write_action_header(OpCode::Add2, 0)?,
Action::And => self.write_action_header(OpCode::And, 0)?,
Action::AsciiToChar => self.write_action_header(OpCode::AsciiToChar, 0)?,
Action::BitAnd => self.write_action_header(OpCode::BitAnd, 0)?,
Action::BitLShift => self.write_action_header(OpCode::BitLShift, 0)?,
Action::BitOr => self.write_action_header(OpCode::BitOr, 0)?,
Action::BitRShift => self.write_action_header(OpCode::BitRShift, 0)?,
Action::BitURShift => self.write_action_header(OpCode::BitURShift, 0)?,
Action::BitXor => self.write_action_header(OpCode::BitXor, 0)?,
Action::Call => self.write_action_header(OpCode::Call, 0)?,
Action::CallFunction => self.write_action_header(OpCode::CallFunction, 0)?,
Action::CallMethod => self.write_action_header(OpCode::CallMethod, 0)?,
Action::CastOp => self.write_action_header(OpCode::CastOp, 0)?,
Action::CharToAscii => self.write_action_header(OpCode::CharToAscii, 0)?,
Action::CloneSprite => self.write_action_header(OpCode::CloneSprite, 0)?,
Action::ConstantPool(ref constants) => {
let len = 2 + constants.iter().map(|c| c.len() + 1).sum::<usize>();
self.write_action_header(OpCode::ConstantPool, len)?;
self.write_u16(constants.len() as u16)?;
for constant in constants {
self.write_c_string(constant)?;
}
}
Action::Decrement => self.write_action_header(OpCode::Decrement, 0)?,
Action::DefineFunction {
ref name,
ref params,
ref actions,
} => {
// 1 zero byte for string name, 1 zero byte per param, 2 bytes for # of params,
// 2 bytes for code length
let len = name.len() + 1 + 2 + params.iter().map(|p| p.len() + 1).sum::<usize>() + 2;
self.write_action_header(OpCode::DefineFunction, len)?;
self.write_c_string(name)?;
self.write_u16(params.len() as u16)?;
for param in params {
self.write_c_string(param)?;
}
self.write_u16(actions.len() as u16)?;
self.inner.write_all(actions)?;
}
Action::DefineFunction2(ref function) => {
let len = function.name.len()
+ 1
+ 3
+ function
.params
.iter()
.map(|p| p.name.len() + 2)
.sum::<usize>()
+ 4;
let num_registers = function
.params
.iter()
.map(|p| if p.register_index.is_none() { 1 } else { 0 })
.sum();
self.write_action_header(OpCode::DefineFunction2, len)?;
self.write_c_string(&function.name)?;
self.write_u16(function.params.len() as u16)?;
self.write_u8(num_registers)?;
let flags = if function.preload_global {
0b1_00000000
} else {
0
} | if function.preload_parent {
0b10000000
} else {
0
} | if function.preload_root { 0b1000000 } else { 0 }
| if function.suppress_super { 0b100000 } else { 0 }
| if function.preload_super { 0b10000 } else { 0 }
| if function.suppress_arguments {
0b1000
} else {
0
}
| if function.preload_arguments { 0b100 } else { 0 }
| if function.suppress_this { 0b10 } else { 0 }
| if function.preload_this { 0b1 } else { 0 };
self.write_u16(flags)?;
for param in &function.params {
self.write_u8(if let Some(n) = param.register_index {
n
} else {
0
})?;
self.write_c_string(&param.name)?;
}
self.write_u16(function.actions.len() as u16)?;
self.inner.write_all(&function.actions)?;
}
Action::DefineLocal => self.write_action_header(OpCode::DefineLocal, 0)?,
Action::DefineLocal2 => self.write_action_header(OpCode::DefineLocal2, 0)?,
Action::Divide => self.write_action_header(OpCode::Divide, 0)?,
Action::Delete => self.write_action_header(OpCode::Delete, 0)?,
Action::Delete2 => self.write_action_header(OpCode::Delete2, 0)?,
Action::EndDrag => self.write_action_header(OpCode::EndDrag, 0)?,
Action::Enumerate => self.write_action_header(OpCode::Enumerate, 0)?,
Action::Enumerate2 => self.write_action_header(OpCode::Enumerate2, 0)?,
Action::Equals => self.write_action_header(OpCode::Equals, 0)?,
Action::Equals2 => self.write_action_header(OpCode::Equals2, 0)?,
Action::Extends => self.write_action_header(OpCode::Extends, 0)?,
Action::GetMember => self.write_action_header(OpCode::GetMember, 0)?,
Action::GetProperty => self.write_action_header(OpCode::GetProperty, 0)?,
Action::GetTime => self.write_action_header(OpCode::GetTime, 0)?,
Action::GetUrl {
ref url,
ref target,
} => {
self.write_action_header(OpCode::GetUrl, url.len() + target.len() + 2)?;
self.write_c_string(url)?;
self.write_c_string(target)?;
}
Action::GetUrl2 {
send_vars_method,
is_target_sprite,
is_load_vars,
} => {
self.write_action_header(OpCode::GetUrl2, 1)?;
let flags = (match send_vars_method {
SendVarsMethod::None => 0,
SendVarsMethod::Get => 1,
SendVarsMethod::Post => 2,
} << 6)
| if is_target_sprite { 0b10 } else { 0 }
| if is_load_vars { 0b1 } else { 0 };
self.write_u8(flags)?;
}
Action::GetVariable => self.write_action_header(OpCode::GetVariable, 0)?,
Action::GotoFrame(frame) => {
self.write_action_header(OpCode::GotoFrame, 2)?;
self.write_u16(frame)?;
}
Action::GotoFrame2 {
set_playing,
scene_offset,
} => {
if scene_offset != 0 {
self.write_action_header(OpCode::GotoFrame2, 3)?;
self.write_u8(if set_playing { 0b11 } else { 0b01 })?;
self.write_u16(scene_offset)?;
} else {
self.write_action_header(OpCode::GotoFrame2, 1)?;
self.write_u8(if set_playing { 0b10 } else { 0b00 })?;
}
}
Action::GotoLabel(ref label) => {
self.write_action_header(OpCode::GotoLabel, label.len() + 1)?;
self.write_c_string(label)?;
}
Action::Greater => self.write_action_header(OpCode::Greater, 0)?,
Action::If { offset } => {
self.write_action_header(OpCode::If, 2)?;
self.write_i16(offset)?;
}
Action::ImplementsOp => self.write_action_header(OpCode::ImplementsOp, 0)?,
Action::Increment => self.write_action_header(OpCode::Increment, 0)?,
Action::InitArray => self.write_action_header(OpCode::InitArray, 0)?,
Action::InitObject => self.write_action_header(OpCode::InitObject, 0)?,
Action::InstanceOf => self.write_action_header(OpCode::InstanceOf, 0)?,
Action::Jump { offset } => {
self.write_action_header(OpCode::Jump, 2)?;
self.write_i16(offset)?;
}
Action::Less => self.write_action_header(OpCode::Less, 0)?,
Action::Less2 => self.write_action_header(OpCode::Less2, 0)?,
Action::MBAsciiToChar => self.write_action_header(OpCode::MBAsciiToChar, 0)?,
Action::MBCharToAscii => self.write_action_header(OpCode::MBCharToAscii, 0)?,
Action::MBStringExtract => self.write_action_header(OpCode::MBStringExtract, 0)?,
Action::MBStringLength => self.write_action_header(OpCode::MBStringLength, 0)?,
Action::Modulo => self.write_action_header(OpCode::Modulo, 0)?,
Action::Multiply => self.write_action_header(OpCode::Multiply, 0)?,
Action::NewMethod => self.write_action_header(OpCode::NewMethod, 0)?,
Action::NewObject => self.write_action_header(OpCode::NewObject, 0)?,
Action::NextFrame => self.write_action_header(OpCode::NextFrame, 0)?,
Action::Not => self.write_action_header(OpCode::Not, 0)?,
Action::Or => self.write_action_header(OpCode::Or, 0)?,
Action::Play => self.write_action_header(OpCode::Play, 0)?,
Action::Pop => self.write_action_header(OpCode::Pop, 0)?,
Action::PreviousFrame => self.write_action_header(OpCode::PreviousFrame, 0)?,
Action::Push(ref values) => {
let len = values
.iter()
.map(|v| match *v {
Value::Str(ref string) => string.len() + 2,
Value::Null | Value::Undefined => 1,
Value::Register(_) | Value::Bool(_) => 2,
Value::Double(_) => 9,
Value::Float(_) | Value::Int(_) => 5,
Value::ConstantPool(v) => {
if v < 256 {
2
} else {
3
}
}
})
.sum();
self.write_action_header(OpCode::Push, len)?;
for value in values {
self.write_push_value(value)?;
}
}
Action::PushDuplicate => self.write_action_header(OpCode::PushDuplicate, 0)?,
Action::RandomNumber => self.write_action_header(OpCode::RandomNumber, 0)?,
Action::RemoveSprite => self.write_action_header(OpCode::RemoveSprite, 0)?,
Action::Return => self.write_action_header(OpCode::Return, 0)?,
Action::SetMember => self.write_action_header(OpCode::SetMember, 0)?,
Action::SetProperty => self.write_action_header(OpCode::SetProperty, 0)?,
Action::SetTarget(ref target) => {
self.write_action_header(OpCode::SetTarget, target.len() + 1)?;
self.write_c_string(target)?;
}
Action::SetTarget2 => self.write_action_header(OpCode::SetTarget2, 0)?,
Action::SetVariable => self.write_action_header(OpCode::SetVariable, 0)?,
Action::StackSwap => self.write_action_header(OpCode::StackSwap, 0)?,
Action::StartDrag => self.write_action_header(OpCode::StartDrag, 0)?,
Action::Stop => self.write_action_header(OpCode::Stop, 0)?,
Action::StopSounds => self.write_action_header(OpCode::StopSounds, 0)?,
Action::StoreRegister(register) => {
self.write_action_header(OpCode::StoreRegister, 1)?;
self.write_u8(register)?;
}
Action::StrictEquals => self.write_action_header(OpCode::StrictEquals, 0)?,
Action::StringAdd => self.write_action_header(OpCode::StringAdd, 0)?,
Action::StringEquals => self.write_action_header(OpCode::StringEquals, 0)?,
Action::StringExtract => self.write_action_header(OpCode::StringExtract, 0)?,
Action::StringGreater => self.write_action_header(OpCode::StringGreater, 0)?,
Action::StringLength => self.write_action_header(OpCode::StringLength, 0)?,
Action::StringLess => self.write_action_header(OpCode::StringLess, 0)?,
Action::Subtract => self.write_action_header(OpCode::Subtract, 0)?,
Action::TargetPath => self.write_action_header(OpCode::TargetPath, 0)?,
Action::Throw => self.write_action_header(OpCode::Throw, 0)?,
Action::ToggleQuality => self.write_action_header(OpCode::ToggleQuality, 0)?,
Action::ToInteger => self.write_action_header(OpCode::ToInteger, 0)?,
Action::ToNumber => self.write_action_header(OpCode::ToNumber, 0)?,
Action::ToString => self.write_action_header(OpCode::ToString, 0)?,
Action::Trace => self.write_action_header(OpCode::Trace, 0)?,
Action::Try(ref try_block) => {
let try_length;
let catch_length;
let finally_length;
let mut action_buf = vec![];
{
action_buf.write_all(&try_block.try_actions)?;
try_length = try_block.try_actions.len();
catch_length = if let Some((_, ref catch)) = try_block.catch {
action_buf.write_all(catch)?;
catch.len()
} else {
0
};
finally_length = if let Some(ref finally) = try_block.finally {
action_buf.write_all(finally)?;
finally.len()
} else {
0
};
}
let len = 7
+ action_buf.len()
+ if let Some((CatchVar::Var(ref name), _)) = try_block.catch {
name.len() + 1
} else {
1
};
self.write_action_header(OpCode::Try, len)?;
self.write_u8(
if let Some((CatchVar::Register(_), _)) = try_block.catch {
0b100
} else {
0
} | if try_block.finally.is_some() { 0b10 } else { 0 }
| if try_block.catch.is_some() { 0b1 } else { 0 },
)?;
self.write_u16(try_length as u16)?;
self.write_u16(catch_length as u16)?;
self.write_u16(finally_length as u16)?;
match try_block.catch {
Some((CatchVar::Var(ref name), _)) => self.write_c_string(name)?,
Some((CatchVar::Register(i), _)) => self.write_u8(i)?,
_ => (),
}
self.inner.write_all(&action_buf)?;
}
Action::TypeOf => self.write_action_header(OpCode::TypeOf, 0)?,
Action::WaitForFrame {
frame,
num_actions_to_skip,
} => {
self.write_action_header(OpCode::WaitForFrame, 3)?;
self.write_u16(frame)?;
self.write_u8(num_actions_to_skip)?;
}
Action::WaitForFrame2 {
num_actions_to_skip,
} => {
self.write_action_header(OpCode::WaitForFrame2, 1)?;
self.write_u8(num_actions_to_skip)?;
}
Action::With { ref actions } => {
self.write_action_header(OpCode::With, actions.len())?;
self.inner.write_all(&actions)?;
}
Action::Unknown { opcode, ref data } => {
self.write_opcode_and_length(opcode, data.len())?;
self.inner.write_all(data)?;
}
}
Ok(())
}
pub fn write_action_header(&mut self, opcode: OpCode, length: usize) -> Result<()> {
self.write_opcode_and_length(opcode as u8, length)
}
pub fn write_opcode_and_length(&mut self, opcode: u8, length: usize) -> Result<()> {
self.write_u8(opcode)?;
assert!(
opcode >= 0x80 || length == 0,
"Opcodes less than 0x80 must have length 0"
);
if opcode >= 0x80 {
self.write_u16(length as u16)?;
}
Ok(())
}
fn write_push_value(&mut self, value: &Value) -> Result<()> {
match *value {
Value::Str(ref string) => {
self.write_u8(0)?;
self.write_c_string(string)?;
}
Value::Float(v) => {
self.write_u8(1)?;
self.write_f32(v)?;
}
Value::Null => {
self.write_u8(2)?;
}
Value::Undefined => {
self.write_u8(3)?;
}
Value::Register(v) => {
self.write_u8(4)?;
self.write_u8(v)?;
}
Value::Bool(v) => {
self.write_u8(5)?;
self.write_u8(v as u8)?;
}
Value::Double(v) => {
self.write_u8(6)?;
self.write_f64(v)?;
}
Value::Int(v) => {
self.write_u8(7)?;
self.write_i32(v)?;
}
Value::ConstantPool(v) => {
if v < 256 {
self.write_u8(8)?;
self.write_u8(v as u8)?;
} else {
self.write_u8(9)?;
self.write_u16(v)?;
}
}
};
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_data;
#[test]
fn write_action() {
for (swf_version, action, expected_bytes) in test_data::avm1_tests() {
let mut written_bytes = Vec::new();
Writer::new(&mut written_bytes, swf_version)
.write_action(&action)
.unwrap();
if written_bytes != expected_bytes {
panic!(
"Error writing action.\nTag:\n{:?}\n\nWrote:\n{:?}\n\nExpected:\n{:?}",
action, written_bytes, expected_bytes
);
}
}
}
}

5
swf/src/avm2.rs Normal file
View File

@ -0,0 +1,5 @@
pub mod read;
pub mod types;
pub mod write;
mod opcode;

149
swf/src/avm2/opcode.rs Normal file
View File

@ -0,0 +1,149 @@
#![allow(clippy::useless_attribute)]
#[allow(dead_code)]
#[derive(Debug, PartialEq, Clone, Copy, FromPrimitive)]
pub enum OpCode {
Add = 0xA0,
AddI = 0xC5,
AsType = 0x86,
AsTypeLate = 0x87,
BitAnd = 0xA8,
BitNot = 0x97,
BitOr = 0xa9,
BitXor = 0xaa,
Call = 0x41,
CallMethod = 0x43,
CallProperty = 0x46,
CallPropLex = 0x4c,
CallPropVoid = 0x4f,
CallStatic = 0x44,
CallSuper = 0x45,
CallSuperVoid = 0x4e,
CheckFilter = 0x78,
Coerce = 0x80,
CoerceA = 0x82,
CoerceS = 0x85,
Construct = 0x42,
ConstructProp = 0x4a,
ConstructSuper = 0x49,
ConvertB = 0x76,
ConvertI = 0x73,
ConvertD = 0x75,
ConvertO = 0x77,
ConvertU = 0x74,
ConvertS = 0x70,
Debug = 0xef,
DebugFile = 0xf1,
DebugLine = 0xf0,
DecLocal = 0x94,
DecLocalI = 0xc3,
Decrement = 0x93,
DecrementI = 0xc1,
DeleteProperty = 0x6a,
Divide = 0xa3,
Dup = 0x2a,
Dxns = 0x06,
DxnsLate = 0x07,
Equals = 0xab,
EscXAttr = 0x72,
EscXElem = 0x71,
FindProperty = 0x5e,
FindPropStrict = 0x5d,
GetDescendants = 0x59,
GetGlobalScope = 0x64,
GetGlobalSlot = 0x6e,
GetLex = 0x60,
GetLocal = 0x62,
GetLocal0 = 0xd0,
GetLocal1 = 0xd1,
GetLocal2 = 0xd2,
GetLocal3 = 0xd3,
GetProperty = 0x66,
GetScopeObject = 0x65,
GetSlot = 0x6c,
GetSuper = 0x04,
GreaterEquals = 0xb0, // Listed incorrectly in AVM2 specs.
GreaterThan = 0xaf,
HasNext = 0x1f,
HasNext2 = 0x32,
IfEq = 0x13,
IfFalse = 0x12,
IfGe = 0x18,
IfGt = 0x17,
IfLe = 0x16,
IfLt = 0x15,
IfNge = 0x0f,
IfNgt = 0x0e,
IfNle = 0x0d,
IfNlt = 0x0c,
IfNe = 0x14,
IfStrictEq = 0x19,
IfStrictNe = 0x1a,
IfTrue = 0x11,
In = 0xb4,
IncLocal = 0x92,
IncLocalI = 0xc2,
Increment = 0x91,
IncrementI = 0xc0,
InitProperty = 0x68,
InstanceOf = 0xb1,
IsType = 0xb2,
IsTypeLate = 0xb3,
Jump = 0x10,
Kill = 0x08,
Label = 0x09,
LessEquals = 0xae,
LessThan = 0xad,
LookupSwitch = 0x1b,
LShift = 0xa5,
Modulo = 0xa4,
Multiply = 0xa2,
MultiplyI = 0xc7,
Negate = 0x90,
NegateI = 0xc4,
NewActivation = 0x57,
NewArray = 0x56,
NewCatch = 0x5a,
NewClass = 0x58,
NewFunction = 0x40,
NewObject = 0x55,
NextName = 0x1e,
NextValue = 0x23,
Nop = 0x02,
Not = 0x96,
Pop = 0x29,
PopScope = 0x1d,
PushByte = 0x24,
PushDouble = 0x2f,
PushFalse = 0x27,
PushInt = 0x2d,
PushNamespace = 0x31,
PushNaN = 0x28,
PushNull = 0x20,
PushScope = 0x30,
PushShort = 0x25,
PushString = 0x2c,
PushTrue = 0x26,
PushUint = 0x2e,
PushUndefined = 0x21,
PushWith = 0x1c,
ReturnValue = 0x48,
ReturnVoid = 0x47,
RShift = 0xa6,
SetLocal = 0x63,
SetLocal0 = 0xd4,
SetLocal1 = 0xd5,
SetLocal2 = 0xd6,
SetLocal3 = 0xd7,
SetGlobalSlot = 0x6f,
SetProperty = 0x61,
SetSlot = 0x6d,
SetSuper = 0x05,
StrictEquals = 0xac,
Subtract = 0xa1,
SubtractI = 0xc6,
Swap = 0x2b,
Throw = 0x03,
TypeOf = 0x95,
URShift = 0xa7,
}

884
swf/src/avm2/read.rs Normal file
View File

@ -0,0 +1,884 @@
use crate::avm2::types::*;
use crate::read::SwfRead;
use std::io::{Error, ErrorKind, Read, Result};
pub struct Reader<R: Read> {
inner: R,
}
impl<R: Read> SwfRead<R> for Reader<R> {
fn get_inner(&mut self) -> &mut R {
&mut self.inner
}
}
impl<R: Read> Reader<R> {
pub fn new(inner: R) -> Reader<R> {
Reader { inner }
}
pub fn read(&mut self) -> Result<AbcFile> {
let minor_version = self.read_u16()?;
let major_version = self.read_u16()?;
let constant_pool = self.read_constant_pool()?;
let len = self.read_u30()?;
let mut methods = vec![];
for _ in 0..len {
methods.push(self.read_method()?);
}
let len = self.read_u30()? as usize;
let mut metadata = Vec::with_capacity(len);
for _ in 0..len {
metadata.push(self.read_metadata()?);
}
let len = self.read_u30()? as usize;
let mut instances = Vec::with_capacity(len);
for _ in 0..len {
instances.push(self.read_instance()?);
}
let mut classes = Vec::with_capacity(len);
for _ in 0..len {
classes.push(self.read_class()?);
}
let len = self.read_u30()? as usize;
let mut scripts = Vec::with_capacity(len);
for _ in 0..len {
scripts.push(self.read_script()?);
}
let len = self.read_u30()? as usize;
let mut method_bodies = Vec::with_capacity(len);
for _ in 0..len {
method_bodies.push(self.read_method_body()?);
}
Ok(AbcFile {
major_version,
minor_version,
constant_pool,
methods,
metadata,
instances,
classes,
scripts,
method_bodies,
})
}
fn read_u30(&mut self) -> Result<u32> {
let mut n = 0;
let mut i = 0;
loop {
let byte: u32 = self.read_u8()?.into();
n |= (byte & 0b0111_1111) << i;
i += 7;
if byte & 0b1000_0000 == 0 {
break;
}
}
Ok(n)
}
fn read_u32(&mut self) -> Result<u32> {
self.read_u30()
}
fn read_i24(&mut self) -> Result<i32> {
Ok(i32::from(self.read_u8()?)
| (i32::from(self.read_u8()?) << 8)
| (i32::from(self.read_u8()?) << 16))
}
fn read_i32(&mut self) -> Result<i32> {
let mut n: i32 = 0;
let mut i = 0;
loop {
let byte: i32 = self.read_u8()?.into();
n |= (byte & 0b0111_1111) << i;
i += 7;
if byte & 0b1000_0000 == 0 {
n <<= 32 - i;
n >>= 32 - i;
break;
}
}
Ok(n)
}
fn read_string(&mut self) -> Result<String> {
let len = self.read_u30()? as usize;
let mut s = String::with_capacity(len);
self.inner
.by_ref()
.take(len as u64)
.read_to_string(&mut s)?;
Ok(s)
}
fn read_index<T>(&mut self) -> Result<Index<T>> {
use std::marker::PhantomData;
Ok(Index(self.read_u30()?, PhantomData))
}
fn read_namespace(&mut self) -> Result<Namespace> {
let kind = self.read_u8()?;
let name: Index<String> = self.read_index()?;
// TODO: AVM2 specs say that "non-system" namespaces
// should have an empty name?
Ok(match kind {
0x05 => Namespace::Private(name),
0x08 => Namespace::Namespace(name),
0x16 => Namespace::Package(name),
0x17 => Namespace::PackageInternal(name),
0x18 => Namespace::Protected(name),
0x19 => Namespace::Explicit(name),
0x1a => Namespace::StaticProtected(name),
_ => return Err(Error::new(ErrorKind::InvalidData, "Invalid namespace kind")),
})
}
fn read_namespace_set(&mut self) -> Result<NamespaceSet> {
let len = self.read_u30()? as usize;
let mut namespace_set = vec![];
for _ in 0..len {
namespace_set.push(self.read_index()?);
}
Ok(namespace_set)
}
fn read_multiname(&mut self) -> Result<Multiname> {
let kind = self.read_u8()?;
Ok(match kind {
0x07 => Multiname::QName {
namespace: self.read_index()?,
name: self.read_index()?,
},
0x0d => Multiname::QNameA {
namespace: self.read_index()?,
name: self.read_index()?,
},
0x0f => Multiname::RTQName {
name: self.read_index()?,
},
0x10 => Multiname::RTQNameA {
name: self.read_index()?,
},
0x11 => Multiname::RTQNameL,
0x12 => Multiname::RTQNameLA,
0x09 => Multiname::Multiname {
name: self.read_index()?,
namespace_set: self.read_index()?,
},
0x0e => Multiname::MultinameA {
name: self.read_index()?,
namespace_set: self.read_index()?,
},
0x1b => Multiname::MultinameL {
namespace_set: self.read_index()?,
},
0x1c => Multiname::MultinameLA {
namespace_set: self.read_index()?,
},
_ => return Err(Error::new(ErrorKind::InvalidData, "Invalid multiname kind")),
})
}
fn read_constant_pool(&mut self) -> Result<ConstantPool> {
let len = self.read_u30()?;
let mut ints = Vec::with_capacity(len as usize);
if len > 0 {
for _ in 0..len - 1 {
ints.push(self.read_i32()?);
}
}
let len = self.read_u30()?;
let mut uints = Vec::with_capacity(len as usize);
if len > 0 {
for _ in 0..len - 1 {
uints.push(self.read_u32()?);
}
}
let len = self.read_u30()?;
let mut doubles = Vec::with_capacity(len as usize);
if len > 0 {
for _ in 0..len - 1 {
doubles.push(self.read_f64()?);
}
}
let len = self.read_u30()?;
let mut strings = Vec::with_capacity(len as usize);
if len > 0 {
for _ in 0..len - 1 {
strings.push(self.read_string()?);
}
}
let len = self.read_u30()?;
let mut namespaces = Vec::with_capacity(len as usize);
if len > 0 {
for _ in 0..len - 1 {
namespaces.push(self.read_namespace()?);
}
}
let len = self.read_u30()?;
let mut namespace_sets = Vec::with_capacity(len as usize);
if len > 0 {
for _ in 0..len - 1 {
namespace_sets.push(self.read_namespace_set()?);
}
}
let len = self.read_u30()?;
let mut multinames = Vec::with_capacity(len as usize);
if len > 0 {
for _ in 0..len - 1 {
multinames.push(self.read_multiname()?);
}
}
Ok(ConstantPool {
ints,
uints,
doubles,
strings,
namespaces,
namespace_sets,
multinames,
})
}
fn read_method(&mut self) -> Result<Method> {
let num_params = self.read_u8()? as usize;
let return_type = self.read_index()?;
let mut params = vec![];
for _ in 0..num_params {
params.push(MethodParam {
kind: self.read_index()?,
name: None,
default_value: None,
})
}
let name = self.read_index()?;
let flags = self.read_u8()?;
if flags & 0x08 != 0 {
let num_optional_params = self.read_u30()? as usize;
#[allow(clippy::needless_range_loop)]
for i in 0..num_optional_params {
params[i].default_value = Some(self.read_constant_value()?);
}
}
if flags & 0x80 != 0 {
#[allow(clippy::needless_range_loop)]
for i in 0..num_params {
params[i].name = Some(self.read_index()?);
}
}
Ok(Method {
name,
params,
return_type,
needs_arguments_object: flags & 0x01 != 0,
needs_activation: flags & 0x02 != 0,
needs_rest: flags & 0x04 != 0,
needs_dxns: flags & 0x40 != 0,
})
}
fn read_constant_value(&mut self) -> Result<DefaultValue> {
let index = self.read_u30()?;
Ok(match self.read_u8()? {
0x00 => DefaultValue::Undefined,
0x01 => DefaultValue::String(Index::new(index)),
0x03 => DefaultValue::Int(Index::new(index)),
0x04 => DefaultValue::Uint(Index::new(index)),
0x05 => DefaultValue::Private(Index::new(index)),
0x06 => DefaultValue::Double(Index::new(index)),
0x08 => DefaultValue::Namespace(Index::new(index)),
0x0a => DefaultValue::False,
0x0b => DefaultValue::True,
0x0c => DefaultValue::Null,
0x16 => DefaultValue::Package(Index::new(index)),
0x17 => DefaultValue::PackageInternal(Index::new(index)),
0x18 => DefaultValue::Protected(Index::new(index)),
0x19 => DefaultValue::Explicit(Index::new(index)),
0x1a => DefaultValue::StaticProtected(Index::new(index)),
_ => return Err(Error::new(ErrorKind::InvalidData, "Invalid default value")),
})
}
fn read_optional_value(&mut self) -> Result<Option<DefaultValue>> {
let index = self.read_u30()?;
if index == 0 {
Ok(None)
} else {
Ok(Some(match self.read_u8()? {
0x00 => DefaultValue::Undefined,
0x01 => DefaultValue::String(Index::new(index)),
0x03 => DefaultValue::Int(Index::new(index)),
0x04 => DefaultValue::Uint(Index::new(index)),
0x05 => DefaultValue::Private(Index::new(index)),
0x06 => DefaultValue::Double(Index::new(index)),
0x08 => DefaultValue::Namespace(Index::new(index)),
0x0a => DefaultValue::False,
0x0b => DefaultValue::True,
0x0c => DefaultValue::Null,
0x16 => DefaultValue::Package(Index::new(index)),
0x17 => DefaultValue::PackageInternal(Index::new(index)),
0x18 => DefaultValue::Protected(Index::new(index)),
0x19 => DefaultValue::Explicit(Index::new(index)),
0x1a => DefaultValue::StaticProtected(Index::new(index)),
_ => return Err(Error::new(ErrorKind::InvalidData, "Invalid default value")),
}))
}
}
fn read_metadata(&mut self) -> Result<Metadata> {
let name = self.read_index()?;
let mut items = vec![];
let num_items = self.read_u30()?;
for _ in 0..num_items {
items.push(MetadataItem {
key: self.read_index()?,
value: self.read_index()?,
})
}
Ok(Metadata { name, items })
}
fn read_instance(&mut self) -> Result<Instance> {
let name = self.read_index()?;
let super_name = self.read_index()?;
let flags = self.read_u8()?;
let protected_namespace = if flags & 0x08 != 0 {
Some(self.read_index()?)
} else {
None
};
let num_interfaces = self.read_u30()? as usize;
let mut interfaces = Vec::with_capacity(num_interfaces);
for _ in 0..num_interfaces {
interfaces.push(self.read_index()?);
}
let init_method = self.read_index()?;
let num_traits = self.read_u30()? as usize;
let mut traits = Vec::with_capacity(num_traits);
for _ in 0..num_traits {
traits.push(self.read_trait()?);
}
Ok(Instance {
name,
super_name,
protected_namespace,
interfaces,
traits,
init_method,
is_sealed: flags & 0x01 != 0,
is_final: flags & 0x02 != 0,
is_interface: flags & 0x04 != 0,
})
}
fn read_class(&mut self) -> Result<Class> {
let init_method = self.read_index()?;
let num_traits = self.read_u30()? as usize;
let mut traits = Vec::with_capacity(num_traits);
for _ in 0..num_traits {
traits.push(self.read_trait()?);
}
Ok(Class {
init_method,
traits,
})
}
fn read_script(&mut self) -> Result<Script> {
let init_method = self.read_index()?;
let num_traits = self.read_u30()? as usize;
let mut traits = Vec::with_capacity(num_traits);
for _ in 0..num_traits {
traits.push(self.read_trait()?);
}
Ok(Script {
init_method,
traits,
})
}
fn read_trait(&mut self) -> Result<Trait> {
let name = self.read_index()?;
let flags = self.read_u8()?;
let kind = match flags & 0b1111 {
0 => TraitKind::Slot {
slot_id: self.read_u30()?,
type_name: self.read_index()?,
value: self.read_optional_value()?,
},
1 => TraitKind::Method {
disp_id: self.read_u30()?,
method: self.read_index()?,
},
2 => TraitKind::Getter {
disp_id: self.read_u30()?,
method: self.read_index()?,
},
3 => TraitKind::Setter {
disp_id: self.read_u30()?,
method: self.read_index()?,
},
4 => TraitKind::Class {
slot_id: self.read_u30()?,
class: self.read_index()?,
},
5 => TraitKind::Function {
slot_id: self.read_u30()?,
function: self.read_index()?,
},
6 => TraitKind::Const {
slot_id: self.read_u30()?,
type_name: self.read_index()?,
value: self.read_optional_value()?,
},
_ => return Err(Error::new(ErrorKind::InvalidData, "Invalid trait kind")),
};
let mut metadata = vec![];
if flags & 0b0100_0000 != 0 {
let num_metadata = self.read_u30()? as usize;
metadata.reserve(num_metadata);
for _ in 0..num_metadata {
metadata.push(self.read_index()?);
}
}
Ok(Trait {
name,
kind,
metadata,
is_final: flags & 0b0001_0000 != 0,
is_override: flags & 0b0010_0000 != 0,
})
}
fn read_method_body(&mut self) -> Result<MethodBody> {
let method = self.read_index()?;
let max_stack = self.read_u30()?;
let num_locals = self.read_u30()?;
let init_scope_depth = self.read_u30()?;
let max_scope_depth = self.read_u30()?;
let code_len = self.read_u30()?;
let mut code = vec![];
{
let mut code_reader = Reader::new(self.inner.by_ref().take(code_len.into()));
while let Ok(Some(op)) = code_reader.read_op() {
code.push(op);
}
}
let num_exceptions = self.read_u30()? as usize;
let mut exceptions = Vec::with_capacity(num_exceptions);
for _ in 0..num_exceptions {
exceptions.push(self.read_exception()?);
}
let num_traits = self.read_u30()? as usize;
let mut traits = Vec::with_capacity(num_traits);
for _ in 0..num_traits {
traits.push(self.read_trait()?);
}
Ok(MethodBody {
method,
max_stack,
num_locals,
init_scope_depth,
max_scope_depth,
code,
exceptions,
traits,
})
}
fn read_op(&mut self) -> Result<Option<Op>> {
use crate::avm2::opcode::OpCode;
use num_traits::FromPrimitive;
let opcode = match OpCode::from_u8(self.read_u8()?) {
Some(o) => o,
None => return Err(Error::new(ErrorKind::InvalidData, "Invalid opcode")),
};
let op = match opcode {
OpCode::Add => Op::Add,
OpCode::AddI => Op::AddI,
OpCode::AsType => Op::AsType {
type_name: self.read_index()?,
},
OpCode::AsTypeLate => Op::AsTypeLate,
OpCode::BitAnd => Op::BitAnd,
OpCode::BitNot => Op::BitNot,
OpCode::BitOr => Op::BitOr,
OpCode::BitXor => Op::BitXor,
OpCode::Call => Op::Call {
num_args: self.read_u30()?,
},
OpCode::CallMethod => Op::CallMethod {
index: self.read_index()?,
num_args: self.read_u30()?,
},
OpCode::CallProperty => Op::CallProperty {
index: self.read_index()?,
num_args: self.read_u30()?,
},
OpCode::CallPropLex => Op::CallPropLex {
index: self.read_index()?,
num_args: self.read_u30()?,
},
OpCode::CallPropVoid => Op::CallPropVoid {
index: self.read_index()?,
num_args: self.read_u30()?,
},
OpCode::CallStatic => Op::CallStatic {
index: self.read_index()?,
num_args: self.read_u30()?,
},
OpCode::CallSuper => Op::CallSuper {
index: self.read_index()?,
num_args: self.read_u30()?,
},
OpCode::CallSuperVoid => Op::CallSuperVoid {
index: self.read_index()?,
num_args: self.read_u30()?,
},
OpCode::CheckFilter => Op::CheckFilter,
OpCode::Coerce => Op::Coerce {
index: self.read_index()?,
},
OpCode::CoerceA => Op::CoerceA,
OpCode::CoerceS => Op::CoerceS,
OpCode::Construct => Op::Construct {
num_args: self.read_u30()?,
},
OpCode::ConstructProp => Op::ConstructProp {
index: self.read_index()?,
num_args: self.read_u30()?,
},
OpCode::ConstructSuper => Op::ConstructSuper {
num_args: self.read_u30()?,
},
OpCode::ConvertB => Op::ConvertB,
OpCode::ConvertD => Op::ConvertD,
OpCode::ConvertI => Op::ConvertI,
OpCode::ConvertO => Op::ConvertO,
OpCode::ConvertS => Op::ConvertS,
OpCode::ConvertU => Op::ConvertU,
OpCode::Debug => {
let op = Op::Debug {
is_local_register: self.read_u8()? != 0,
register_name: self.read_index()?,
register: self.read_u8()?,
};
self.read_u30()?; // Unused
op
}
OpCode::DebugFile => Op::DebugFile {
file_name: self.read_index()?,
},
OpCode::DebugLine => Op::DebugLine {
line_num: self.read_u30()?,
},
OpCode::DecLocal => Op::DecLocal {
index: self.read_u30()?,
},
OpCode::DecLocalI => Op::DecLocalI {
index: self.read_u30()?,
},
OpCode::Decrement => Op::Decrement,
OpCode::DecrementI => Op::DecrementI,
OpCode::DeleteProperty => Op::DeleteProperty {
index: self.read_index()?,
},
OpCode::Divide => Op::Divide,
OpCode::Dup => Op::Dup,
OpCode::Dxns => Op::Dxns {
index: self.read_index()?,
},
OpCode::DxnsLate => Op::DxnsLate,
OpCode::Equals => Op::Equals,
OpCode::EscXAttr => Op::EscXAttr,
OpCode::EscXElem => Op::EscXElem,
OpCode::FindProperty => Op::FindProperty {
index: self.read_index()?,
},
OpCode::FindPropStrict => Op::FindPropStrict {
index: self.read_index()?,
},
OpCode::GetDescendants => Op::GetDescendants {
index: self.read_index()?,
},
OpCode::GetGlobalScope => Op::GetGlobalScope,
OpCode::GetGlobalSlot => Op::GetGlobalSlot {
index: self.read_u30()?,
},
OpCode::GetLex => Op::GetLex {
index: self.read_index()?,
},
OpCode::GetLocal => Op::GetLocal {
index: self.read_u30()?,
},
OpCode::GetLocal0 => Op::GetLocal { index: 0 },
OpCode::GetLocal1 => Op::GetLocal { index: 1 },
OpCode::GetLocal2 => Op::GetLocal { index: 2 },
OpCode::GetLocal3 => Op::GetLocal { index: 3 },
OpCode::GetProperty => Op::GetProperty {
index: self.read_index()?,
},
OpCode::GetScopeObject => Op::GetScopeObject {
index: self.read_u8()?,
},
OpCode::GetSlot => Op::GetSlot {
index: self.read_u30()?,
},
OpCode::GetSuper => Op::GetSuper {
index: self.read_index()?,
},
OpCode::GreaterEquals => Op::GreaterEquals,
OpCode::GreaterThan => Op::GreaterThan,
OpCode::HasNext => Op::HasNext,
OpCode::HasNext2 => Op::HasNext2 {
object_register: self.read_u30()?,
index_register: self.read_u30()?,
},
OpCode::IfEq => Op::IfEq {
offset: self.read_i24()?,
},
OpCode::IfFalse => Op::IfFalse {
offset: self.read_i24()?,
},
OpCode::IfGe => Op::IfGe {
offset: self.read_i24()?,
},
OpCode::IfGt => Op::IfGt {
offset: self.read_i24()?,
},
OpCode::IfLe => Op::IfLe {
offset: self.read_i24()?,
},
OpCode::IfLt => Op::IfLt {
offset: self.read_i24()?,
},
OpCode::IfNge => Op::IfNge {
offset: self.read_i24()?,
},
OpCode::IfNgt => Op::IfNgt {
offset: self.read_i24()?,
},
OpCode::IfNle => Op::IfNle {
offset: self.read_i24()?,
},
OpCode::IfNlt => Op::IfNlt {
offset: self.read_i24()?,
},
OpCode::IfNe => Op::IfNe {
offset: self.read_i24()?,
},
OpCode::IfStrictEq => Op::IfStrictEq {
offset: self.read_i24()?,
},
OpCode::IfStrictNe => Op::IfStrictNe {
offset: self.read_i24()?,
},
OpCode::IfTrue => Op::IfTrue {
offset: self.read_i24()?,
},
OpCode::In => Op::In,
OpCode::IncLocal => Op::IncLocal {
index: self.read_u30()?,
},
OpCode::IncLocalI => Op::IncLocalI {
index: self.read_u30()?,
},
OpCode::Increment => Op::Increment,
OpCode::IncrementI => Op::IncrementI,
OpCode::InitProperty => Op::InitProperty {
index: self.read_index()?,
},
OpCode::InstanceOf => Op::InstanceOf,
OpCode::IsType => Op::IsType {
index: self.read_index()?,
},
OpCode::IsTypeLate => Op::IsTypeLate,
OpCode::Jump => Op::Jump {
offset: self.read_i24()?,
},
OpCode::Kill => Op::Kill {
index: self.read_u30()?,
},
OpCode::Label => Op::Label,
OpCode::LessEquals => Op::LessEquals,
OpCode::LessThan => Op::LessThan,
OpCode::LookupSwitch => Op::LookupSwitch {
default_offset: self.read_i24()?,
case_offsets: {
let num_cases = self.read_u30()? + 1;
let mut case_offsets = vec![];
for _ in 0..num_cases {
case_offsets.push(self.read_i24()?);
}
case_offsets
},
},
OpCode::LShift => Op::LShift,
OpCode::Modulo => Op::Modulo,
OpCode::Multiply => Op::Multiply,
OpCode::MultiplyI => Op::MultiplyI,
OpCode::Negate => Op::Negate,
OpCode::NegateI => Op::NegateI,
OpCode::NewActivation => Op::NewActivation,
OpCode::NewArray => Op::NewArray {
num_args: self.read_u30()?,
},
OpCode::NewCatch => Op::NewCatch {
index: self.read_index()?,
},
OpCode::NewClass => Op::NewClass {
index: self.read_index()?,
},
OpCode::NewFunction => Op::NewFunction {
index: self.read_index()?,
},
OpCode::NewObject => Op::NewObject {
num_args: self.read_u30()?,
},
OpCode::NextName => Op::NextName,
OpCode::NextValue => Op::NextValue,
OpCode::Nop => Op::Nop,
OpCode::Not => Op::Not,
OpCode::Pop => Op::Pop,
OpCode::PopScope => Op::PopScope,
OpCode::PushByte => Op::PushByte {
value: self.read_u8()?,
},
OpCode::PushDouble => Op::PushDouble {
value: self.read_index()?,
},
OpCode::PushFalse => Op::PushFalse,
OpCode::PushInt => Op::PushInt {
value: self.read_index()?,
},
OpCode::PushNamespace => Op::PushNamespace {
value: self.read_index()?,
},
OpCode::PushNaN => Op::PushNaN,
OpCode::PushNull => Op::PushNull,
OpCode::PushScope => Op::PushScope,
OpCode::PushShort => Op::PushShort {
value: self.read_u30()?,
},
OpCode::PushString => Op::PushString {
value: self.read_index()?,
},
OpCode::PushTrue => Op::PushTrue,
OpCode::PushUint => Op::PushUint {
value: self.read_index()?,
},
OpCode::PushUndefined => Op::PushUndefined,
OpCode::PushWith => Op::PushWith,
OpCode::ReturnValue => Op::ReturnValue,
OpCode::ReturnVoid => Op::ReturnVoid,
OpCode::RShift => Op::RShift,
OpCode::SetLocal => Op::SetLocal {
index: self.read_u30()?,
},
OpCode::SetLocal0 => Op::SetLocal { index: 0 },
OpCode::SetLocal1 => Op::SetLocal { index: 1 },
OpCode::SetLocal2 => Op::SetLocal { index: 2 },
OpCode::SetLocal3 => Op::SetLocal { index: 3 },
OpCode::SetGlobalSlot => Op::SetGlobalSlot {
index: self.read_u30()?,
},
OpCode::SetProperty => Op::SetProperty {
index: self.read_index()?,
},
OpCode::SetSlot => Op::SetSlot {
index: self.read_u30()?,
},
OpCode::SetSuper => Op::SetSuper {
index: self.read_index()?,
},
OpCode::StrictEquals => Op::StrictEquals,
OpCode::Subtract => Op::Subtract,
OpCode::SubtractI => Op::SubtractI,
OpCode::Swap => Op::Swap,
OpCode::Throw => Op::Throw,
OpCode::TypeOf => Op::TypeOf,
OpCode::URShift => Op::URShift,
};
Ok(Some(op))
}
fn read_exception(&mut self) -> Result<Exception> {
Ok(Exception {
from_offset: self.read_u30()?,
to_offset: self.read_u30()?,
target_offset: self.read_u30()?,
type_name: self.read_index()?,
variable_name: self.read_index()?,
})
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::test_data;
pub fn read_abc_from_file(path: &str) -> Vec<u8> {
use crate::types::Tag;
use std::fs::File;
let mut file = File::open(path).unwrap();
let mut data = Vec::new();
file.read_to_end(&mut data).unwrap();
let swf = crate::read_swf(&data[..]).unwrap();
for tag in swf.tags {
if let Tag::DoAbc(do_abc) = tag {
return do_abc.data;
}
}
panic!("ABC tag not found in {}", path);
}
#[test]
fn read_abc() {
for (_, abc_file, bytes) in test_data::avm2_tests() {
let mut reader = Reader::new(&bytes[..]);
let parsed = reader.read().unwrap();
if parsed != abc_file {
// Failed, result doesn't match.
panic!(
"Incorrectly parsed ABC.\nRead:\n{:?}\n\nExpected:\n{:?}",
parsed, abc_file
);
}
}
}
}

515
swf/src/avm2/types.rs Normal file
View File

@ -0,0 +1,515 @@
use std::marker::PhantomData;
#[derive(Clone, Debug, PartialEq)]
pub struct AbcFile {
pub major_version: u16,
pub minor_version: u16,
pub constant_pool: ConstantPool,
pub methods: Vec<Method>,
pub metadata: Vec<Metadata>,
pub instances: Vec<Instance>,
pub classes: Vec<Class>,
pub scripts: Vec<Script>,
pub method_bodies: Vec<MethodBody>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ConstantPool {
pub ints: Vec<i32>,
pub uints: Vec<u32>,
pub doubles: Vec<f64>,
pub strings: Vec<String>,
pub namespaces: Vec<Namespace>,
pub namespace_sets: Vec<NamespaceSet>,
pub multinames: Vec<Multiname>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Index<T>(pub u32, pub PhantomData<T>);
impl<T> Index<T> {
pub fn new(i: u32) -> Index<T> {
Index(i, PhantomData)
}
pub fn as_u30(&self) -> u32 {
self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Namespace {
Namespace(Index<String>),
Package(Index<String>),
PackageInternal(Index<String>),
Protected(Index<String>),
Explicit(Index<String>),
StaticProtected(Index<String>),
Private(Index<String>),
}
pub type NamespaceSet = Vec<Index<Namespace>>;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Multiname {
QName {
namespace: Index<Namespace>,
name: Index<String>,
},
QNameA {
namespace: Index<Namespace>,
name: Index<String>,
},
RTQName {
name: Index<String>,
},
RTQNameA {
name: Index<String>,
},
RTQNameL,
RTQNameLA,
Multiname {
namespace_set: Index<NamespaceSet>,
name: Index<String>,
},
MultinameA {
namespace_set: Index<NamespaceSet>,
name: Index<String>,
},
MultinameL {
namespace_set: Index<NamespaceSet>,
},
MultinameLA {
namespace_set: Index<NamespaceSet>,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct Method {
pub name: Index<String>,
pub params: Vec<MethodParam>,
pub return_type: Index<Multiname>,
pub needs_arguments_object: bool,
pub needs_activation: bool,
pub needs_rest: bool,
pub needs_dxns: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MethodParam {
pub name: Option<Index<String>>,
pub kind: Index<Multiname>,
pub default_value: Option<DefaultValue>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MethodBody {
pub method: Index<Method>,
pub max_stack: u32,
pub num_locals: u32,
pub init_scope_depth: u32,
pub max_scope_depth: u32,
pub code: Vec<Op>,
pub exceptions: Vec<Exception>,
pub traits: Vec<Trait>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Exception {
pub from_offset: u32,
pub to_offset: u32,
pub target_offset: u32,
pub variable_name: Index<String>,
pub type_name: Index<Multiname>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Opcode;
#[derive(Clone, Debug, PartialEq)]
pub enum DefaultValue {
Int(Index<i32>),
Uint(Index<u32>),
Double(Index<f64>),
String(Index<String>),
True,
False,
Null,
Undefined,
Namespace(Index<Namespace>),
Package(Index<Namespace>),
PackageInternal(Index<Namespace>),
Protected(Index<Namespace>),
Explicit(Index<Namespace>),
StaticProtected(Index<Namespace>),
Private(Index<Namespace>),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Metadata {
pub name: Index<String>,
pub items: Vec<MetadataItem>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MetadataItem {
pub key: Index<String>,
pub value: Index<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Instance {
pub name: Index<Multiname>,
pub super_name: Index<Multiname>,
pub is_sealed: bool,
pub is_final: bool,
pub is_interface: bool,
pub protected_namespace: Option<Index<Namespace>>,
pub interfaces: Vec<Index<Multiname>>,
pub init_method: Index<Method>,
pub traits: Vec<Trait>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Trait {
pub name: Index<Multiname>,
pub kind: TraitKind,
pub metadata: Vec<Index<Metadata>>,
pub is_final: bool,
pub is_override: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub enum TraitKind {
Slot {
slot_id: u32,
type_name: Index<Multiname>,
value: Option<DefaultValue>,
},
Method {
disp_id: u32,
method: Index<Method>,
},
Getter {
disp_id: u32,
method: Index<Method>,
},
Setter {
disp_id: u32,
method: Index<Method>,
},
Class {
slot_id: u32,
class: Index<Class>,
},
Function {
slot_id: u32,
function: Index<Method>,
},
Const {
slot_id: u32,
type_name: Index<Multiname>,
value: Option<DefaultValue>,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct Class {
pub init_method: Index<Method>,
pub traits: Vec<Trait>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Script {
pub init_method: Index<Method>,
pub traits: Vec<Trait>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Op {
Add,
AddI,
AsType {
type_name: Index<Multiname>,
},
AsTypeLate,
BitAnd,
BitNot,
BitOr,
BitXor,
Call {
num_args: u32,
},
CallMethod {
index: Index<Method>,
num_args: u32,
},
CallProperty {
index: Index<Multiname>,
num_args: u32,
},
CallPropLex {
index: Index<Multiname>,
num_args: u32,
},
CallPropVoid {
index: Index<Multiname>,
num_args: u32,
},
CallStatic {
index: Index<Method>,
num_args: u32,
},
CallSuper {
index: Index<Multiname>,
num_args: u32,
},
CallSuperVoid {
index: Index<Multiname>,
num_args: u32,
},
CheckFilter,
Coerce {
index: Index<Multiname>,
},
CoerceA,
CoerceS,
Construct {
num_args: u32,
},
ConstructProp {
index: Index<Multiname>,
num_args: u32,
},
ConstructSuper {
num_args: u32,
},
ConvertB,
ConvertD,
ConvertI,
ConvertO,
ConvertS,
ConvertU,
Debug {
is_local_register: bool,
register_name: Index<String>,
register: u8,
},
DebugFile {
file_name: Index<String>,
},
DebugLine {
line_num: u32,
},
DecLocal {
index: u32,
},
DecLocalI {
index: u32,
},
Decrement,
DecrementI,
DeleteProperty {
index: Index<Multiname>,
},
Divide,
Dup,
Dxns {
index: Index<String>,
},
DxnsLate,
Equals,
EscXAttr,
EscXElem,
FindProperty {
index: Index<Multiname>,
},
FindPropStrict {
index: Index<Multiname>,
},
GetDescendants {
index: Index<Multiname>,
},
GetGlobalScope,
GetGlobalSlot {
index: u32,
},
GetLex {
index: Index<Multiname>,
},
GetLocal {
index: u32,
},
GetProperty {
index: Index<Multiname>,
},
GetScopeObject {
index: u8,
},
GetSlot {
index: u32,
},
GetSuper {
index: Index<Multiname>,
},
GreaterEquals,
GreaterThan,
HasNext,
HasNext2 {
object_register: u32,
index_register: u32,
},
IfEq {
offset: i32,
},
IfFalse {
offset: i32,
},
IfGe {
offset: i32,
},
IfGt {
offset: i32,
},
IfLe {
offset: i32,
},
IfLt {
offset: i32,
},
IfNge {
offset: i32,
},
IfNgt {
offset: i32,
},
IfNle {
offset: i32,
},
IfNlt {
offset: i32,
},
IfNe {
offset: i32,
},
IfStrictEq {
offset: i32,
},
IfStrictNe {
offset: i32,
},
IfTrue {
offset: i32,
},
In,
IncLocal {
index: u32,
},
IncLocalI {
index: u32,
},
Increment,
IncrementI,
InitProperty {
index: Index<Multiname>,
},
InstanceOf,
IsType {
index: Index<Multiname>,
},
IsTypeLate,
Jump {
offset: i32,
},
Kill {
index: u32,
},
Label,
LessEquals,
LessThan,
LookupSwitch {
default_offset: i32,
case_offsets: Vec<i32>,
},
LShift,
Modulo,
Multiply,
MultiplyI,
Negate,
NegateI,
NewActivation,
NewArray {
num_args: u32,
},
NewCatch {
index: Index<Exception>,
},
NewClass {
index: Index<Class>,
},
NewFunction {
index: Index<Method>,
},
NewObject {
num_args: u32,
},
NextName,
NextValue,
Nop,
Not,
Pop,
PopScope,
PushByte {
value: u8,
},
PushDouble {
value: Index<f64>,
},
PushFalse,
PushInt {
value: Index<i32>,
},
PushNamespace {
value: Index<Namespace>,
},
PushNaN,
PushNull,
PushScope,
PushShort {
value: u32,
}, // TODO: Is this really a u30?
PushString {
value: Index<String>,
},
PushTrue,
PushUint {
value: Index<u32>,
},
PushUndefined,
PushWith,
ReturnValue,
ReturnVoid,
RShift,
SetLocal {
index: u32,
},
SetGlobalSlot {
index: u32,
},
SetProperty {
index: Index<Multiname>,
},
SetSlot {
index: u32,
},
SetSuper {
index: Index<Multiname>,
},
StrictEquals,
Subtract,
SubtractI,
Swap,
Throw,
TypeOf,
URShift,
}

996
swf/src/avm2/write.rs Normal file
View File

@ -0,0 +1,996 @@
use crate::avm2::opcode::OpCode;
use crate::avm2::types::*;
use crate::write::SwfWrite;
use std::io::{Result, Write};
pub struct Writer<W: Write> {
inner: W,
}
impl<W: Write> SwfWrite<W> for Writer<W> {
fn get_inner(&mut self) -> &mut W {
&mut self.inner
}
}
impl<W: Write> Writer<W> {
pub fn new(inner: W) -> Writer<W> {
Writer { inner }
}
pub fn write(&mut self, abc_file: AbcFile) -> Result<()> {
self.write_u16(abc_file.minor_version)?;
self.write_u16(abc_file.major_version)?;
self.write_constant_pool(&abc_file.constant_pool)?;
self.write_u30(abc_file.methods.len() as u32)?;
for method in &abc_file.methods {
self.write_method(method)?;
}
self.write_u30(abc_file.metadata.len() as u32)?;
for metadata in &abc_file.metadata {
self.write_metadata(metadata)?;
}
self.write_u30(abc_file.instances.len() as u32)?;
for instance in &abc_file.instances {
self.write_instance(instance)?;
}
for class in &abc_file.classes {
self.write_class(class)?;
}
self.write_u30(abc_file.scripts.len() as u32)?;
for script in &abc_file.scripts {
self.write_script(script)?;
}
self.write_u30(abc_file.method_bodies.len() as u32)?;
for method_body in &abc_file.method_bodies {
self.write_method_body(method_body)?;
}
Ok(())
}
fn write_u30(&mut self, n: u32) -> Result<()> {
// TODO: Verify n fits in 30 bits.
self.write_u32(n)
}
fn write_u32(&mut self, mut n: u32) -> Result<()> {
loop {
let byte = (n as u8) & 0x7f;
n >>= 7;
if n != 0 {
self.write_u8(0b1_0000000 | byte)?;
} else {
self.write_u8(byte)?;
break;
}
}
Ok(())
}
fn write_i24(&mut self, n: i32) -> Result<()> {
// TODO: Verify n fits in 24-bits.
self.write_u8(((n >> 16) & 0xff) as u8)?;
self.write_u8(((n >> 8) & 0xff) as u8)?;
self.write_u8((n & 0xff) as u8)?;
Ok(())
}
fn write_i32(&mut self, mut n: i32) -> Result<()> {
loop {
let byte = (n as u8) & 0x7f;
n >>= 7;
if n != 0 && n != -1 {
self.write_u8(0b1_0000000 | byte)?;
} else {
self.write_u8(byte)?;
break;
}
}
Ok(())
}
fn write_index<T>(&mut self, i: &Index<T>) -> Result<()> {
self.write_u30(i.0)
}
fn write_string(&mut self, s: &str) -> Result<()> {
self.write_u30(s.len() as u32)?;
self.inner.write_all(s.as_bytes())?;
Ok(())
}
fn write_constant_pool(&mut self, constant_pool: &ConstantPool) -> Result<()> {
if !constant_pool.ints.is_empty() {
self.write_u30(constant_pool.ints.len() as u32 + 1)?;
for n in &constant_pool.ints {
self.write_i32(*n)?;
}
} else {
self.write_u32(0)?;
}
if !constant_pool.uints.is_empty() {
self.write_u30(constant_pool.uints.len() as u32 + 1)?;
for n in &constant_pool.uints {
self.write_u32(*n)?;
}
} else {
self.write_u30(0)?;
}
if !constant_pool.doubles.is_empty() {
self.write_u30(constant_pool.doubles.len() as u32 + 1)?;
for n in &constant_pool.doubles {
self.write_f64(*n)?;
}
} else {
self.write_u32(0)?;
}
if !constant_pool.strings.is_empty() {
self.write_u30(constant_pool.strings.len() as u32 + 1)?;
for s in &constant_pool.strings {
self.write_string(s)?;
}
} else {
self.write_u32(0)?;
}
if !constant_pool.namespaces.is_empty() {
self.write_u30(constant_pool.namespaces.len() as u32 + 1)?;
for namespace in &constant_pool.namespaces {
self.write_namespace(namespace)?;
}
} else {
self.write_u32(0)?;
}
if !constant_pool.namespace_sets.is_empty() {
self.write_u30(constant_pool.namespace_sets.len() as u32 + 1)?;
for namespace_set in &constant_pool.namespace_sets {
self.write_namespace_set(namespace_set)?;
}
} else {
self.write_u32(0)?;
}
if !constant_pool.multinames.is_empty() {
self.write_u30(constant_pool.multinames.len() as u32 + 1)?;
for multiname in &constant_pool.multinames {
self.write_multiname(multiname)?;
}
} else {
self.write_u32(0)?;
}
Ok(())
}
fn write_namespace(&mut self, namespace: &Namespace) -> Result<()> {
match *namespace {
Namespace::Namespace(ref name) => {
self.write_u8(0x08)?;
self.write_index(name)?;
}
Namespace::Package(ref name) => {
self.write_u8(0x16)?;
self.write_index(name)?;
}
Namespace::PackageInternal(ref name) => {
self.write_u8(0x17)?;
self.write_index(name)?;
}
Namespace::Protected(ref name) => {
self.write_u8(0x18)?;
self.write_index(name)?;
}
Namespace::Explicit(ref name) => {
self.write_u8(0x19)?;
self.write_index(name)?;
}
Namespace::StaticProtected(ref name) => {
self.write_u8(0x1a)?;
self.write_index(name)?;
}
Namespace::Private(ref name) => {
self.write_u8(0x05)?;
self.write_index(name)?;
}
}
Ok(())
}
fn write_namespace_set(&mut self, namespace_set: &[Index<Namespace>]) -> Result<()> {
self.write_u30(namespace_set.len() as u32)?;
for i in namespace_set {
self.write_index(i)?;
}
Ok(())
}
fn write_multiname(&mut self, multiname: &Multiname) -> Result<()> {
match *multiname {
Multiname::QName {
ref namespace,
ref name,
} => {
self.write_u8(0x07)?;
self.write_index(namespace)?;
self.write_index(name)?;
}
Multiname::QNameA {
ref namespace,
ref name,
} => {
self.write_u8(0x0d)?;
self.write_index(namespace)?;
self.write_index(name)?;
}
Multiname::RTQName { ref name } => {
self.write_u8(0x0f)?;
self.write_index(name)?;
}
Multiname::RTQNameA { ref name } => {
self.write_u8(0x10)?;
self.write_index(name)?;
}
Multiname::RTQNameL => {
self.write_u8(0x11)?;
}
Multiname::RTQNameLA => {
self.write_u8(0x12)?;
}
Multiname::Multiname {
ref namespace_set,
ref name,
} => {
self.write_u8(0x09)?;
self.write_index(name)?;
self.write_index(namespace_set)?;
}
Multiname::MultinameA {
ref namespace_set,
ref name,
} => {
self.write_u8(0x0e)?;
self.write_index(name)?;
self.write_index(namespace_set)?;
}
Multiname::MultinameL { ref namespace_set } => {
self.write_u8(0x1b)?;
self.write_index(namespace_set)?;
}
Multiname::MultinameLA { ref namespace_set } => {
self.write_u8(0x1c)?;
self.write_index(namespace_set)?;
}
}
Ok(())
}
fn write_method(&mut self, method: &Method) -> Result<()> {
self.write_u8(method.params.len() as u8)?;
self.write_index(&method.return_type)?;
let mut num_optional_params = 0;
let mut has_param_names = false;
for param in &method.params {
self.write_index(&param.kind)?;
if param.default_value.is_some() {
num_optional_params += 1;
}
if param.name.is_some() {
has_param_names = true;
}
}
self.write_index(&method.name)?;
self.write_u8(
if has_param_names { 0x80 } else { 0 }
| if method.needs_dxns { 0x40 } else { 0 }
| if num_optional_params > 0 { 0x08 } else { 0 }
| if method.needs_rest { 0x04 } else { 0 }
| if method.needs_activation { 0x02 } else { 0 }
| if method.needs_arguments_object {
0x01
} else {
0
},
)?;
if num_optional_params > 0 {
self.write_u30(num_optional_params)?;
let num_required = method.params.len() - num_optional_params as usize;
for param in method.params.iter().skip(num_required) {
if let Some(ref value) = param.default_value {
self.write_constant_value(value)?;
}
}
}
if has_param_names {
for param in &method.params {
if let Some(ref name) = param.name {
self.write_index(name)?;
}
}
}
Ok(())
}
fn write_constant_value(&mut self, value: &DefaultValue) -> Result<()> {
let (index, kind) = match *value {
DefaultValue::Undefined => (0, 0x00),
DefaultValue::String(ref i) => (i.as_u30(), 0x01),
DefaultValue::Int(ref i) => (i.as_u30(), 0x03),
DefaultValue::Uint(ref i) => (i.as_u30(), 0x04),
DefaultValue::Private(ref i) => (i.as_u30(), 0x05),
DefaultValue::Double(ref i) => (i.as_u30(), 0x06),
DefaultValue::Namespace(ref i) => (i.as_u30(), 0x08),
DefaultValue::False => (0, 0x0a),
DefaultValue::True => (0, 0x0b),
DefaultValue::Null => (0, 0x0c),
DefaultValue::Package(ref i) => (i.as_u30(), 0x16),
DefaultValue::PackageInternal(ref i) => (i.as_u30(), 0x17),
DefaultValue::Protected(ref i) => (i.as_u30(), 0x18),
DefaultValue::Explicit(ref i) => (i.as_u30(), 0x19),
DefaultValue::StaticProtected(ref i) => (i.as_u30(), 0x1a),
};
self.write_u30(index)?;
self.write_u8(kind)?;
Ok(())
}
fn write_optional_value(&mut self, value: &Option<DefaultValue>) -> Result<()> {
match *value {
None => self.write_u30(0)?,
Some(ref value) => {
let (index, kind) = match *value {
DefaultValue::Undefined => (0, 0x00),
DefaultValue::String(ref i) => (i.as_u30(), 0x01),
DefaultValue::Int(ref i) => (i.as_u30(), 0x03),
DefaultValue::Uint(ref i) => (i.as_u30(), 0x04),
DefaultValue::Private(ref i) => (i.as_u30(), 0x05),
DefaultValue::Double(ref i) => (i.as_u30(), 0x06),
DefaultValue::Namespace(ref i) => (i.as_u30(), 0x08),
DefaultValue::False => (0, 0x0a),
DefaultValue::True => (0, 0x0b),
DefaultValue::Null => (0, 0x0c),
DefaultValue::Package(ref i) => (i.as_u30(), 0x16),
DefaultValue::PackageInternal(ref i) => (i.as_u30(), 0x17),
DefaultValue::Protected(ref i) => (i.as_u30(), 0x18),
DefaultValue::Explicit(ref i) => (i.as_u30(), 0x19),
DefaultValue::StaticProtected(ref i) => (i.as_u30(), 0x1a),
};
self.write_u30(index)?;
self.write_u8(kind)?;
}
}
Ok(())
}
fn write_metadata(&mut self, metadata: &Metadata) -> Result<()> {
self.write_index(&metadata.name)?;
self.write_u30(metadata.items.len() as u32)?;
for item in &metadata.items {
self.write_index(&item.key)?;
self.write_index(&item.value)?;
}
Ok(())
}
fn write_instance(&mut self, instance: &Instance) -> Result<()> {
self.write_index(&instance.name)?;
self.write_index(&instance.super_name)?;
self.write_u8(
if instance.protected_namespace.is_some() {
0x08
} else {
0
} | if instance.is_interface { 0x04 } else { 0 }
| if instance.is_final { 0x02 } else { 0 }
| if instance.is_sealed { 0x01 } else { 0 },
)?;
if let Some(ref namespace) = instance.protected_namespace {
self.write_index(namespace)?;
}
self.write_u30(instance.interfaces.len() as u32)?;
for interface in &instance.interfaces {
self.write_index(interface)?;
}
self.write_index(&instance.init_method)?;
self.write_u30(instance.traits.len() as u32)?;
for t in &instance.traits {
self.write_trait(t)?;
}
Ok(())
}
fn write_class(&mut self, class: &Class) -> Result<()> {
self.write_index(&class.init_method)?;
self.write_u30(class.traits.len() as u32)?;
for t in &class.traits {
self.write_trait(t)?;
}
Ok(())
}
fn write_script(&mut self, script: &Script) -> Result<()> {
self.write_index(&script.init_method)?;
self.write_u30(script.traits.len() as u32)?;
for t in &script.traits {
self.write_trait(t)?;
}
Ok(())
}
fn write_trait(&mut self, t: &Trait) -> Result<()> {
self.write_index(&t.name)?;
let flags = if !t.metadata.is_empty() {
0b0100_0000
} else {
0
} | if t.is_override { 0b0010_0000 } else { 0 }
| if t.is_final { 0b0001_0000 } else { 0 };
match t.kind {
TraitKind::Slot {
slot_id,
ref type_name,
ref value,
} => {
self.write_u8(flags)?;
self.write_u30(slot_id)?;
self.write_index(type_name)?;
self.write_optional_value(value)?;
}
TraitKind::Method {
disp_id,
ref method,
} => {
self.write_u8(flags | 1)?;
self.write_u30(disp_id)?;
self.write_index(method)?;
}
TraitKind::Getter {
disp_id,
ref method,
} => {
self.write_u8(flags | 2)?;
self.write_u30(disp_id)?;
self.write_index(method)?;
}
TraitKind::Setter {
disp_id,
ref method,
} => {
self.write_u8(flags | 3)?;
self.write_u30(disp_id)?;
self.write_index(method)?;
}
TraitKind::Class { slot_id, ref class } => {
self.write_u8(flags | 4)?;
self.write_u30(slot_id)?;
self.write_index(class)?;
}
TraitKind::Function {
slot_id,
ref function,
} => {
self.write_u8(flags | 5)?;
self.write_u30(slot_id)?;
self.write_index(function)?;
}
TraitKind::Const {
slot_id,
ref type_name,
ref value,
} => {
self.write_u8(flags | 6)?;
self.write_u30(slot_id)?;
self.write_index(type_name)?;
self.write_optional_value(value)?;
}
}
if !t.metadata.is_empty() {
self.write_u30(t.metadata.len() as u32)?;
for metadata in &t.metadata {
self.write_index(metadata)?;
}
}
Ok(())
}
fn write_method_body(&mut self, method_body: &MethodBody) -> Result<()> {
self.write_index(&method_body.method)?;
self.write_u30(method_body.max_stack)?;
self.write_u30(method_body.num_locals)?;
self.write_u30(method_body.init_scope_depth)?;
self.write_u30(method_body.max_scope_depth)?;
let mut buf = Vec::with_capacity(method_body.code.len());
{
let mut writer = Writer::new(&mut buf);
for op in &method_body.code {
writer.write_op(op)?;
}
}
self.write_u30(buf.len() as u32)?;
self.inner.write_all(&buf)?;
self.write_u30(method_body.exceptions.len() as u32)?;
for exception in &method_body.exceptions {
self.write_exception(exception)?;
}
self.write_u30(method_body.traits.len() as u32)?;
for t in &method_body.traits {
self.write_trait(t)?;
}
Ok(())
}
fn write_exception(&mut self, exception: &Exception) -> Result<()> {
self.write_u30(exception.from_offset)?;
self.write_u30(exception.to_offset)?;
self.write_u30(exception.target_offset)?;
self.write_index(&exception.type_name)?;
self.write_index(&exception.variable_name)?;
Ok(())
}
fn write_op(&mut self, op: &Op) -> Result<()> {
match *op {
Op::Add => self.write_opcode(OpCode::Add)?,
Op::AddI => self.write_opcode(OpCode::AddI)?,
Op::AsType { ref type_name } => {
self.write_opcode(OpCode::AsType)?;
self.write_index(type_name)?;
}
Op::AsTypeLate => self.write_opcode(OpCode::AsTypeLate)?,
Op::BitAnd => self.write_opcode(OpCode::BitAnd)?,
Op::BitNot => self.write_opcode(OpCode::BitNot)?,
Op::BitOr => self.write_opcode(OpCode::BitOr)?,
Op::BitXor => self.write_opcode(OpCode::BitXor)?,
Op::Call { num_args } => {
self.write_opcode(OpCode::Call)?;
self.write_u30(num_args)?;
}
Op::CallMethod {
ref index,
num_args,
} => {
self.write_opcode(OpCode::CallMethod)?;
self.write_index(index)?;
self.write_u30(num_args)?;
}
Op::CallProperty {
ref index,
num_args,
} => {
self.write_opcode(OpCode::CallProperty)?;
self.write_index(index)?;
self.write_u30(num_args)?;
}
Op::CallPropLex {
ref index,
num_args,
} => {
self.write_opcode(OpCode::CallPropLex)?;
self.write_index(index)?;
self.write_u30(num_args)?;
}
Op::CallPropVoid {
ref index,
num_args,
} => {
self.write_opcode(OpCode::CallPropVoid)?;
self.write_index(index)?;
self.write_u30(num_args)?;
}
Op::CallStatic {
ref index,
num_args,
} => {
self.write_opcode(OpCode::CallStatic)?;
self.write_index(index)?;
self.write_u30(num_args)?;
}
Op::CallSuper {
ref index,
num_args,
} => {
self.write_opcode(OpCode::CallSuper)?;
self.write_index(index)?;
self.write_u30(num_args)?;
}
Op::CallSuperVoid {
ref index,
num_args,
} => {
self.write_opcode(OpCode::CallSuperVoid)?;
self.write_index(index)?;
self.write_u30(num_args)?;
}
Op::CheckFilter => self.write_opcode(OpCode::CheckFilter)?,
Op::Coerce { ref index } => {
self.write_opcode(OpCode::Coerce)?;
self.write_index(index)?;
}
Op::CoerceA => self.write_opcode(OpCode::CoerceA)?,
Op::CoerceS => self.write_opcode(OpCode::CoerceS)?,
Op::Construct { num_args } => {
self.write_opcode(OpCode::Construct)?;
self.write_u30(num_args)?;
}
Op::ConstructProp {
ref index,
num_args,
} => {
self.write_opcode(OpCode::ConstructProp)?;
self.write_index(index)?;
self.write_u30(num_args)?;
}
Op::ConstructSuper { num_args } => {
self.write_opcode(OpCode::ConstructSuper)?;
self.write_u30(num_args)?;
}
Op::ConvertB => self.write_opcode(OpCode::ConvertB)?,
Op::ConvertD => self.write_opcode(OpCode::ConvertD)?,
Op::ConvertI => self.write_opcode(OpCode::ConvertI)?,
Op::ConvertO => self.write_opcode(OpCode::ConvertO)?,
Op::ConvertS => self.write_opcode(OpCode::ConvertS)?,
Op::ConvertU => self.write_opcode(OpCode::ConvertU)?,
Op::Debug {
is_local_register,
ref register_name,
register,
} => {
self.write_opcode(OpCode::Debug)?;
self.write_u8(is_local_register as u8)?;
self.write_index(register_name)?;
self.write_u8(register)?;
self.write_u30(0)?; // Unused
}
Op::DebugFile { ref file_name } => {
self.write_opcode(OpCode::DebugFile)?;
self.write_index(file_name)?;
}
Op::DebugLine { line_num } => {
self.write_opcode(OpCode::DebugLine)?;
self.write_u30(line_num)?;
}
Op::DecLocal { index } => {
self.write_opcode(OpCode::DecLocal)?;
self.write_u30(index)?;
}
Op::DecLocalI { index } => {
self.write_opcode(OpCode::DecLocalI)?;
self.write_u30(index)?;
}
Op::Decrement => self.write_opcode(OpCode::Decrement)?,
Op::DecrementI => self.write_opcode(OpCode::DecrementI)?,
Op::DeleteProperty { ref index } => {
self.write_opcode(OpCode::DeleteProperty)?;
self.write_index(index)?;
}
Op::Divide => self.write_opcode(OpCode::Divide)?,
Op::Dup => self.write_opcode(OpCode::Dup)?,
Op::Dxns { ref index } => {
self.write_opcode(OpCode::Dxns)?;
self.write_index(index)?;
}
Op::DxnsLate => self.write_opcode(OpCode::DxnsLate)?,
Op::Equals => self.write_opcode(OpCode::Equals)?,
Op::EscXAttr => self.write_opcode(OpCode::EscXAttr)?,
Op::EscXElem => self.write_opcode(OpCode::EscXElem)?,
Op::FindProperty { ref index } => {
self.write_opcode(OpCode::FindProperty)?;
self.write_index(index)?;
}
Op::FindPropStrict { ref index } => {
self.write_opcode(OpCode::FindPropStrict)?;
self.write_index(index)?;
}
Op::GetDescendants { ref index } => {
self.write_opcode(OpCode::GetDescendants)?;
self.write_index(index)?;
}
Op::GetGlobalScope => self.write_opcode(OpCode::GetGlobalScope)?,
Op::GetGlobalSlot { index } => {
self.write_opcode(OpCode::GetGlobalSlot)?;
self.write_u30(index)?;
}
Op::GetLex { ref index } => {
self.write_opcode(OpCode::GetLex)?;
self.write_index(index)?;
}
Op::GetLocal { index } => match index {
0 => self.write_opcode(OpCode::GetLocal0)?,
1 => self.write_opcode(OpCode::GetLocal1)?,
2 => self.write_opcode(OpCode::GetLocal2)?,
3 => self.write_opcode(OpCode::GetLocal3)?,
_ => {
self.write_opcode(OpCode::GetLocal)?;
self.write_u30(index)?;
}
},
Op::GetProperty { ref index } => {
self.write_opcode(OpCode::GetProperty)?;
self.write_index(index)?;
}
Op::GetScopeObject { index } => {
self.write_opcode(OpCode::GetScopeObject)?;
self.write_u8(index)?;
}
Op::GetSlot { index } => {
self.write_opcode(OpCode::GetSlot)?;
self.write_u30(index)?;
}
Op::GetSuper { ref index } => {
self.write_opcode(OpCode::GetSuper)?;
self.write_index(index)?;
}
Op::GreaterEquals => self.write_opcode(OpCode::GreaterEquals)?,
Op::GreaterThan => self.write_opcode(OpCode::GreaterThan)?,
Op::HasNext => self.write_opcode(OpCode::HasNext)?,
Op::HasNext2 {
object_register,
index_register,
} => {
self.write_opcode(OpCode::HasNext2)?;
self.write_u30(object_register)?;
self.write_u30(index_register)?;
}
Op::IfEq { offset } => {
self.write_opcode(OpCode::IfEq)?;
self.write_i24(offset)?;
}
Op::IfFalse { offset } => {
self.write_opcode(OpCode::IfFalse)?;
self.write_i24(offset)?;
}
Op::IfGe { offset } => {
self.write_opcode(OpCode::IfGe)?;
self.write_i24(offset)?;
}
Op::IfGt { offset } => {
self.write_opcode(OpCode::IfGt)?;
self.write_i24(offset)?;
}
Op::IfLe { offset } => {
self.write_opcode(OpCode::IfLe)?;
self.write_i24(offset)?;
}
Op::IfLt { offset } => {
self.write_opcode(OpCode::IfLt)?;
self.write_i24(offset)?;
}
Op::IfNge { offset } => {
self.write_opcode(OpCode::IfNge)?;
self.write_i24(offset)?;
}
Op::IfNgt { offset } => {
self.write_opcode(OpCode::IfNgt)?;
self.write_i24(offset)?;
}
Op::IfNle { offset } => {
self.write_opcode(OpCode::IfNle)?;
self.write_i24(offset)?;
}
Op::IfNlt { offset } => {
self.write_opcode(OpCode::IfNlt)?;
self.write_i24(offset)?;
}
Op::IfNe { offset } => {
self.write_opcode(OpCode::IfNe)?;
self.write_i24(offset)?;
}
Op::IfStrictEq { offset } => {
self.write_opcode(OpCode::IfStrictEq)?;
self.write_i24(offset)?;
}
Op::IfStrictNe { offset } => {
self.write_opcode(OpCode::IfStrictNe)?;
self.write_i24(offset)?;
}
Op::IfTrue { offset } => {
self.write_opcode(OpCode::IfTrue)?;
self.write_i24(offset)?;
}
Op::In => self.write_opcode(OpCode::In)?,
Op::IncLocal { index } => {
self.write_opcode(OpCode::IncLocal)?;
self.write_u30(index)?;
}
Op::IncLocalI { index } => {
self.write_opcode(OpCode::IncLocalI)?;
self.write_u30(index)?;
}
Op::Increment => self.write_opcode(OpCode::Increment)?,
Op::IncrementI => self.write_opcode(OpCode::IncrementI)?,
Op::InitProperty { ref index } => {
self.write_opcode(OpCode::InitProperty)?;
self.write_index(index)?;
}
Op::InstanceOf => self.write_opcode(OpCode::InstanceOf)?,
Op::IsType { ref index } => {
self.write_opcode(OpCode::IsType)?;
self.write_index(index)?;
}
Op::IsTypeLate => self.write_opcode(OpCode::IsTypeLate)?,
Op::Jump { offset } => {
self.write_opcode(OpCode::Jump)?;
self.write_i24(offset)?;
}
Op::Kill { index } => {
self.write_opcode(OpCode::Kill)?;
self.write_u30(index)?;
}
Op::Label => self.write_opcode(OpCode::Label)?,
Op::LessEquals => self.write_opcode(OpCode::LessEquals)?,
Op::LessThan => self.write_opcode(OpCode::LessThan)?,
Op::LookupSwitch {
default_offset,
ref case_offsets,
} => {
self.write_opcode(OpCode::LookupSwitch)?;
self.write_i24(default_offset)?;
self.write_u30(case_offsets.len() as u32 - 1)?;
for offset in case_offsets {
self.write_i24(*offset)?;
}
}
Op::LShift => self.write_opcode(OpCode::LShift)?,
Op::Modulo => self.write_opcode(OpCode::Modulo)?,
Op::Multiply => self.write_opcode(OpCode::Multiply)?,
Op::MultiplyI => self.write_opcode(OpCode::MultiplyI)?,
Op::Negate => self.write_opcode(OpCode::Negate)?,
Op::NegateI => self.write_opcode(OpCode::NegateI)?,
Op::NewActivation => self.write_opcode(OpCode::NewActivation)?,
Op::NewArray { num_args } => {
self.write_opcode(OpCode::NewArray)?;
self.write_u30(num_args)?;
}
Op::NewCatch { ref index } => {
self.write_opcode(OpCode::NewCatch)?;
self.write_index(index)?;
}
Op::NewClass { ref index } => {
self.write_opcode(OpCode::NewClass)?;
self.write_index(index)?;
}
Op::NewFunction { ref index } => {
self.write_opcode(OpCode::NewFunction)?;
self.write_index(index)?;
}
Op::NewObject { num_args } => {
self.write_opcode(OpCode::NewObject)?;
self.write_u30(num_args)?;
}
Op::NextName => self.write_opcode(OpCode::NextName)?,
Op::NextValue => self.write_opcode(OpCode::NextValue)?,
Op::Nop => self.write_opcode(OpCode::Nop)?,
Op::Not => self.write_opcode(OpCode::Not)?,
Op::Pop => self.write_opcode(OpCode::Pop)?,
Op::PopScope => self.write_opcode(OpCode::PopScope)?,
Op::PushByte { value } => {
self.write_opcode(OpCode::PushByte)?;
self.write_u8(value)?;
}
Op::PushDouble { ref value } => {
self.write_opcode(OpCode::PushDouble)?;
self.write_index(value)?;
}
Op::PushFalse => self.write_opcode(OpCode::PushFalse)?,
Op::PushInt { ref value } => {
self.write_opcode(OpCode::PushInt)?;
self.write_index(value)?;
}
Op::PushNamespace { ref value } => {
self.write_opcode(OpCode::PushNamespace)?;
self.write_index(value)?;
}
Op::PushNaN => self.write_opcode(OpCode::PushNaN)?,
Op::PushNull => self.write_opcode(OpCode::PushNull)?,
Op::PushScope => self.write_opcode(OpCode::PushScope)?,
Op::PushShort { value } => {
self.write_opcode(OpCode::PushShort)?;
self.write_u30(value)?;
}
Op::PushString { ref value } => {
self.write_opcode(OpCode::PushString)?;
self.write_index(value)?;
}
Op::PushTrue => self.write_opcode(OpCode::PushTrue)?,
Op::PushUint { ref value } => {
self.write_opcode(OpCode::PushUint)?;
self.write_index(value)?;
}
Op::PushUndefined => self.write_opcode(OpCode::PushUndefined)?,
Op::PushWith => self.write_opcode(OpCode::PushWith)?,
Op::ReturnValue => self.write_opcode(OpCode::ReturnValue)?,
Op::ReturnVoid => self.write_opcode(OpCode::ReturnVoid)?,
Op::RShift => self.write_opcode(OpCode::RShift)?,
Op::SetLocal { index } => match index {
0 => self.write_opcode(OpCode::SetLocal0)?,
1 => self.write_opcode(OpCode::SetLocal1)?,
2 => self.write_opcode(OpCode::SetLocal2)?,
3 => self.write_opcode(OpCode::SetLocal3)?,
_ => {
self.write_opcode(OpCode::SetLocal)?;
self.write_u30(index)?;
}
},
Op::SetGlobalSlot { index } => {
self.write_opcode(OpCode::SetGlobalSlot)?;
self.write_u30(index)?;
}
Op::SetProperty { ref index } => {
self.write_opcode(OpCode::SetProperty)?;
self.write_index(index)?;
}
Op::SetSlot { index } => {
self.write_opcode(OpCode::SetSlot)?;
self.write_u30(index)?;
}
Op::SetSuper { ref index } => {
self.write_opcode(OpCode::SetSuper)?;
self.write_index(index)?;
}
Op::StrictEquals => self.write_opcode(OpCode::StrictEquals)?,
Op::Subtract => self.write_opcode(OpCode::Subtract)?,
Op::SubtractI => self.write_opcode(OpCode::SubtractI)?,
Op::Swap => self.write_opcode(OpCode::Swap)?,
Op::Throw => self.write_opcode(OpCode::Throw)?,
Op::TypeOf => self.write_opcode(OpCode::TypeOf)?,
Op::URShift => self.write_opcode(OpCode::URShift)?,
};
Ok(())
}
fn write_opcode(&mut self, opcode: OpCode) -> Result<()> {
self.write_u8(opcode as u8)
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::test_data;
#[test]
fn write_abc() {
for (_, abc_file, bytes) in test_data::avm2_tests() {
let mut out = vec![];
{
let mut writer = Writer::new(&mut out);
writer.write(abc_file).unwrap();
}
if bytes != out {
// Failed, result doesn't match.
panic!(
"Incorrectly written ABC.\nWritten:\n{:?}\n\nExpected:\n{:?}",
out, bytes
);
}
}
}
}

35
swf/src/lib.rs Normal file
View File

@ -0,0 +1,35 @@
//! # swf-rs
//!
//! Library for reading and writing Adobe Flash SWF files.
//!
//! # Organization
//!
//! This library consits of a `read` module for decoding SWF data, and a `write` library for
//! writing SWF data.
extern crate byteorder;
#[cfg(feature = "flate2")]
extern crate flate2;
#[cfg(feature = "libflate")]
extern crate libflate;
#[macro_use]
extern crate num_derive;
extern crate num_traits;
#[cfg(feature = "lzma-support")]
extern crate xz2;
pub mod avm1;
pub mod avm2;
pub mod read;
mod tag_code;
mod types;
pub mod write;
#[cfg(test)]
mod test_data;
/// Reexports
pub use read::{read_swf, read_swf_header};
pub use tag_code::TagCode;
pub use types::*;
pub use write::write_swf;

3158
swf/src/read.rs Normal file

File diff suppressed because it is too large Load Diff

98
swf/src/tag_code.rs Normal file
View File

@ -0,0 +1,98 @@
#![allow(clippy::useless_attribute)]
#[allow(dead_code)]
#[derive(Debug, PartialEq, Clone, Copy, FromPrimitive)]
pub enum TagCode {
End = 0,
ShowFrame = 1,
DefineShape = 2,
PlaceObject = 4,
RemoveObject = 5,
DefineBits = 6,
DefineButton = 7,
JpegTables = 8,
SetBackgroundColor = 9,
DefineFont = 10,
DefineText = 11,
DoAction = 12,
DefineFontInfo = 13,
DefineSound = 14,
StartSound = 15,
DefineButtonSound = 17,
SoundStreamHead = 18,
SoundStreamBlock = 19,
DefineBitsLossless = 20,
DefineBitsJpeg2 = 21,
DefineShape2 = 22,
DefineButtonCxform = 23,
Protect = 24,
PlaceObject2 = 26,
RemoveObject2 = 28,
DefineShape3 = 32,
DefineText2 = 33,
DefineButton2 = 34,
DefineBitsJpeg3 = 35,
DefineBitsLossless2 = 36,
DefineEditText = 37,
DefineSprite = 39,
ProductInfo = 41,
FrameLabel = 43,
SoundStreamHead2 = 45,
DefineMorphShape = 46,
DefineFont2 = 48,
ExportAssets = 56,
ImportAssets = 57,
EnableDebugger = 58,
DoInitAction = 59,
DefineVideoStream = 60,
VideoFrame = 61,
DefineFontInfo2 = 62,
DebugId = 63,
EnableDebugger2 = 64,
ScriptLimits = 65,
SetTabIndex = 66,
FileAttributes = 69,
PlaceObject3 = 70,
ImportAssets2 = 71,
DefineFontAlignZones = 73,
CsmTextSettings = 74,
DefineFont3 = 75,
SymbolClass = 76,
Metadata = 77,
DefineScalingGrid = 78,
DoAbc = 82,
DefineShape4 = 83,
DefineMorphShape2 = 84,
DefineSceneAndFrameLabelData = 86,
DefineBinaryData = 87,
DefineFontName = 88,
StartSound2 = 89,
DefineBitsJpeg4 = 90,
DefineFont4 = 91,
EnableTelemetry = 93,
PlaceObject4 = 94,
}
impl TagCode {
pub fn from_u16(n: u16) -> Option<Self> {
num_traits::FromPrimitive::from_u16(n)
}
}

2650
swf/src/test_data.rs Normal file

File diff suppressed because it is too large Load Diff

1109
swf/src/types.rs Normal file

File diff suppressed because it is too large Load Diff

3102
swf/src/write.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
var document = fl.getDocumentDOM();
if(document) {
var element = document.getTimeline().layers[0].frames[0].elements[0];
if(element) {
element.setPersistentData("test", "string", "Testing!");
element.setPublishPersistentData("test", "_EMBED_SWF_", true);
document.setPublishDocumentData("_EMBED_SWF_", true);
alert("Added PlaceObject4 data for clip.");
} else {
alert("Please select a symbol in the library.");
}
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,6 @@
package {
public function Avm2Test():void {
trace("Test");
}
Avm2Test();
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,7 @@
package {
import flash.utils.ByteArray;
[Embed(source="embed-data.txt", mimeType="application/octet-stream")]
public class EmbedData extends ByteArray {
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More