| 1 |
use crate::{ |
| 2 |
Error, Result, |
| 3 |
module::{PrimitiveTypeInfo, TypeInfo}, |
| 4 |
}; |
| 5 |
use std::collections::HashSet; |
| 6 |
use std::ops::Range; |
| 7 |
use wasm_encoder::{RawSection, SectionId}; |
| 8 |
use wasmparser::{BinaryReader, Chunk, Parser, Payload}; |
| 9 |
|
| 10 |
/// Provides module information for future usage during mutation |
| 11 |
/// an instance of ModuleInfo could be user to determine which mutation could be applied |
| 12 |
#[derive(Default, Clone, Debug)] |
| 13 |
pub struct ModuleInfo<'a> { |
| 14 |
// The following fields are offsets inside the `raw_sections` field. |
| 15 |
// The main idea is to maintain the order of the sections in the input Wasm. |
| 16 |
pub exports: Option<usize>, |
| 17 |
pub export_names: HashSet<String>, |
| 18 |
|
| 19 |
// Indices of various sections within `self.raw_sections`. |
| 20 |
pub types: Option<usize>, |
| 21 |
pub imports: Option<usize>, |
| 22 |
pub tables: Option<usize>, |
| 23 |
pub memories: Option<usize>, |
| 24 |
pub globals: Option<usize>, |
| 25 |
pub elements: Option<usize>, |
| 26 |
pub functions: Option<usize>, |
| 27 |
pub data_count: Option<usize>, |
| 28 |
pub data: Option<usize>, |
| 29 |
pub code: Option<usize>, |
| 30 |
pub start: Option<usize>, |
| 31 |
|
| 32 |
pub exports_count: u32, |
| 33 |
elements_count: u32, |
| 34 |
data_segments_count: u32, |
| 35 |
start_function: Option<u32>, |
| 36 |
memory_count: u32, |
| 37 |
table_count: u32, |
| 38 |
tag_count: u32, |
| 39 |
|
| 40 |
imported_functions_count: u32, |
| 41 |
imported_globals_count: u32, |
| 42 |
imported_memories_count: u32, |
| 43 |
imported_tables_count: u32, |
| 44 |
imported_tags_count: u32, |
| 45 |
|
| 46 |
// types for inner functions |
| 47 |
pub types_map: Vec<TypeInfo>, |
| 48 |
|
| 49 |
// function idx to type idx |
| 50 |
pub function_map: Vec<u32>, |
| 51 |
pub global_types: Vec<PrimitiveTypeInfo>, |
| 52 |
pub table_types: Vec<wasmparser::TableType>, |
| 53 |
pub memory_types: Vec<wasmparser::MemoryType>, |
| 54 |
|
| 55 |
// raw_sections |
| 56 |
pub raw_sections: Vec<RawSection<'a>>, |
| 57 |
pub input_wasm: &'a [u8], |
| 58 |
} |
| 59 |
|
| 60 |
impl<'a> ModuleInfo<'a> { |
| 61 |
/// Parse the given Wasm bytes and fill out a `ModuleInfo` AST for it. |
| 62 |
pub fn new(input_wasm: &[u8]) -> Result<ModuleInfo<'_>> { |
| 63 |
let mut parser = Parser::new(0); |
| 64 |
let mut info = ModuleInfo::default(); |
| 65 |
let mut wasm = input_wasm; |
| 66 |
info.input_wasm = wasm; |
| 67 |
|
| 68 |
loop { |
| 69 |
let (payload, consumed) = match parser.parse(wasm, true)? { |
| 70 |
Chunk::NeedMoreData(hint) => { |
| 71 |
panic!("Invalid Wasm module {hint:?}"); |
| 72 |
} |
| 73 |
Chunk::Parsed { consumed, payload } => (payload, consumed), |
| 74 |
}; |
| 75 |
match payload { |
| 76 |
Payload::CodeSectionStart { |
| 77 |
count: _, |
| 78 |
range, |
| 79 |
size: _, |
| 80 |
} => { |
| 81 |
info.code = Some(info.raw_sections.len()); |
| 82 |
info.section(SectionId::Code.into(), range.clone(), input_wasm); |
| 83 |
parser.skip_section(); |
| 84 |
// update slice, bypass the section |
| 85 |
wasm = &input_wasm[range.end..]; |
| 86 |
|
| 87 |
continue; |
| 88 |
} |
| 89 |
Payload::TypeSection(reader) => { |
| 90 |
info.types = Some(info.raw_sections.len()); |
| 91 |
info.section(SectionId::Type.into(), reader.range(), input_wasm); |
| 92 |
|
| 93 |
// Save function types |
| 94 |
for ty in reader.into_iter_err_on_gc_types() { |
| 95 |
info.types_map.push(ty?.try_into()?); |
| 96 |
} |
| 97 |
} |
| 98 |
Payload::ImportSection(reader) => { |
| 99 |
info.imports = Some(info.raw_sections.len()); |
| 100 |
info.section(SectionId::Import.into(), reader.range(), input_wasm); |
| 101 |
|
| 102 |
for ty in reader { |
| 103 |
match ty?.ty { |
| 104 |
wasmparser::TypeRef::Func(ty) => { |
| 105 |
// Save imported functions |
| 106 |
info.function_map.push(ty); |
| 107 |
info.imported_functions_count += 1; |
| 108 |
} |
| 109 |
wasmparser::TypeRef::Global(ty) => { |
| 110 |
let ty = PrimitiveTypeInfo::try_from(ty.content_type)?; |
| 111 |
info.global_types.push(ty); |
| 112 |
info.imported_globals_count += 1; |
| 113 |
} |
| 114 |
wasmparser::TypeRef::Memory(ty) => { |
| 115 |
info.memory_count += 1; |
| 116 |
info.imported_memories_count += 1; |
| 117 |
info.memory_types.push(ty); |
| 118 |
} |
| 119 |
wasmparser::TypeRef::Table(ty) => { |
| 120 |
info.table_count += 1; |
| 121 |
info.imported_tables_count += 1; |
| 122 |
info.table_types.push(ty); |
| 123 |
} |
| 124 |
wasmparser::TypeRef::Tag(_ty) => { |
| 125 |
info.tag_count += 1; |
| 126 |
info.imported_tags_count += 1; |
| 127 |
} |
| 128 |
} |
| 129 |
} |
| 130 |
} |
| 131 |
Payload::FunctionSection(reader) => { |
| 132 |
info.functions = Some(info.raw_sections.len()); |
| 133 |
info.section(SectionId::Function.into(), reader.range(), input_wasm); |
| 134 |
|
| 135 |
for ty in reader { |
| 136 |
info.function_map.push(ty?); |
| 137 |
} |
| 138 |
} |
| 139 |
Payload::TableSection(reader) => { |
| 140 |
info.tables = Some(info.raw_sections.len()); |
| 141 |
info.table_count += reader.count(); |
| 142 |
info.section(SectionId::Table.into(), reader.range(), input_wasm); |
| 143 |
|
| 144 |
for table in reader { |
| 145 |
let table = table?; |
| 146 |
info.table_types.push(table.ty); |
| 147 |
} |
| 148 |
} |
| 149 |
Payload::MemorySection(reader) => { |
| 150 |
info.memories = Some(info.raw_sections.len()); |
| 151 |
info.memory_count += reader.count(); |
| 152 |
info.section(SectionId::Memory.into(), reader.range(), input_wasm); |
| 153 |
|
| 154 |
for ty in reader { |
| 155 |
info.memory_types.push(ty?); |
| 156 |
} |
| 157 |
} |
| 158 |
Payload::GlobalSection(reader) => { |
| 159 |
info.globals = Some(info.raw_sections.len()); |
| 160 |
info.section(SectionId::Global.into(), reader.range(), input_wasm); |
| 161 |
|
| 162 |
for ty in reader { |
| 163 |
let ty = ty?; |
| 164 |
// We only need the type of the global, not necessarily if is mutable or not |
| 165 |
let ty = PrimitiveTypeInfo::try_from(ty.ty.content_type)?; |
| 166 |
info.global_types.push(ty); |
| 167 |
} |
| 168 |
} |
| 169 |
Payload::ExportSection(reader) => { |
| 170 |
info.exports = Some(info.raw_sections.len()); |
| 171 |
info.exports_count = reader.count(); |
| 172 |
|
| 173 |
for entry in reader.clone() { |
| 174 |
info.export_names.insert(entry?.name.into()); |
| 175 |
} |
| 176 |
|
| 177 |
info.section(SectionId::Export.into(), reader.range(), input_wasm); |
| 178 |
} |
| 179 |
Payload::StartSection { func, range } => { |
| 180 |
info.start = Some(info.raw_sections.len()); |
| 181 |
info.start_function = Some(func); |
| 182 |
info.section(SectionId::Start.into(), range, input_wasm); |
| 183 |
} |
| 184 |
Payload::ElementSection(reader) => { |
| 185 |
info.elements = Some(info.raw_sections.len()); |
| 186 |
info.elements_count = reader.count(); |
| 187 |
info.section(SectionId::Element.into(), reader.range(), input_wasm); |
| 188 |
} |
| 189 |
Payload::DataSection(reader) => { |
| 190 |
info.data = Some(info.raw_sections.len()); |
| 191 |
info.data_segments_count = reader.count(); |
| 192 |
info.section(SectionId::Data.into(), reader.range(), input_wasm); |
| 193 |
} |
| 194 |
Payload::CustomSection(c) => { |
| 195 |
info.section(SectionId::Custom.into(), c.range(), input_wasm); |
| 196 |
} |
| 197 |
Payload::UnknownSection { |
| 198 |
id, |
| 199 |
contents: _, |
| 200 |
range, |
| 201 |
} => { |
| 202 |
info.section(id, range, input_wasm); |
| 203 |
} |
| 204 |
Payload::DataCountSection { count: _, range } => { |
| 205 |
info.data_count = Some(info.raw_sections.len()); |
| 206 |
info.section(SectionId::DataCount.into(), range, input_wasm); |
| 207 |
} |
| 208 |
Payload::Version { .. } => {} |
| 209 |
Payload::End(_) => { |
| 210 |
break; |
| 211 |
} |
| 212 |
_ => return Err(Error::unsupported(format!("section: {payload:?}"))), |
| 213 |
} |
| 214 |
wasm = &wasm[consumed..]; |
| 215 |
} |
| 216 |
|
| 217 |
Ok(info) |
| 218 |
} |
| 219 |
|
| 220 |
pub fn has_nonempty_code(&self) -> bool { |
| 221 |
if let Some(section) = self.code { |
| 222 |
let section_data = self.raw_sections[section].data; |
| 223 |
let reader = BinaryReader::new(section_data, 0); |
| 224 |
wasmparser::CodeSectionReader::new(reader) |
| 225 |
.map(|r| r.count() != 0) |
| 226 |
.unwrap_or(false) |
| 227 |
} else { |
| 228 |
false |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
pub fn has_code(&self) -> bool { |
| 233 |
self.code != None |
| 234 |
} |
| 235 |
|
| 236 |
/// Does this module have any custom sections? |
| 237 |
pub fn has_custom_section(&self) -> bool { |
| 238 |
self.raw_sections |
| 239 |
.iter() |
| 240 |
.any(|s| s.id == SectionId::Custom as u8) |
| 241 |
} |
| 242 |
|
| 243 |
/// Registers a new raw_section in the ModuleInfo |
| 244 |
pub fn section(&mut self, id: u8, range: Range<usize>, full_wasm: &'a [u8]) { |
| 245 |
self.raw_sections.push(RawSection { |
| 246 |
id, |
| 247 |
data: &full_wasm[range], |
| 248 |
}); |
| 249 |
} |
| 250 |
|
| 251 |
pub fn get_code_section(&self) -> RawSection<'a> { |
| 252 |
self.raw_sections[self.code.unwrap()] |
| 253 |
} |
| 254 |
|
| 255 |
pub fn get_binary_reader(&self, i: usize) -> wasmparser::BinaryReader<'a> { |
| 256 |
BinaryReader::new(self.raw_sections[i].data, 0) |
| 257 |
} |
| 258 |
|
| 259 |
pub fn has_exports(&self) -> bool { |
| 260 |
self.exports != None |
| 261 |
} |
| 262 |
|
| 263 |
/// Returns the function type based on the index of the function type |
| 264 |
/// `types[functions[idx]]` |
| 265 |
pub fn get_functype_idx(&self, idx: u32) -> &TypeInfo { |
| 266 |
let functpeindex = self.function_map[idx as usize] as usize; |
| 267 |
&self.types_map[functpeindex] |
| 268 |
} |
| 269 |
|
| 270 |
/// Returns the number of globals used by the Wasm binary including imported |
| 271 |
/// glboals |
| 272 |
pub fn get_global_count(&self) -> usize { |
| 273 |
self.global_types.len() |
| 274 |
} |
| 275 |
|
| 276 |
/// Insert a new section as the `i`th section in the Wasm module. |
| 277 |
pub fn insert_section( |
| 278 |
&self, |
| 279 |
i: usize, |
| 280 |
new_section: &impl wasm_encoder::Section, |
| 281 |
) -> wasm_encoder::Module { |
| 282 |
log::trace!("inserting new section at {i}"); |
| 283 |
let mut module = wasm_encoder::Module::new(); |
| 284 |
self.raw_sections.iter().enumerate().for_each(|(j, s)| { |
| 285 |
if i == j { |
| 286 |
module.section(new_section); |
| 287 |
} |
| 288 |
module.section(s); |
| 289 |
}); |
| 290 |
if self.raw_sections.len() == i { |
| 291 |
module.section(new_section); |
| 292 |
} |
| 293 |
module |
| 294 |
} |
| 295 |
|
| 296 |
/// Move a section from index `src_idx` to `dest_idx` in the Wasm module |
| 297 |
pub fn move_section(&self, src_idx: usize, dest_idx: usize) -> wasm_encoder::Module { |
| 298 |
log::trace!("moving section from index {src_idx} to index {dest_idx}"); |
| 299 |
assert!(src_idx < self.raw_sections.len()); |
| 300 |
assert!(dest_idx < self.raw_sections.len()); |
| 301 |
assert_ne!(src_idx, dest_idx); |
| 302 |
let mut sections = self.raw_sections.clone(); |
| 303 |
let to_move = sections.remove(src_idx); |
| 304 |
let mut module = wasm_encoder::Module::new(); |
| 305 |
for (i, section) in sections.iter().enumerate() { |
| 306 |
if i == dest_idx { |
| 307 |
module.section(&to_move); |
| 308 |
} |
| 309 |
module.section(section); |
| 310 |
} |
| 311 |
if sections.len() == dest_idx { |
| 312 |
module.section(&to_move); |
| 313 |
} |
| 314 |
module |
| 315 |
} |
| 316 |
|
| 317 |
/// Replace the `i`th section in this module with the given new section. |
| 318 |
pub fn replace_section( |
| 319 |
&self, |
| 320 |
i: usize, |
| 321 |
new_section: &impl wasm_encoder::Section, |
| 322 |
) -> wasm_encoder::Module { |
| 323 |
log::trace!("replacing section {i}"); |
| 324 |
let mut module = wasm_encoder::Module::new(); |
| 325 |
for (j, s) in self.raw_sections.iter().enumerate() { |
| 326 |
if i == j { |
| 327 |
module.section(new_section); |
| 328 |
} else { |
| 329 |
module.section(s); |
| 330 |
} |
| 331 |
} |
| 332 |
module |
| 333 |
} |
| 334 |
|
| 335 |
/// Replaces raw sections in the passed indexes and return a new module |
| 336 |
/// |
| 337 |
/// This method will be helpful to add more than one custom section. For |
| 338 |
/// example, some code mutations might need to add a few globals. This |
| 339 |
/// method can be used to write a new or custom global section before the |
| 340 |
/// code section. |
| 341 |
/// * `section_writer` this callback should write the custom section and |
| 342 |
/// returns true if it was successful, if false is returned then the |
| 343 |
/// default section will be written to the module |
| 344 |
pub fn replace_multiple_sections<P>(&self, mut section_writer: P) -> wasm_encoder::Module |
| 345 |
where |
| 346 |
P: FnMut(usize, u8, &mut wasm_encoder::Module) -> bool, |
| 347 |
{ |
| 348 |
let mut module = wasm_encoder::Module::new(); |
| 349 |
self.raw_sections.iter().enumerate().for_each(|(j, s)| { |
| 350 |
// Write if the section_writer did not write a custom section |
| 351 |
if !section_writer(j, s.id, &mut module) { |
| 352 |
module.section(s); |
| 353 |
} |
| 354 |
}); |
| 355 |
module |
| 356 |
} |
| 357 |
|
| 358 |
pub fn num_functions(&self) -> u32 { |
| 359 |
self.function_map.len() as u32 |
| 360 |
} |
| 361 |
|
| 362 |
pub fn num_local_functions(&self) -> u32 { |
| 363 |
self.num_functions() - self.num_imported_functions() |
| 364 |
} |
| 365 |
|
| 366 |
pub fn num_imported_functions(&self) -> u32 { |
| 367 |
self.imported_functions_count |
| 368 |
} |
| 369 |
|
| 370 |
pub fn num_tables(&self) -> u32 { |
| 371 |
self.table_count |
| 372 |
} |
| 373 |
|
| 374 |
pub fn num_imported_tables(&self) -> u32 { |
| 375 |
self.imported_tables_count |
| 376 |
} |
| 377 |
|
| 378 |
pub fn num_memories(&self) -> u32 { |
| 379 |
self.memory_count |
| 380 |
} |
| 381 |
|
| 382 |
pub fn num_imported_memories(&self) -> u32 { |
| 383 |
self.imported_memories_count |
| 384 |
} |
| 385 |
|
| 386 |
pub fn num_globals(&self) -> u32 { |
| 387 |
self.global_types.len() as u32 |
| 388 |
} |
| 389 |
|
| 390 |
pub fn num_imported_globals(&self) -> u32 { |
| 391 |
self.imported_globals_count |
| 392 |
} |
| 393 |
|
| 394 |
pub fn num_local_globals(&self) -> u32 { |
| 395 |
self.global_types.len() as u32 - self.imported_globals_count |
| 396 |
} |
| 397 |
|
| 398 |
pub fn num_tags(&self) -> u32 { |
| 399 |
self.tag_count |
| 400 |
} |
| 401 |
|
| 402 |
pub fn num_imported_tags(&self) -> u32 { |
| 403 |
self.imported_tags_count |
| 404 |
} |
| 405 |
|
| 406 |
pub fn num_data(&self) -> u32 { |
| 407 |
self.data_segments_count |
| 408 |
} |
| 409 |
|
| 410 |
pub fn num_elements(&self) -> u32 { |
| 411 |
self.elements_count |
| 412 |
} |
| 413 |
|
| 414 |
pub fn num_types(&self) -> u32 { |
| 415 |
self.types_map.len() as u32 |
| 416 |
} |
| 417 |
} |