parity-wasm-0.41.0/.editorconfig 0100644 0000765 0000024 00000000247 13447427055 0014763 0 ustar 00 0000000 0000000 root = true
[*]
indent_style=tab
indent_size=tab
tab_width=4
end_of_line=lf
charset=utf-8
trim_trailing_whitespace=true
max_line_length=120
insert_final_newline=true
parity-wasm-0.41.0/.gitignore 0100644 0000765 0000024 00000000061 13447427055 0014270 0 ustar 00 0000000 0000000 target
Cargo.lock
.vscode
**/.DS_Store
rls
.idea
parity-wasm-0.41.0/.gitmodules 0100644 0000765 0000024 00000000150 13447427055 0014454 0 ustar 00 0000000 0000000 [submodule "spec/testsuite"]
path = spec/testsuite
url = https://github.com/WebAssembly/testsuite.git
parity-wasm-0.41.0/.travis.yml 0100644 0000765 0000024 00000003250 13526456013 0014406 0 ustar 00 0000000 0000000 dist: trusty
language: rust
rust:
- nightly
- stable
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-8
- g++-8
- cmake
script:
- export CC=/usr/bin/gcc-8
- export CXX=/usr/bin/g++-8
- if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then cargo build --no-default-features;
fi
# Check with all features
- cargo check --features simd,atomics,sign_ext,bulk
- cargo build --release --verbose
- cargo test --release --verbose
- cargo test --release --manifest-path=spec/Cargo.toml
- cargo run --example bench-decoder --release
after_success: |-
[ $TRAVIS_BRANCH = master ] &&
[ $TRAVIS_PULL_REQUEST = false ] &&
cargo doc \
&& echo '' > target/doc/index.html && \
sudo pip install ghp-import && \
ghp-import -n target/doc && \
git push -qf https://${TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
env:
global:
- RUSTFLAGS=--cfg=slow_assertions
- CC=/usr/bin/gcc-8
- CXX=/usr/bin/g++-8
- secure: n+t7rAF58avDd1LcmNmEAN/0zlkZlSreg0EOYEz+BHY/ftUq/MWaA2Efz6fGcsZnLjFUDVZdQz/eiD6JkCthf3WBGZEyAbJuPdjXf1UG6857l5XvUkLrixXrE+gSx0y7jxp+z5Hh+wsw8AuGtRh/023VHir3+hfZU5sMRAUng3iuAQqVgzcwFPIpNUKd7RZ0T2tB+VoAPDsptdHi2HKHe9UMQmnT3z2zenC+oSaEtG421A/QNiZh7G5sUJWCmBtAnkU+Kr2R2YQZOvbr4wyHjluM/UiCAnApM5efQwqel+4HNPbbSfg2WCX4BE3gV+Hxa3yRcRX8IsgsYw13racppws3JYXPXMe8PWVu9vnVWyfudBp/kChP2VWejrPLMp5+H++4hE8G4wfygk6G0jOPd+9cG/rYAk25oRU2BvX8aPdzbLRqGtCSGHkXMRjtvmPoaajspHZLLqG4Ka839pSvBzGSQOJtQl4FqR9EP4PIfmrTvMQuFvBNGNCT3AhoQlDFoNHSpPLJqRSSS/duRzJSGe0Yw7v1h2Y85Lvx8xkHfjPGKeiZyBbqkCggxaS1qfggdw9XiMR9mijbSng3o92QDGX9QLbnPzgK7Gk0MHRdthjrKUCzhyE8rJiJefXYOGYF8YRigL4U2lHvoHrw+iOdGX3ZxHgpgvU2F5txctK3MqU=
parity-wasm-0.41.0/Cargo.toml.orig 0100644 0000765 0000024 00000002170 13556562052 0015170 0 ustar 00 0000000 0000000 [package]
name = "parity-wasm"
version = "0.41.0"
authors = ["Nikolay Volf ", "Svyatoslav Nikolsky ", "Sergey Shulepov "]
license = "MIT/Apache-2.0"
readme = "README.md"
repository = "https://github.com/paritytech/parity-wasm"
homepage = "https://github.com/paritytech/parity-wasm"
documentation = "https://paritytech.github.io/parity-wasm/parity_wasm/"
description = "WebAssembly low-level format library"
keywords = ["wasm", "webassembly", "bytecode", "serde", "interpreter"]
categories = ["wasm", "parser-implementations"]
exclude = [ "res/*", "spec/*" ]
edition = "2018"
[dev-dependencies]
time = "0.1"
[features]
default = ["std"]
std = []
#
# Features for enabling non-MVP proposals.
# These features should be tested as part of Travis CI build.
#
# Atomics aka threading.
# https://github.com/webassembly/threads/
atomics = []
# SIMD
# https://github.com/WebAssembly/simd/
simd = []
# Sign-extension operators
# https://github.com/WebAssembly/sign-extension-ops/
sign_ext = []
# Bulk-memory operators
# https://github.com/WebAssembly/bulk-memory-operations/
bulk = []
parity-wasm-0.41.0/Cargo.toml 0000644 00000002406 00000000000 0011432 0 ustar 00 # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
edition = "2018"
name = "parity-wasm"
version = "0.41.0"
authors = ["Nikolay Volf ", "Svyatoslav Nikolsky ", "Sergey Shulepov "]
exclude = ["res/*", "spec/*"]
description = "WebAssembly low-level format library"
homepage = "https://github.com/paritytech/parity-wasm"
documentation = "https://paritytech.github.io/parity-wasm/parity_wasm/"
readme = "README.md"
keywords = ["wasm", "webassembly", "bytecode", "serde", "interpreter"]
categories = ["wasm", "parser-implementations"]
license = "MIT/Apache-2.0"
repository = "https://github.com/paritytech/parity-wasm"
[dev-dependencies.time]
version = "0.1"
[features]
atomics = []
bulk = []
default = ["std"]
sign_ext = []
simd = []
std = []
parity-wasm-0.41.0/examples/bench-decoder.rs 0100644 0000765 0000024 00000001415 13447427055 0017152 0 ustar 00 0000000 0000000 extern crate parity_wasm;
extern crate time;
use std::fs;
fn rate(file_name: &'static str, iterations: u64) {
let file_size = fs::metadata(file_name).expect(&format!("{} to exist", file_name)).len();
let mut total_ms = 0;
for _ in 0..iterations {
let start = time::PreciseTime::now();
let _module = parity_wasm::deserialize_file(file_name);
let end = time::PreciseTime::now();
total_ms += start.to(end).num_milliseconds();
}
println!("Rate for {}: {} MB/s", file_name,
(file_size as f64 * iterations as f64 / (1024*1024) as f64) / // total work megabytes
(total_ms as f64 / 1000f64) // total seconds
);
}
fn main() {
rate("./res/cases/v1/clang.wasm", 10);
rate("./res/cases/v1/hello.wasm", 100);
rate("./res/cases/v1/with_names.wasm", 100);
} parity-wasm-0.41.0/examples/build.rs 0100644 0000765 0000024 00000003124 13447427055 0015566 0 ustar 00 0000000 0000000 // Simple example of how to use parity-wasm builder api.
// Builder api introduced as a method for fast generation of
// different small wasm modules.
extern crate parity_wasm;
use std::env;
use parity_wasm::builder;
use parity_wasm::elements;
fn main() {
// Example binary accepts one parameter which is the output file
// where generated wasm module will be written at the end of execution
let args = env::args().collect::>();
if args.len() != 2 {
println!("Usage: {} output_file.wasm", args[0]);
return;
}
// Main entry for the builder api is the module function
// It returns empty module builder structure which can be further
// appended with various wasm artefacts
let module = builder::module()
// Here we append function to the builder
// function() function returns a function builder attached
// to the module builder.
.function()
// We describe signature for the function via signature()
// function. In our simple example it's just one input
// argument of type 'i32' without return value
.signature().with_param(elements::ValueType::I32).build()
// body() without any further arguments means that the body
// of the function will be empty
.body().build()
// This is the end of the function builder. When `build()` is
// invoked, function builder returns original module builder
// from which it was invoked
.build()
// And finally we finish our module builder to produce actual
// wasm module.
.build();
// Module structure can be serialzed to produce a valid wasm file
parity_wasm::serialize_to_file(&args[1], module).unwrap();
} parity-wasm-0.41.0/examples/data.rs 0100644 0000765 0000024 00000002776 13447427055 0015414 0 ustar 00 0000000 0000000 // This short example provides the utility to inspect
// wasm file data section.
extern crate parity_wasm;
use std::env;
fn main() {
// Example executable takes one argument which must
// refernce the existing file with a valid wasm module
let args = env::args().collect::>();
if args.len() != 2 {
println!("Usage: {} somefile.wasm", args[0]);
return;
}
// Here we load module using dedicated for this purpose
// `deserialize_file` function (which works only with modules)
let module = parity_wasm::deserialize_file(&args[1]).expect("Failed to load module");
// We query module for data section. Note that not every valid
// wasm module must contain a data section. So in case the provided
// module does not contain data section, we panic with an error
let data_section = module.data_section().expect("no data section in module");
// Printing the total count of data segments
println!("Data segments: {}", data_section.entries().len());
let mut index = 0;
for entry in data_section.entries() {
// Printing the details info of each data segment
// see `elements::DataSegment` for more properties
// you can query
println!(" Entry #{}", index);
// This shows the initialization member of data segment
// (expression which must resolve in the linear memory location).
if let Some(offset) = entry.offset() {
println!(" init: {}", offset.code()[0]);
}
// This shows the total length of the data segment in bytes.
println!(" size: {}", entry.value().len());
index += 1;
}
}
parity-wasm-0.41.0/examples/exports.rs 0100644 0000765 0000024 00000006441 13447427055 0016200 0 ustar 00 0000000 0000000 // This examples allow to query all function exports of the
// provided wasm module
extern crate parity_wasm;
use std::env::args;
use parity_wasm::elements::{Internal, External, Type, FunctionType, Module};
// Auxillary function to resolve function type (signature) given it's callable index
fn type_by_index(module: &Module, index: usize) -> FunctionType {
// Demand that function and type section exist. Otherwise, fail with a
// corresponding error.
let function_section = module.function_section().expect("No function section found");
let type_section = module.type_section().expect("No type section found");
// This counts the number of _function_ imports listed by the module, excluding
// the globals, since indexing for actual functions for `call` and `export` purposes
// includes both imported and own functions. So we actualy need the imported function count
// to resolve actual index of the given function in own functions list.
let import_section_len: usize = match module.import_section() {
Some(import) =>
import.entries().iter().filter(|entry| match entry.external() {
&External::Function(_) => true,
_ => false,
}).count(),
None => 0,
};
// Substract the value queried in the previous step from the provided index
// to get own function index from which we can query type next.
let function_index_in_section = index - import_section_len;
// Query the own function given we have it's index
let func_type_ref: usize = function_section.entries()[function_index_in_section].type_ref() as usize;
// Finally, return function type (signature)
match type_section.types()[func_type_ref] {
Type::Function(ref func_type) => func_type.clone(),
}
}
fn main() {
// Example executable takes one argument which must
// refernce the existing file with a valid wasm module
let args: Vec<_> = args().collect();
if args.len() < 2 {
println!("Prints export function names with and their types");
println!("Usage: {} ", args[0]);
return;
}
// Here we load module using dedicated for this purpose
// `deserialize_file` function (which works only with modules)
let module = parity_wasm::deserialize_file(&args[1]).expect("File to be deserialized");
// Query the export section from the loaded module. Note that not every
// wasm module obliged to contain export section. So in case there is no
// any export section, we panic with the corresponding error.
let export_section = module.export_section().expect("No export section found");
// Process all exports, leaving only those which reference the internal function
// of the wasm module
let exports: Vec = export_section.entries().iter()
.filter_map(|entry|
// This is match on export variant, which can be function, global,table or memory
// We are interested only in functions for an example
match *entry.internal() {
// Return function export name (return by field() function and it's index)
Internal::Function(index) => Some((entry.field(), index as usize)),
_ => None
})
// Another map to resolve function signature index given it's internal index and return
// the printable string of the export
.map(|(field, index)| format!("{:}: {:?}", field, type_by_index(&module, index).params())).collect();
// Print the result
for export in exports {
println!("{:}", export);
}
}
parity-wasm-0.41.0/examples/info.rs 0100644 0000765 0000024 00000003072 13447427055 0015424 0 ustar 00 0000000 0000000 extern crate parity_wasm;
use std::env;
use parity_wasm::elements::Section;
fn main() {
let args = env::args().collect::>();
if args.len() != 2 {
println!("Usage: {} somefile.wasm", args[0]);
return;
}
let module = parity_wasm::deserialize_file(&args[1]).expect("Failed to load module");
println!("Module sections: {}", module.sections().len());
for section in module.sections() {
match *section {
Section::Import(ref import_section) => {
println!(" Imports: {}", import_section.entries().len());
import_section.entries().iter().map(|e| println!(" {}.{}", e.module(), e.field())).count();
},
Section::Export(ref exports_section) => {
println!(" Exports: {}", exports_section.entries().len());
exports_section.entries().iter().map(|e| println!(" {}", e.field())).count();
},
Section::Function(ref function_section) => {
println!(" Functions: {}", function_section.entries().len());
},
Section::Type(ref type_section) => {
println!(" Types: {}", type_section.types().len());
},
Section::Global(ref globals_section) => {
println!(" Globals: {}", globals_section.entries().len());
},
Section::Table(ref table_section) => {
println!(" Tables: {}", table_section.entries().len());
},
Section::Memory(ref memory_section) => {
println!(" Memories: {}", memory_section.entries().len());
},
Section::Data(ref data_section) if data_section.entries().len() > 0 => {
let data = &data_section.entries()[0];
println!(" Data size: {}", data.value().len());
},
_ => {},
}
}
} parity-wasm-0.41.0/examples/inject.rs 0100644 0000765 0000024 00000002525 13447427055 0015747 0 ustar 00 0000000 0000000 extern crate parity_wasm;
use std::env;
use parity_wasm::elements;
use parity_wasm::builder;
pub fn inject_nop(instructions: &mut elements::Instructions) {
use parity_wasm::elements::Instruction::*;
let instructions = instructions.elements_mut();
let mut position = 0;
loop {
let need_inject = match &instructions[position] {
&Block(_) | &If(_) => true,
_ => false,
};
if need_inject {
instructions.insert(position + 1, Nop);
}
position += 1;
if position >= instructions.len() {
break;
}
}
}
fn main() {
let args = env::args().collect::>();
if args.len() != 3 {
println!("Usage: {} input_file.wasm output_file.wasm", args[0]);
return;
}
let mut module = parity_wasm::deserialize_file(&args[1]).unwrap();
for section in module.sections_mut() {
match section {
&mut elements::Section::Code(ref mut code_section) => {
for ref mut func_body in code_section.bodies_mut() {
inject_nop(func_body.code_mut());
}
},
_ => { }
}
}
let mut build = builder::from_module(module);
let import_sig = build.push_signature(
builder::signature()
.param().i32()
.param().i32()
.return_type().i32()
.build_sig()
);
let build = build.import()
.module("env")
.field("log")
.external().func(import_sig)
.build();
parity_wasm::serialize_to_file(&args[2], build.build()).unwrap();
} parity-wasm-0.41.0/examples/roundtrip.rs 0100644 0000765 0000024 00000001131 13447427055 0016511 0 ustar 00 0000000 0000000 extern crate parity_wasm;
use std::env;
fn main() {
let args = env::args().collect::>();
if args.len() != 3 {
println!("Usage: {} in.wasm out.wasm", args[0]);
return;
}
let module = match parity_wasm::deserialize_file(&args[1])
.expect("Failed to load module")
.parse_names()
.and_then(|module| module.parse_reloc())
{
Ok(m) => m,
Err((errors, m)) => {
for (index, error) in errors.into_iter() {
println!("Custom section #{} parse error: {:?}", index, error);
}
m
}
};
parity_wasm::serialize_to_file(&args[2], module).expect("Failed to write module");
}
parity-wasm-0.41.0/examples/show.rs 0100644 0000765 0000024 00000002003 13447427055 0015442 0 ustar 00 0000000 0000000 extern crate parity_wasm;
use std::env;
fn main() {
let args = env::args().collect::>();
if args.len() != 3 {
println!("Usage: {} ", args[0]);
return;
}
let module = parity_wasm::deserialize_file(&args[1]).expect("Failed to load module");
let function_index = args[2].parse::().expect("Failed to parse function index");
if module.code_section().is_none() {
println!("no code in module!");
std::process::exit(1);
}
let sig = match module.function_section().unwrap().entries().get(function_index) {
Some(s) => s,
None => {
println!("no such function in module!");
std::process::exit(1)
}
};
let sig_type = &module.type_section().expect("No type section: module malformed").types()[sig.type_ref() as usize];
let code = &module.code_section().expect("Already checked, impossible").bodies()[function_index];
println!("signature: {:?}", sig_type);
println!("code: ");
for instruction in code.code().elements() {
println!("{}", instruction);
}
} parity-wasm-0.41.0/LICENSE-APACHE 0100644 0000765 0000024 00000025137 13447427055 0014237 0 ustar 00 0000000 0000000 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.
parity-wasm-0.41.0/LICENSE-MIT 0100644 0000765 0000024 00000002064 13447427055 0013741 0 ustar 00 0000000 0000000 Copyright (c) 2017-2018 Parity Technologies Limited
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.
parity-wasm-0.41.0/README.md 0100644 0000765 0000024 00000004667 13556562052 0013575 0 ustar 00 0000000 0000000 # parity-wasm
Low-level WebAssembly format library.
[](https://travis-ci.org/paritytech/parity-wasm)
[](https://crates.io/crates/parity-wasm)
[Documentation](https://docs.rs/parity-wasm/0.40.2/parity_wasm/)
## Rust WebAssembly format serializing/deserializing
Add to Cargo.toml
```toml
[dependencies]
parity-wasm = "0.41"
```
and then
```rust
let module = parity_wasm::deserialize_file("./res/cases/v1/hello.wasm").unwrap();
assert!(module.code_section().is_some());
let code_section = module.code_section().unwrap(); // Part of the module with functions code
println!("Function count in wasm file: {}", code_section.bodies().len());
```
## Wabt Test suite
`parity-wasm` supports full wabt testsuite (https://github.com/WebAssembly/testsuite), running asserts that involves deserialization.
To run testsuite:
- make sure you have all prerequisites to build `wabt` (since parity-wasm builds it internally using `wabt-rs`, see https://github.com/WebAssembly/wabt)
- checkout with submodules (`git submodule update --init --recursive`)
- run `cargo test --release --manifest-path=spec/Cargo.toml`
Decoder can be fuzzed with `cargo-fuzz` using `wasm-opt` (https://github.com/WebAssembly/binaryen):
- make sure you have all prerequisites to build `binaryen` and `cargo-fuzz` (`cmake` and a C++11 toolchain)
- checkout with submodules (`git submodule update --init --recursive`)
- install `cargo fuzz` subcommand with `cargo install cargo-fuzz`
- set rustup to use a nightly toolchain, because `cargo fuzz` uses a rust compiler plugin: `rustup override set nightly`
- run `cargo fuzz run deserialize`
## `no_std` crates
This crate has a feature, `std`, that is enabled by default. To use this crate
in a `no_std` context, add the following to your `Cargo.toml` (still requires allocator though):
```toml
[dependencies]
parity-wasm = { version = "0.41", default-features = false }
```
# License
`parity-wasm` is primarily distributed under the terms of both the MIT
license and the Apache License (Version 2.0), at your choice.
See LICENSE-APACHE, and LICENSE-MIT for details.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in parity-wasm by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
parity-wasm-0.41.0/src/builder/code.rs 0100644 0000765 0000024 00000023231 13556562014 0015775 0 ustar 00 0000000 0000000 use alloc::vec::Vec;
use crate::elements;
use super::{
invoke::{Invoke, Identity},
misc::{ValueTypeBuilder, ValueTypesBuilder, OptionalValueTypeBuilder},
};
/// Signature template description
pub enum Signature {
TypeReference(u32),
Inline(elements::FunctionType),
}
/// Signature builder
pub struct SignatureBuilder {
callback: F,
signature: elements::FunctionType,
}
impl SignatureBuilder {
/// New signature builder
pub fn new() -> Self {
SignatureBuilder::with_callback(Identity)
}
}
impl SignatureBuilder where F: Invoke {
/// New builder with callback function specified
pub fn with_callback(callback: F) -> Self {
SignatureBuilder {
callback: callback,
signature: elements::FunctionType::default(),
}
}
/// Add argument to signature builder
pub fn with_param(mut self, value_type: elements::ValueType) -> Self {
self.signature.params_mut().push(value_type);
self
}
/// Add multiple arguments to signature builder
pub fn with_params(mut self, value_types: Vec) -> Self {
self.signature.params_mut().extend(value_types);
self
}
/// Override signature return type
pub fn with_return_type(mut self, return_type: Option) -> Self {
*self.signature.return_type_mut() = return_type;
self
}
/// Start build new argument
pub fn param(self) -> ValueTypeBuilder {
ValueTypeBuilder::with_callback(self)
}
/// Start build multiple arguments
pub fn params(self) -> ValueTypesBuilder {
ValueTypesBuilder::with_callback(self)
}
/// Start building return type
pub fn return_type(self) -> OptionalValueTypeBuilder {
OptionalValueTypeBuilder::with_callback(self)
}
/// Finish current builder
pub fn build(self) -> F::Result {
self.callback.invoke(self.signature)
}
/// Finish current builder returning intermediate `Signature` struct
pub fn build_sig(self) -> Signature {
Signature::Inline(self.signature)
}
}
impl Invoke> for SignatureBuilder
where F: Invoke
{
type Result = Self;
fn invoke(self, args: Vec) -> Self {
self.with_params(args)
}
}
impl Invoke