diff --git a/.gitignore b/.gitignore index 41ded14..966b563 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /target *.bndb /toolchain -/research \ No newline at end of file +/research +/.codegraph diff --git a/CHANGELOG.md b/CHANGELOG.md index c6723bb..842cf47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,88 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [0.6.0] - 2026-11-08 + +A form's record stream had three misreads: a hosted control's record was +property data nobody decoded, the form header's +0x59 and +0x5D were read as +a width and a height they never held, and external table type 6 was read as +a type library reference rather than the global object the runtime binds. + +### Added + +- **The procedure an event handler slot calls.** `VbObject::handler_method` + resolves a connected sink slot's stub to the method-table index of the + procedure it calls: a P-Code stub (`mov eax, imm32; cmp ax, 0xC033; mov + edx, ; ...`) by the `ProcDscInfo` a method slot points at, + a native one (`sub dword [esp+4], imm32; jmp `) by the + procedure a native method slot points at. `EventBinding::method_index` + carries it. A handler's name is the binding Visual Basic makes at compile + time, so the procedure names an event no template does: `events` + `Listener`'s `WithEvents m_Source` handlers resolve to `m_Source_Started`, + `m_Source_Ticked` and `m_Source_Named`, and `activex`'s hosted `Winsock1` + slots resolve although its sink leads with the extender's events. A + natively compiled class has no method table, so its handlers do not + resolve (`events-native`). + +- **A hosted control's extender properties.** A hosted control's record (an + ActiveX control, a project's UserControl) has type `0xFF` and states its + extender's properties - its place (`Bounds`, or `Left` and `Top` for one + not drawn at run time), `Index` and `TabIndex` - after its ProgID, around + the object it persisted. `FormControlRecord::properties` now starts + decoding past the ProgID (its `u16` length, bytes and NUL) rather than at + the stream's first byte, against the `Extender` descriptor table (75 + entries, MSVBVM60.DLL 6.00.8176 `0x6602DE18`); any other record has no + ProgID and still decodes from the first byte. + `PropertyIter::new_at` decodes from a given offset so the properties' + offsets stay those of the whole stream. + +- **The persisted object a hosted control writes** (`ObjectBlob`): a `u32` + tag, a `u32` length and that many bytes (`OleObjectBlob`), carried by the + new `PropertyValue::ObjectBlob` and `PropType::ObjectBlob` (persisted as + `"ObjectBlob"`). `forms` Gauge1 is 72 bytes and `activex` CommonDialog1 + 76, each record going on after it with the extender's remaining + properties. + +- **`ExternalGlobalObject::data_slot_va`**: the `.data` slot the runtime + stores the bound object into. + +- **The arithmetic every opcode computes.** `ArithOp` gains `Fix`, `Int` + and `Sgn` for the `FnFix`, `FnInt` and `FnSgn` families, which were + `ArithOp::Other`. Two tests now assert that no `Arithmetic` or `Unary` + opcode in any of the six dispatch tables is left `ArithOp::Other`. + +### Changed + +- **`EventBinding` gains `method_index`** (breaking for struct literals). + +- **External table type 6 is a global object, not a type library** + (breaking). The runtime binds the object of the entry's class into the + entry's data slot when it loads the project, so the entry is + `{lpClsid, lpDataSlot}`: `ExternalKind::TypeLib` is now + `ExternalKind::GlobalObject` (persisted as `"GlobalObject"`), + `ExternalTypelibInfo` is now `ExternalGlobalObject` with `clsid_va`, + `clsid` and the new `data_slot_va`, and + `ExternalTableEntry::as_typelib` is now `as_global_object`. + +- **`PropType`, `PropertyValue` and `ArithOp` gain variants** (breaking for + exhaustive matches; none of the three is `non_exhaustive`). + +### Fixed + +- **The form header's +0x59 and +0x5D are sizes of the stream, not a form's + width and height** (breaking). `FormDataHeader::width` is now + `stream_size`, the byte length of the form's stream from offset 0x5D to + the `0x04` after its last record, and `height` is now `properties_size`, + the byte length of the designer object's own record counted from 0x5D. + `forms` Board states 483 and 87 there, and its size is in its properties + (`ClientSize`, 4680 x 3090 twips); the old names reported 483 x 87 twips + as a form's dimensions. + +- **Exponentiation is classified.** `ArithOp::Pow` was never produced: the + build script looked for a `Pow` mnemonic prefix, and the opcodes are the + `Pwr` family (`PwrR8R8`, `PwrR8I2`, `PwrVar`), which classified as + `ArithOp::Other`. + ## [0.5.0] - 2026-10-09 Every name of the ProjectInfo2 name area now has an owner: the private @@ -687,7 +769,8 @@ Affects `vbobject.rs`, `pcodemethod.rs`, `methodlink.rs`, Initial public release. -[Unreleased]: https://github.com/ATRAPSLLC/visualbasic-rs/compare/v0.5.0...HEAD +[Unreleased]: https://github.com/ATRAPSLLC/visualbasic-rs/compare/v0.6.0...HEAD +[0.6.0]: https://github.com/ATRAPSLLC/visualbasic-rs/compare/v0.5.0...v0.6.0 [0.5.0]: https://github.com/ATRAPSLLC/visualbasic-rs/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/ATRAPSLLC/visualbasic-rs/compare/v0.3.2...v0.4.0 [0.3.2]: https://github.com/ATRAPSLLC/visualbasic-rs/compare/v0.3.1...v0.3.2 diff --git a/Cargo.lock b/Cargo.lock index 24d94a5..5fb981e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -363,7 +363,7 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "visualbasic" -version = "0.5.0" +version = "0.6.0" dependencies = [ "goblin", "msft-typelib", diff --git a/Cargo.toml b/Cargo.toml index 57b690c..41f8074 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "visualbasic" -version = "0.5.0" +version = "0.6.0" edition = "2024" rust-version = "1.88" description = "Parse and inspect Visual Basic 6 compiled binaries" diff --git a/build.rs b/build.rs index 9d1a1fa..7730519 100644 --- a/build.rs +++ b/build.rs @@ -11,11 +11,7 @@ //! - `opcode_generated.rs` - 6 static `[OpcodeInfo; 256]` opcode arrays //! - `vb6_data_generated.rs` - control GUIDs, event templates, VB6 constants -use std::collections::HashMap; -use std::env; -use std::fs; -use std::io::Write; -use std::path::Path; +use std::{collections::HashMap, env, fs, io::Write, mem, path::Path}; /// Splits one CSV line into its fields, honouring double-quoted fields (a /// quoted field may hold commas; `""` inside one is a quote). @@ -31,7 +27,7 @@ fn split_csv_line(line: &str) -> Vec { chars.next(); } '"' => quoted = !quoted, - ',' if !quoted => fields.push(std::mem::take(&mut field)), + ',' if !quoted => fields.push(mem::take(&mut field)), _ => field.push(c), } } @@ -672,7 +668,7 @@ fn generate_control_properties(out_dir: &str) { // Only generate entries for active and flag properties // (flag = bits 16+17 clear in descriptor flags, opcode emitted with no value) - if status != "active" && status != "flag" { + if status != "active" && status != "flag" && status != "blob" { continue; } @@ -680,6 +676,8 @@ fn generate_control_properties(out_dir: &str) { // Flag entries have no value data regardless of ser_type. let prop_type = if status == "flag" { "Flag" + } else if status == "blob" { + "ObjectBlob" } else { match (ser_type, callback_bytes) { (0, _) => "Flag", @@ -720,6 +718,9 @@ fn generate_control_properties(out_dir: &str) { props.sort_by_key(|e| e.index); } + writeln!(out, "use super::PropType;").unwrap(); + writeln!(out).unwrap(); + // Write the PropertyDesc struct writeln!( out, @@ -732,7 +733,7 @@ fn generate_control_properties(out_dir: &str) { writeln!(out, " /// Property name.").unwrap(); writeln!(out, " pub name: &'static str,").unwrap(); writeln!(out, " /// Serialized value type.").unwrap(); - writeln!(out, " pub prop_type: super::PropType,").unwrap(); + writeln!(out, " pub prop_type: PropType,").unwrap(); writeln!( out, " /// Serialization type from descriptor flags & 0x3F." @@ -767,7 +768,7 @@ fn generate_control_properties(out_dir: &str) { { writeln!( out, - " ({idx}, PropertyDesc {{ name: {name:?}, prop_type: super::PropType::{prop_type}, ser_type: {ser_type}, callback_bytes: {callback_bytes} }})," + " ({idx}, PropertyDesc {{ name: {name:?}, prop_type: PropType::{prop_type}, ser_type: {ser_type}, callback_bytes: {callback_bytes} }})," ) .unwrap(); } @@ -832,6 +833,9 @@ fn generate_control_properties(out_dir: &str) { ("UserControl", 40), ("PropertyPage", 41), ("UserDocument", 42), + // A hosted control's record (an ActiveX control, a project's + // UserControl) has type 0xFF and states its extender's properties. + ("Extender", 255), ]; for (ctrl_name, ctype_id) in &ctype_map { @@ -1105,7 +1109,7 @@ fn classify_arith_op(mnemonic: &str) -> &'static str { if mnemonic.starts_with("Mod") { return "Mod"; } - if mnemonic.starts_with("Pow") { + if mnemonic.starts_with("Pwr") { return "Pow"; } if mnemonic.starts_with("Concat") { @@ -1139,6 +1143,15 @@ fn classify_unary_op(mnemonic: &str) -> &'static str { if mnemonic.starts_with("FnAbs") { return "Abs"; } + if mnemonic.starts_with("FnFix") { + return "Fix"; + } + if mnemonic.starts_with("FnInt") { + return "Int"; + } + if mnemonic.starts_with("FnSgn") { + return "Sgn"; + } "Other" } diff --git a/data/vb6_control_properties.csv b/data/vb6_control_properties.csv index 2a05ab5..871b123 100644 --- a/data/vb6_control_properties.csv +++ b/data/vb6_control_properties.csv @@ -5,7 +5,11 @@ # the composite labels Bounds (Left, Top, Width, Height), ClientSize (ClientLeft to # ClientHeight) and DataSource(obj). A property stream names a property by # its index in the table. -# Status: active=serializable, fontsub=flag-only, skip=runtime-only, sep=separator, obj=COM object ref +# Status: active=serializable, fontsub=flag-only, skip=runtime-only, sep=separator, obj=COM object ref, +# blob=a persisted object: a u32 tag, a u32 length and that many bytes. A hosted +# control's OleObjectBlob is one (`tests/fixtures/forms` Gauge1, `activex` +# CommonDialog1, whose record goes on after it); the OLE container's writes only +# its opcode (`props` POLE decodes to its terminator with it as a flag) # # Descriptor Table VAs: # Timer: 0x66028A50 (9 entries) @@ -34,6 +38,10 @@ # PropertyPage: 0x6602A3F0 (78 entries) # UserControl: 0x66029530 (94 entries) # UserDocument: 0x66029D10 (88 entries) +# Extender: 0x6602DE18 (75 entries) in MSVBVM60.DLL 6.00.8176 +# (`toolchain/vb6`), the properties a hosted control's record +# (type 0xFF: an ActiveX control, a project's UserControl) states +# after its ProgID; rows reuse the rows of the same descriptors # control_type,index,name,ser_type,callback_bytes,status,flags,descriptor_va CheckBox,0,Name,18,0,skip,0x8400D412,0x66001E50 @@ -1248,3 +1256,78 @@ VScrollBar,23,WhatsThisHelpID,3,0,active,0x80C12203,0x66001EF0 VScrollBar,24,Container,32,0,skip,0x80004C20,0x66001FB0 VScrollBar,25,RightToLeft,4,0,active,0x80C14404,0x66114000 VScrollBar,26,CausesValidation,4,0,active,0x80C12204,0x66002010 +Extender,0,Name,18,0,skip,0x8400D412,0x6602DE18 +Extender,1,Index,17,0,active,0x84C1D411,0x6602DE18 +Extender,2,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,3,Bounds,8,4,active,0x90222408,0x6602DE18 +Extender,4,Top,10,0,flag,0x9020240A,0x6602DE18 +Extender,5,Width,9,0,flag,0x90202409,0x6602DE18 +Extender,6,Height,11,0,flag,0x9020240B,0x6602DE18 +Extender,7,Visible,4,0,active,0x80E14404,0x6602DE18 +Extender,8,Parent,32,0,skip,0x80005820,0x6602DE18 +Extender,9,DragMode,6,0,active,0x80C12606,0x6602DE18 +Extender,10,DragIcon,21,0,active,0x84C1A215,0x6602DE18 +Extender,11,Tag,13,0,active,0x80C1220D,0x6602DE18 +Extender,12,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,13,Enabled,4,0,flag,0x00C04404,0x6602DE18 +Extender,14,TabStop,4,0,active,0x80C14404,0x6602DE18 +Extender,15,TabIndex,2,0,active,0x84012402,0x6602DE18 +Extender,16,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,17,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,18,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,19,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,20,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,21,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,22,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,23,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,24,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,25,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,26,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,27,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,28,Object,32,0,skip,0x00005820,0x6602DE18 +Extender,29,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,30,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,31,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,32,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,33,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,34,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,35,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,36,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,37,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,38,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,39,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,40,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,41,DataFormat,22,0,active,0x84654416,0x6602DE18 +Extender,42,DataMember,33,0,active,0x80F12621,0x6602DE18 +Extender,43,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,44,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,45,OleObjectBlob,3,0,blob,0x02021803,0x6602DE18 +Extender,46,DataSource(obj),22,0,flag,0x84244C16,0x6602DE18 +Extender,47,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,48,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,49,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,50,HelpContextID,3,0,active,0x80C12203,0x6602DE18 +Extender,51,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,52,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,53,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,54,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,55,Default,4,0,active,0x84C14404,0x6602DE18 +Extender,56,Cancel,4,0,active,0x84C14404,0x6602DE18 +Extender,57,Left,8,0,active,0x82013408,0x6602DE18 +Extender,58,Top,10,0,active,0x8201340A,0x6602DE18 +Extender,59,Align,6,0,active,0x80C12406,0x6602DE18 +Extender,60,Negotiate,4,0,active,0x82C13404,0x6602DE18 +Extender,61,LinkTimeout,2,0,active,0x80C14402,0x6602DE18 +Extender,62,LinkTopic,1,0,active,0x80E1C401,0x6602DE18 +Extender,63,LinkItem,1,0,active,0x80E1C401,0x6602DE18 +Extender,64,LinkMode,6,0,active,0x80C1C406,0x6602DE18 +Extender,65,DataChanged,4,0,flag,0x80106E04,0x6602DE18 +Extender,66,DataField,1,0,active,0x80F12601,0x6602DE18 +Extender,67,DataSource,1,0,active,0x82F13201,0x6602DE18 +Extender,68,Bindings,1,0,active,0x02021801,0x6602DE18 +Extender,69,_,4,0,sep,0xE0000804,0x6602DE18 +Extender,70,WhatsThisHelpID,3,0,active,0x80C12203,0x6602DE18 +Extender,71,Container,32,0,skip,0x80004C20,0x6602DE18 +Extender,72,CausesValidation,4,0,active,0x80C12204,0x6602DE18 +Extender,73,DataBindings,22,0,flag,0x04005016,0x6602DE18 +Extender,74,ToolTipText,1,0,active,0x80D12401,0x6602DE18 diff --git a/examples/dump.rs b/examples/dump.rs index 251fcde..f2e2b80 100644 --- a/examples/dump.rs +++ b/examples/dump.rs @@ -3,25 +3,26 @@ //! Usage: //! cargo run --example dump -- -use std::collections::HashMap; -use std::error::Error as StdError; -use std::str; -use std::{env, fs, process}; +use std::{ + borrow::Cow, collections::HashMap, env, error::Error as StdError, fs, iter, process, str, +}; use visualbasic::{ - MethodEntry, VbControl, VbObject, VbProject, + Error, MethodEntry, VbControl, VbObject, VbProject, + addressmap::AddressMap, pcode::{calltarget::CallResolver, operand::Operand}, - project::MethodLinkKind, + project::{MethodLinkKind, format_signature}, vb::{ comreg::{ComRegData, ComRegObject}, - control::ControlKind, + control::{ControlKind, Guid}, + controlprop::CleanupAction, eventname, - external::ExternalKind, + external::{ExternalKind, ExternalTableEntry}, formdata::{FormControlType, FormDataParser}, functype::FuncTypDesc, guitable::{GuiTableEntry, GuiTableIter}, member::MemberKind, - projectinfo2::{ControlTypeIter, ProjectInfo2, read_name_strings}, + projectinfo2::{ControlTypeEntry, ControlTypeIter, ProjectInfo2, read_name_strings}, property::{Property, PropertyValue}, publicbytes::ClassFormPublicBytes, }, @@ -137,7 +138,7 @@ fn print_assembly_header(project: &VbProject<'_>, path: &str) -> DynResult<()> { println!(" .compilation {}", mode.to_lowercase()); println!(" .version {runtime_build}.{runtime_revision:02}"); println!(" .lcid 0x{lcid:08X}"); - if let Some(guid) = visualbasic::vb::control::Guid::from_bytes(ot.uuid()?) { + if let Some(guid) = Guid::from_bytes(ot.uuid()?) { println!(" .uuid {guid}"); } println!( @@ -386,10 +387,7 @@ fn format_obj_flags(obj: &ComRegObject<'_>) -> DynResult { } /// Formats a ProjectInfo2 control type entry as `{GUID} (ClassName)`. -fn format_guid_entry( - entry: &visualbasic::vb::projectinfo2::ControlTypeEntry, - map: &visualbasic::addressmap::AddressMap<'_>, -) -> String { +fn format_guid_entry(entry: &ControlTypeEntry, map: &AddressMap<'_>) -> String { entry .control_guid(map) .map(|g| { @@ -404,10 +402,7 @@ fn format_guid_entry( } /// Resolves an external table entry to a human-readable description string. -fn resolve_external( - project: &VbProject<'_>, - ext: &visualbasic::vb::external::ExternalTableEntry<'_>, -) -> String { +fn resolve_external(project: &VbProject<'_>, ext: &ExternalTableEntry<'_>) -> String { let map = project.address_map(); let obj_va = ext.external_object_va().unwrap_or(0); if obj_va == 0 { @@ -435,13 +430,16 @@ fn resolve_external( format!("va=0x{obj_va:08X}") } } - ExternalKind::TypeLib => { - if let Some(tlib) = ext.as_typelib(map) - && let Some(guid) = tlib.typelib_guid(map) + ExternalKind::GlobalObject => { + if let Some(global) = ext.as_global_object(map) + && let Some(clsid) = global.clsid(map) { - format!("typelib {guid}") + format!( + "global object {clsid} slot=0x{:08X}", + global.data_slot_va().unwrap_or(0) + ) } else { - format!("typelib va=0x{obj_va:08X}") + format!("global object va=0x{obj_va:08X}") } } ExternalKind::Unknown(t) => { @@ -611,17 +609,17 @@ fn print_object( let ge_data_size = ge.form_data_size()?; println!(); println!( - " .formdata va=0x{:08X} size=0x{:X} width={} height={} {{", + " .formdata va=0x{:08X} size=0x{:X} stream={} own={} {{", ge_data_va, ge_data_size, - h.width()?, - h.height()? + h.stream_size()?, + h.properties_size()? ); // Decode form-level properties let form_props = fd.form_properties(); if !form_props.is_empty() { - let decoded: Vec = std::iter::once(format!("Name=\"{}\"", fd.form_name())) + let decoded: Vec = iter::once(format!("Name=\"{}\"", fd.form_name())) .chain(fd.form_properties_decoded().map(|p| property_text(&p))) .collect(); if !decoded.is_empty() { @@ -797,9 +795,9 @@ fn print_object( .map(|b| String::from_utf8_lossy(b).into_owned()) .unwrap_or_else(|| format!("method_{mi:02X}")); - let sig = func_descs.get(&mi).map(|ftd| { - visualbasic::project::format_signature(ftd, &mname, obj.project().address_map()) - }); + let sig = func_descs + .get(&mi) + .map(|ftd| format_signature(ftd, &mname, obj.project().address_map())); let link = links.get(&mi); let entry = method_entries.get(mi); @@ -947,7 +945,7 @@ fn print_object( } /// Converts a Cow string result to an owned string, using `fallback` on error. -fn str_or(result: Result, visualbasic::Error>, fallback: &str) -> String { +fn str_or(result: Result, Error>, fallback: &str) -> String { result .map(|c| c.into_owned()) .unwrap_or_else(|_| fallback.into()) @@ -959,7 +957,7 @@ fn print_variable_table(label: &str, table: &ClassFormPublicBytes<'_>) { println!(" // {label}: data size 0x{size:04X} ({size} bytes)"); for entry in table.control_entries() { let cleanup = entry.cleanup_action(); - let cleanup_note = if cleanup == visualbasic::vb::controlprop::CleanupAction::None { + let cleanup_note = if cleanup == CleanupAction::None { String::new() } else { format!(" cleanup={cleanup}") diff --git a/src/addressmap.rs b/src/addressmap.rs index 214cb16..9efae91 100644 --- a/src/addressmap.rs +++ b/src/addressmap.rs @@ -8,6 +8,8 @@ //! the data at those addresses from the file on disk, we must translate //! each VA through the PE section table. +use goblin::pe::PE; + use crate::error::Error; /// A single PE section's addressing information. @@ -79,7 +81,7 @@ impl<'a> AddressMap<'a> { /// /// - [`Error::TooShort`] if the PE has no optional header. /// - [`Error::Not32Bit`] if the PE is not a 32-bit (PE32) executable. - pub fn from_goblin(file: &'a [u8], pe: &goblin::pe::PE<'_>) -> Result { + pub fn from_goblin(file: &'a [u8], pe: &PE<'_>) -> Result { // Verify this is PE32 (not PE32+) let oh = pe.header.optional_header.as_ref().ok_or(Error::TooShort { expected: 1, diff --git a/src/entrypoint.rs b/src/entrypoint.rs index 08f3fa1..20d9345 100644 --- a/src/entrypoint.rs +++ b/src/entrypoint.rs @@ -49,6 +49,8 @@ //! the first, then the second. Nothing scans the file for the magic. //! [`ExportStub`] decodes every export stub. +use goblin::pe::export::Export; + use crate::{addressmap::AddressMap, error::Error}; /// Minimum number of bytes needed at the entry point to extract the VBHeader VA. @@ -217,7 +219,7 @@ impl ExportStub { /// Returns `None` if no export matches. pub fn extract_vb_header_va_from_exports( map: &AddressMap<'_>, - exports: &[goblin::pe::export::Export<'_>], + exports: &[Export<'_>], ) -> Option { for export in exports { let rva = u32::try_from(export.rva).ok()?; diff --git a/src/error.rs b/src/error.rs index c051e55..f566f7e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -3,8 +3,9 @@ //! A single flat [`Error`] enum covers all failure modes across PE parsing, //! VB structure validation, address translation, and P-Code decoding. -use std::error; -use std::fmt; +use std::{error, fmt}; + +use goblin::error::Error as GoblinError; /// All errors that can occur during VB6 P-Code parsing. /// @@ -258,9 +259,9 @@ impl fmt::Display for Error { impl error::Error for Error {} -impl From for Error { +impl From for Error { /// Converts a goblin parsing error into our [`Error::Goblin`] variant. - fn from(e: goblin::error::Error) -> Self { + fn from(e: GoblinError) -> Self { Error::Goblin(e.to_string()) } } @@ -503,7 +504,7 @@ mod tests { #[test] fn test_error_trait_impl() { - let e: Box = Box::new(Error::RvaNotMapped { rva: 0 }); + let e: Box = Box::new(Error::RvaNotMapped { rva: 0 }); let _ = e.to_string(); } diff --git a/src/extents.rs b/src/extents.rs index c662f06..0f34aa7 100644 --- a/src/extents.rs +++ b/src/extents.rs @@ -20,7 +20,7 @@ use crate::{ control::ControlInfo, controlprop::{ControlPropertyEntry, RecordLayout}, events::{EventHandlerThunk, EventSinkVtable}, - external::{ExternalComponentEntry, ExternalDeclareInfo}, + external::{ExternalComponentEntry, ExternalDeclareInfo, ExternalGlobalObject}, functype::{ArgType, FuncTypDesc}, header::VbHeader, member::MemberDesc, @@ -521,10 +521,14 @@ impl<'p> ExtentWalk<'p> { self.length_prefix(va, name.len().saturating_add(1)); } } - } else if let Some(typelib) = entry.as_typelib(map) { - self.push(object_va, 8, StructureKind::GlobalObjectReference); - if let Ok(guid) = typelib.typelib_guid_va() { - self.guid(guid); + } else if let Some(global) = entry.as_global_object(map) { + self.push( + object_va, + ExternalGlobalObject::SIZE, + StructureKind::GlobalObjectReference, + ); + if let Ok(clsid) = global.clsid_va() { + self.guid(clsid); } } } diff --git a/src/pcode/decoder.rs b/src/pcode/decoder.rs index fec46ff..3db016a 100644 --- a/src/pcode/decoder.rs +++ b/src/pcode/decoder.rs @@ -9,7 +9,7 @@ //! 3. **Variable-length opcodes** (size == -1): A `u16` byte count follows the //! opcode, then that many bytes of payload data. -use std::fmt; +use std::{fmt, iter}; use crate::{ error::Error, @@ -138,13 +138,13 @@ impl Instruction { self.operands.iter().flatten().flat_map( move |operand| -> Box + 'a> { match *operand { - Operand::JumpTarget(t) if !sentinel(t) => Box::new(std::iter::once(t)), + Operand::JumpTarget(t) if !sentinel(t) => Box::new(iter::once(t)), Operand::JumpTable { at, count } => Box::new( (0..usize::from(count)) .map(move |i| usize::from(at).saturating_add(i.saturating_mul(2))) .filter_map(move |pos| read_u16_le(code, pos).ok()), ), - _ => Box::new(std::iter::empty()), + _ => Box::new(iter::empty()), } }, ) diff --git a/src/pcode/opcode.rs b/src/pcode/opcode.rs index a2b93a2..13d24f4 100644 --- a/src/pcode/opcode.rs +++ b/src/pcode/opcode.rs @@ -358,7 +358,7 @@ pub static UNKNOWN_OPCODE: OpcodeInfo = OpcodeInfo { pr_load: None, movement: "", category: "", - semantics: crate::pcode::semantics::OpcodeSemantics::Unclassified, + semantics: OpcodeSemantics::Unclassified, data_type: None, value_type: None, handler: 0, @@ -407,7 +407,10 @@ pub fn table_by_index(table: DispatchTable) -> &'static [OpcodeInfo; 256] { #[cfg(test)] mod tests { + use std::collections::BTreeMap; + use super::*; + use crate::pcode::semantics::{ArithOp, OpcodeSemantics}; #[test] fn test_all_tables_have_256_entries() { @@ -419,6 +422,63 @@ mod tests { assert_eq!(LEAD4_TABLE.len(), 256); } + /// Every arithmetic opcode names the operation it computes: none of the + /// tables' `arith` entries is [`ArithOp::Other`], and exponentiation is + /// the `Pwr` family (`PwrR8R8`, `PwrR8I2`, `PwrVar`). + #[test] + fn every_arithmetic_opcode_names_its_operation() { + let tables = [ + &PRIMARY_TABLE, + &LEAD0_TABLE, + &LEAD1_TABLE, + &LEAD2_TABLE, + &LEAD3_TABLE, + &LEAD4_TABLE, + ]; + let mut unnamed = Vec::new(); + let mut powers = Vec::new(); + for info in tables.iter().flat_map(|table| table.iter()) { + match info.semantics { + OpcodeSemantics::Arithmetic { op: ArithOp::Other } => unnamed.push(info.mnemonic), + OpcodeSemantics::Arithmetic { op: ArithOp::Pow } => powers.push(info.mnemonic), + _ => {} + } + } + assert!(unnamed.is_empty(), "unnamed arithmetic: {unnamed:?}"); + powers.sort_unstable(); + powers.dedup(); + assert_eq!(powers, ["PwrR8I2", "PwrR8R8", "PwrVar"]); + } + + /// Every unary opcode names the operation it computes: none of the + /// tables' `unary` entries is [`ArithOp::Other`], and the `Fn` functions + /// are their own (`FnFixR8` is `Fix`, `FnIntCy` `Int`, `FnSgnUI1` `Sgn`). + #[test] + fn every_unary_opcode_names_its_operation() { + let tables = [ + &PRIMARY_TABLE, + &LEAD0_TABLE, + &LEAD1_TABLE, + &LEAD2_TABLE, + &LEAD3_TABLE, + &LEAD4_TABLE, + ]; + let mut unnamed = Vec::new(); + let mut named = BTreeMap::new(); + for info in tables.iter().flat_map(|table| table.iter()) { + if let OpcodeSemantics::Unary { op } = info.semantics { + if op == ArithOp::Other { + unnamed.push(info.mnemonic); + } + named.insert(info.mnemonic, op); + } + } + assert!(unnamed.is_empty(), "unnamed unary: {unnamed:?}"); + assert_eq!(named.get("FnFixR8"), Some(&ArithOp::Fix)); + assert_eq!(named.get("FnIntCy"), Some(&ArithOp::Int)); + assert_eq!(named.get("FnSgnUI1"), Some(&ArithOp::Sgn)); + } + #[test] fn test_lead_byte_slots_in_primary() { assert_eq!(PRIMARY_TABLE[0xFB].mnemonic, "Lead0"); @@ -650,7 +710,6 @@ mod tests { #[test] fn test_value_type_only_where_fixed() { - use crate::pcode::semantics::PCodeDataType; // Moves name a width: no type. assert_eq!(PRIMARY_TABLE[0x71].mnemonic, "FStR4"); assert_eq!(PRIMARY_TABLE[0x71].value_type, None); diff --git a/src/pcode/semantics.rs b/src/pcode/semantics.rs index afab695..359b2e9 100644 --- a/src/pcode/semantics.rs +++ b/src/pcode/semantics.rs @@ -218,6 +218,12 @@ pub enum ArithOp { Imp, /// Absolute value. Abs, + /// `Fix`: the integral part, rounded toward zero. + Fix, + /// `Int`: the largest integral value not above the operand, rounded down. + Int, + /// `Sgn`: the sign, -1, 0 or 1, as an `Integer`. + Sgn, /// Unrecognized arithmetic. Other, } @@ -270,7 +276,7 @@ impl CallKind { mod tests { use super::*; use crate::pcode::opcode::{ - LEAD0_TABLE, LEAD1_TABLE, LEAD2_TABLE, LEAD3_TABLE, LEAD4_TABLE, PRIMARY_TABLE, + LEAD0_TABLE, LEAD1_TABLE, LEAD2_TABLE, LEAD3_TABLE, LEAD4_TABLE, OpcodeInfo, PRIMARY_TABLE, }; #[test] @@ -368,7 +374,7 @@ mod tests { #[test] fn test_all_implemented_opcodes_have_semantics() { - let tables: [&[crate::pcode::opcode::OpcodeInfo; 256]; 6] = [ + let tables: [&[OpcodeInfo; 256]; 6] = [ &PRIMARY_TABLE, &LEAD0_TABLE, &LEAD1_TABLE, diff --git a/src/project/vbobject.rs b/src/project/vbobject.rs index da20b6c..4d81f3f 100644 --- a/src/project/vbobject.rs +++ b/src/project/vbobject.rs @@ -26,6 +26,7 @@ use crate::{ ControlEntryIterator, MethodEntry, MethodLinkIterator, MethodLinkKind, PCodeMethod, VbProject, }, + trace::warn_drop, util::{read_u16_le, read_u32_le}, vb::{ constantpool::ConstantPool, @@ -780,7 +781,7 @@ impl<'a, 'p: 'a> VbObject<'a, 'p> { .filter_map(|link| match link { Ok(link) => Some(link), Err(e) => { - crate::trace::warn_drop!("code_entries.method_links", error = ?e); + warn_drop!("code_entries.method_links", error = ?e); None } }) @@ -800,7 +801,7 @@ impl<'a, 'p: 'a> VbObject<'a, 'p> { let entry = match result { Ok(entry) => entry, Err(e) => { - crate::trace::warn_drop!("code_entries.methods", error = ?e); + warn_drop!("code_entries.methods", error = ?e); continue; } }; @@ -810,7 +811,7 @@ impl<'a, 'p: 'a> VbObject<'a, 'p> { let pcode_size = match pm.proc_size() { Ok(size) => size, Err(e) => { - crate::trace::warn_drop!("code_entries.proc_size", error = ?e); + warn_drop!("code_entries.proc_size", error = ?e); continue; } }; @@ -890,7 +891,7 @@ impl<'a, 'p: 'a> VbObject<'a, 'p> { .filter_map(|r| match r { Ok(c) => Some(c), Err(e) => { - crate::trace::warn_drop!("code_entries.controls_with_form_data", error = ?e); + warn_drop!("code_entries.controls_with_form_data", error = ?e); None } }) @@ -900,7 +901,7 @@ impl<'a, 'p: 'a> VbObject<'a, 'p> { .filter_map(|r| match r { Ok(c) => Some(c), Err(e) => { - crate::trace::warn_drop!("code_entries.controls", error = ?e); + warn_drop!("code_entries.controls", error = ?e); None } }) @@ -1078,7 +1079,7 @@ impl<'a, 'p: 'a> VbObject<'a, 'p> { .filter_map(|r| match r { Ok(c) => Some(c), Err(e) => { - crate::trace::warn_drop!("events.controls_with_form_data", error = ?e); + warn_drop!("events.controls_with_form_data", error = ?e); None } }) @@ -1088,7 +1089,7 @@ impl<'a, 'p: 'a> VbObject<'a, 'p> { .filter_map(|r| match r { Ok(c) => Some(c), Err(e) => { - crate::trace::warn_drop!("events.controls", error = ?e); + warn_drop!("events.controls", error = ?e); None } }) @@ -1120,12 +1121,71 @@ impl<'a, 'p: 'a> VbObject<'a, 'p> { event_slot: slot, event_name, handler_va, + method_index: self.handler_method(handler_va), }); } } Ok(bindings) } + /// Returns the method-table index of the procedure the event sink stub at + /// `handler_va` calls, or `None` when the stub is of neither form below + /// or calls no procedure of this object. + /// + /// A connected sink slot holds a stub that names its handler: + /// + /// - P-Code: `mov eax, imm32; cmp ax, 0xC033; mov edx, ; + /// push ; ret` (`events` `Listener`'s `m_Source`, + /// `activex` `Client`'s controls), the `ProcDscInfo` being the one a + /// P-Code method table slot points at; + /// - native code: `sub dword [esp+4], imm32; jmp ` + /// (`events-native`), the procedure being the one a native slot points + /// at. A natively compiled class has no method table + /// ([`has_method_table`](Self::has_method_table) is `false` for + /// `events-native`'s `Listener`), and nothing else ties its + /// procedures to the method names: its handlers resolve to `None`. + /// + /// A handler's name is the binding Visual Basic makes at compile time + /// (`m_Source_Ticked`, `Winsock1_DataArrival`), so the procedure names + /// the event even where no event-name template does. + pub fn handler_method(&self, handler_va: u32) -> Option { + let map = self.project.address_map(); + let stub = map.slice_from_va(handler_va, 13).ok()?; + let target = match *stub { + [ + 0xB8, + _, + _, + _, + _, + 0x66, + 0x3D, + 0x33, + 0xC0, + 0xBA, + a, + b, + c, + d, + .., + ] => u32::from_le_bytes([a, b, c, d]), + [0x81, 0x6C, 0x24, 0x04, _, _, _, _, 0xE9, a, b, c, d, ..] => handler_va + .checked_add(13)? + .checked_add_signed(i32::from_le_bytes([a, b, c, d]))?, + _ => return None, + }; + self.methods().ok()?.enumerate().find_map(|(index, entry)| { + let resolved = match entry.ok()? { + MethodEntry::PCode(method) => method.proc_dsc_va(), + MethodEntry::Native { va } => va, + _ => return None, + }; + (resolved == target) + .then(|| u16::try_from(index).ok()) + .flatten() + }) + } + /// Parses the form designer data for this object. /// /// Same as [`form_data_from_gui_entry`](Self::form_data_from_gui_entry): @@ -1562,6 +1622,9 @@ pub struct EventBinding<'a> { /// walker); may be zero when iterating all slots via /// [`VbObject::events_all_slots`]. pub handler_va: u32, + /// Method-table index of the procedure the stub calls + /// ([`VbObject::handler_method`]), whose name is the handler's. + pub method_index: Option, } impl<'a> EventBinding<'a> { diff --git a/src/project/vbproject.rs b/src/project/vbproject.rs index 209f4bd..539dcd0 100644 --- a/src/project/vbproject.rs +++ b/src/project/vbproject.rs @@ -17,6 +17,7 @@ use crate::{ error::Error, imports::ImportTable, project::{CodeEntryKind, MethodLinkKind, PCodeMethod, VbObject}, + trace::warn_drop, util::{read_cstr, read_u16_le, read_u32_le}, vb::{ comreg::ComRegData, @@ -310,7 +311,7 @@ impl<'a> VbProject<'a> { /// /// Same as [`from_bytes`](Self::from_bytes), except PE parsing errors /// are not possible since the PE is already parsed. - pub fn from_goblin(file: &'a [u8], pe: &goblin::pe::PE<'_>) -> Result { + pub fn from_goblin(file: &'a [u8], pe: &PE<'_>) -> Result { let map = AddressMap::from_goblin(file, pe)?; // Extract VBHeader VA from the entry point @@ -1117,7 +1118,7 @@ impl<'a> VbProject<'a> { let obj = match obj_result { Ok(obj) => obj, Err(e) => { - crate::trace::warn_drop!("code_entrypoints.objects", error = ?e); + warn_drop!("code_entrypoints.objects", error = ?e); continue; } }; @@ -1125,7 +1126,7 @@ impl<'a> VbProject<'a> { let entries = match obj.code_entries(None) { Ok(entries) => entries, Err(e) => { - crate::trace::warn_drop!("code_entrypoints.code_entries", error = ?e); + warn_drop!("code_entrypoints.code_entries", error = ?e); continue; } }; diff --git a/src/vb/constantpool.rs b/src/vb/constantpool.rs index 6f2253a..dffd5e9 100644 --- a/src/vb/constantpool.rs +++ b/src/vb/constantpool.rs @@ -354,6 +354,8 @@ impl<'a> Iterator for ConstPoolIter<'a> { #[cfg(test)] mod tests { + use std::array; + use super::*; use crate::addressmap::SectionEntry; @@ -458,7 +460,7 @@ mod tests { fn test_guid_at() { let mut file = vec![0u8; 0x3000]; put(&mut file, 0x401000, &0x00401100u32.to_le_bytes()); - let guid: [u8; 16] = core::array::from_fn(|i| i as u8 + 1); + let guid: [u8; 16] = array::from_fn(|i| i as u8 + 1); put(&mut file, 0x401100, &guid); let map = make_test_map(&file); let pool = ConstantPool::new(&map, 0x00401000); diff --git a/src/vb/control.rs b/src/vb/control.rs index 51baae8..f569079 100644 --- a/src/vb/control.rs +++ b/src/vb/control.rs @@ -577,6 +577,9 @@ impl<'a> Iterator for ControlIterator<'a> { #[cfg(test)] mod tests { + use std::array; + + use super::*; #[test] fn test_guid_parses_its_display() { @@ -592,7 +595,7 @@ mod tests { let lower: Guid = text.to_lowercase().parse().unwrap(); assert_eq!(lower, guid); let all = Guid { - bytes: core::array::from_fn(|i| (i as u8).wrapping_mul(17)), + bytes: array::from_fn(|i| (i as u8).wrapping_mul(17)), }; assert_eq!(all.to_string().parse::().unwrap(), all); // Control: anything else is refused. @@ -610,7 +613,6 @@ mod tests { ); } } - use super::*; fn make_control_info() -> Vec { let mut buf = vec![0u8; ControlInfo::MIN_SIZE]; diff --git a/src/vb/external.rs b/src/vb/external.rs index 34f8056..de44b3d 100644 --- a/src/vb/external.rs +++ b/src/vb/external.rs @@ -10,7 +10,7 @@ //! ├── type 7: ExternalDeclareInfo (the DllFunctionCall descriptor) //! │ ├── lpLibraryName -> DLL name string //! │ └── lpFunctionName -> API function name string -//! └── type 6: ExternalTypelibInfo (lpGuid -> 16-byte GUID) +//! └── type 6: ExternalGlobalObject (lpClsid -> 16-byte CLSID, lpDataSlot) //! //! VbHeader +0x50 (table VA), +0x46 (count) //! └── ExternalComponentEntry (variable length, self-relative offsets) @@ -700,14 +700,16 @@ impl fmt::Display for VarType { /// the entry represents and how `lpExternalObject` should be interpreted. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExternalKind { - /// GUID reference (`fExternalType == 0x06`). + /// A global object the runtime binds at load (`fExternalType == 0x06`). /// - /// The `lpExternalObject` VA points to an [`ExternalTypelibInfo`] whose - /// first dword is the VA of a 16-byte GUID. In the fixtures the two - /// projects with a UserControl (`forms`, `dispid`) each have one such - /// entry, with the GUID `{FCFB3D23-A0FA-1068-A738-08002B3371B5}`; no - /// fixture references an OCX. - TypeLib, + /// The `lpExternalObject` VA points to an [`ExternalGlobalObject`]: the + /// VA of a 16-byte CLSID and the VA of a slot in `.data`. When it loads + /// the project the runtime (MSVBVM60 6.00.8176 0x6602BEF1) walks the + /// external table and stores an AddRef'd reference to the object of that + /// class into the slot. In the fixtures the two projects with a + /// UserControl (`forms`, `dispid`) each have one such entry, for VB's + /// `Global` object, `{FCFB3D23-A0FA-1068-A738-08002B3371B5}`. + GlobalObject, /// Declare function import (`fExternalType == 0x07`). /// @@ -727,7 +729,7 @@ impl ExternalKind { /// Classifies an external type value. pub fn from_raw(value: u32) -> Self { match value { - 0x06 => Self::TypeLib, + 0x06 => Self::GlobalObject, 0x07 => Self::DeclareFunction, other => Self::Unknown(other), } @@ -736,12 +738,12 @@ impl ExternalKind { /// Returns the stable persistence string for this external kind. /// /// These strings are part of the public API contract and are suitable - /// for database storage: `"DeclareFunction"`, `"TypeLib"`, and + /// for database storage: `"DeclareFunction"`, `"GlobalObject"`, and /// `"Unknown"`. pub fn as_str(&self) -> &'static str { match self { Self::DeclareFunction => "DeclareFunction", - Self::TypeLib => "TypeLib", + Self::GlobalObject => "GlobalObject", Self::Unknown(_) => "Unknown", } } @@ -757,7 +759,7 @@ impl fmt::Display for ExternalKind { /// /// The external table is referenced by `ProjectData.external_table_va()?` /// with `ProjectData.external_count()?` entries. Each entry is a DLL -/// function a `Declare` imports or a GUID reference. `Declare`s of the same +/// function a `Declare` imports or a global object the runtime binds. `Declare`s of the same /// entry point share one entry: `vtable` has 13 `Declare`s, 12 of them /// aliases of `GetTickCount`, and 2 entries. /// @@ -804,7 +806,7 @@ impl<'a> ExternalTableEntry<'a> { /// /// Use this to determine how to interpret [`external_object_va`](Self::external_object_va): /// - [`ExternalKind::DeclareFunction`]: VA points to [`ExternalDeclareInfo`] - /// - [`ExternalKind::TypeLib`]: VA points to [`ExternalTypelibInfo`] + /// - [`ExternalKind::GlobalObject`]: VA points to [`ExternalGlobalObject`] /// /// # Errors /// @@ -833,17 +835,18 @@ impl<'a> ExternalTableEntry<'a> { ExternalDeclareInfo::parse(data).ok() } - /// Parses this entry as a TypeLib reference. + /// Parses this entry as a global object reference. /// - /// Returns `None` if the type is not [`ExternalKind::TypeLib`] (`exprs` - /// entry 0, the `Declare` of `lstrlenA`) or the VA cannot be resolved. - pub fn as_typelib(&self, map: &AddressMap<'a>) -> Option> { - if !matches!(self.kind().ok()?, ExternalKind::TypeLib) { + /// Returns `None` if the type is not [`ExternalKind::GlobalObject`] + /// (`exprs` entry 0, the `Declare` of `lstrlenA`) or the VA cannot be + /// resolved. + pub fn as_global_object(&self, map: &AddressMap<'a>) -> Option> { + if !matches!(self.kind().ok()?, ExternalKind::GlobalObject) { return None; } let va = self.external_object_va().ok()?; - let data = map.slice_from_va(va, ExternalTypelibInfo::SIZE).ok()?; - ExternalTypelibInfo::parse(data).ok() + let data = map.slice_from_va(va, ExternalGlobalObject::SIZE).ok()?; + ExternalGlobalObject::parse(data).ok() } } @@ -972,52 +975,64 @@ impl<'a> ExternalDeclareInfo<'a> { } } -/// External TypeLib reference descriptor. +/// A global object the runtime binds at load. /// -/// The target of an [`ExternalKind::TypeLib`] entry. The GUID is accessed -/// indirectly through a VA pointer; in the fixtures it is -/// `{FCFB3D23-A0FA-1068-A738-08002B3371B5}`, not an OCX's type library. +/// The target of an [`ExternalKind::GlobalObject`] entry: the class to bind +/// and where to put it. The runtime stores an AddRef'd reference to the +/// object of that class into the data slot, which the project's code then +/// reads as the object. In the fixtures the class is VB's `Global` object, +/// `{FCFB3D23-A0FA-1068-A738-08002B3371B5}`. /// /// # Layout /// /// | Offset | Size | Field | /// |--------|------|-------| -/// | 0x00 | 4 | `lpTypelibGuid` (VA to 16-byte GUID) | -/// | 0x04 | 4 | `lpRuntimeData` (VA in the zero-filled `.data` section) | +/// | 0x00 | 4 | `lpClsid` (VA to the 16-byte CLSID) | +/// | 0x04 | 4 | `lpDataSlot` (VA of the slot in the zero-filled `.data` section) | #[derive(Clone, Copy, Debug)] -pub struct ExternalTypelibInfo<'a> { +pub struct ExternalGlobalObject<'a> { bytes: &'a [u8], } -impl<'a> ExternalTypelibInfo<'a> { - /// Minimum size of the structure in bytes. +impl<'a> ExternalGlobalObject<'a> { + /// Size of the structure in bytes. pub const SIZE: usize = 0x08; - /// Parses an external typelib info from the given byte slice. + /// Parses a global object reference from the given byte slice. + /// + /// # Errors + /// + /// Returns [`Error::TooShort`] if `data.len() < 8`. pub fn parse(data: &'a [u8]) -> Result { let bytes = data.get(..Self::SIZE).ok_or(Error::TooShort { expected: Self::SIZE, actual: data.len(), - context: "ExternalTypelibInfo", + context: "ExternalGlobalObject", })?; Ok(Self { bytes }) } - /// VA to the 16-byte typelib GUID at offset 0x00. + /// VA of the 16-byte CLSID at offset 0x00. #[inline] - pub fn typelib_guid_va(&self) -> Result { + pub fn clsid_va(&self) -> Result { read_u32_le(self.bytes, 0x00) } - /// Resolves the typelib GUID by following the VA pointer. - pub fn typelib_guid(&self, map: &AddressMap<'a>) -> Option { - let va = self.typelib_guid_va().ok()?; + /// Resolves the CLSID by following [`clsid_va`](Self::clsid_va). + pub fn clsid(&self, map: &AddressMap<'a>) -> Option { + let va = self.clsid_va().ok()?; if va == 0 { return None; } let data = map.slice_from_va(va, 16).ok()?; Guid::from_bytes(data) } + + /// VA of the slot the runtime stores the object into, at offset 0x04. + #[inline] + pub fn data_slot_va(&self) -> Result { + read_u32_le(self.bytes, 0x04) + } } /// View over a variable-length external component entry: one ActiveX diff --git a/src/vb/formdata.rs b/src/vb/formdata.rs index 5c9e353..90f71e4 100644 --- a/src/vb/formdata.rs +++ b/src/vb/formdata.rs @@ -401,15 +401,22 @@ impl<'a> FormDataHeader<'a> { Guid::from_bytes(self.bytes.get(0x25..0x35)?) } - /// Form width in twips at offset 0x59. + /// The byte length of the form's stream at offset 0x59: the bytes from + /// offset 0x5D to the form's end (the `0x04` after its last record). + /// + /// Not a size of the form: `tests/fixtures/forms` Board states 483 here + /// and its client size (`ClientSize`, 4680 x 3090 twips) in its + /// properties; its stream ends 483 bytes after 0x5D. #[inline] - pub fn width(&self) -> Result { + pub fn stream_size(&self) -> Result { read_u32_le(self.bytes, 0x59) } - /// Form height in twips at offset 0x5D. + /// The byte length of the designer object's own record at offset 0x5D, + /// counted from 0x5D: its first child record starts that many bytes + /// after it (Board 87, Gauge 62 in `tests/fixtures/forms`). #[inline] - pub fn height(&self) -> Result { + pub fn properties_size(&self) -> Result { read_u32_le(self.bytes, 0x5D) } } @@ -667,8 +674,16 @@ impl<'a> FormControlRecord<'a> { } /// Decodes the property stream into an iterator of named property values. + /// + /// A hosted control's record (type 0xFF) states its extender's + /// properties after its ProgID ([`prog_id_bytes`](Self::prog_id_bytes)): + /// its place (`Bounds`, or `Left` and `Top` for one not drawn at run + /// time), index and tab index, around its persisted object. pub fn properties(&self) -> PropertyIter<'a> { - PropertyIter::new(self.properties, self.ctype) + let start = self + .prog_id_bytes() + .map_or(0, |bytes| bytes.len().saturating_add(3)); + PropertyIter::new_at(self.properties, self.ctype, start) } } diff --git a/src/vb/object.rs b/src/vb/object.rs index a8f21a8..791ba1e 100644 --- a/src/vb/object.rs +++ b/src/vb/object.rs @@ -3,7 +3,7 @@ //! These structures describe individual objects (forms, modules, classes) //! within a VB6 project. -use std::fmt; +use std::{fmt, vec}; use crate::{ addressmap::AddressMap, @@ -886,7 +886,7 @@ impl fmt::Display for IidKind { #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct TypedIidIter { /// Pre-collected typed IID entries. - inner: std::vec::IntoIter<(IidKind, Guid)>, + inner: vec::IntoIter<(IidKind, Guid)>, } impl Iterator for TypedIidIter { diff --git a/src/vb/property.rs b/src/vb/property.rs index 76ec17b..e4e0a8d 100644 --- a/src/vb/property.rs +++ b/src/vb/property.rs @@ -181,6 +181,10 @@ pub enum PropType { /// /// The layout is MSSTDFMT.DLL 6.01.9839's save and load of the object. DataFormat, + /// A persisted object, [`ObjectBlob`]: a `u32` tag, a `u32` length and + /// that many bytes (`OleObjectBlob`, a hosted control's persisted + /// properties). + ObjectBlob, /// Flag-only: opcode is emitted with NO value data following. /// /// Used for font sub-properties (FontSize, FontBold, FontItalic, @@ -206,6 +210,7 @@ impl PropType { Self::Size16 => Some(16), Self::Font => None, // 11 base + variable nameLen callback Self::DataFormat => None, // StdDataFormat IPersistStream blob + Self::ObjectBlob => None, // 8 bytes and the length they state Self::Str | Self::TagStr | Self::Picture => None, } } @@ -306,6 +311,52 @@ impl fmt::Display for ControlBounds { } } +/// A persisted object (`OleObjectBlob`): what a hosted control (an ActiveX +/// control, a project's UserControl) saved of its own properties, between +/// the extender's properties before and after it. +/// +/// # Binary Layout +/// +/// ```text +/// +0x00 u32 tag (0x0009424C in every fixture) +/// +0x04 u32 length +/// +0x08 [u8; length] the object's persisted data +/// ``` +/// +/// `tests/fixtures/forms` Gauge1 (72 bytes) and `activex` CommonDialog1 (76), +/// whose record goes on after it with its `Left` and `Top`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ObjectBlob { + /// The tag before the length. + pub tag: u32, + /// The persisted bytes. + pub data: Vec, +} + +impl ObjectBlob { + /// Parses a persisted object from raw bytes. + /// Returns the parsed value and bytes consumed, or `None` if too short. + pub fn parse(data: &[u8]) -> Option<(Self, usize)> { + let tag = read_u32_le(data, 0).ok()?; + let length = usize::try_from(read_u32_le(data, 4).ok()?).ok()?; + let end = length.checked_add(8)?; + let bytes = data.get(8..end)?; + Some(( + Self { + tag, + data: bytes.to_vec(), + }, + end, + )) + } +} + +impl fmt::Display for ObjectBlob { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} bytes", self.data.len()) + } +} + /// Client area rectangle from callback data (ClientLeft/Top/Width/Height). /// /// Written by the form's `vtable+0x34` callback when the ClientLeft @@ -793,6 +844,8 @@ pub enum PropertyValue { Picture(PictureData), /// StdDataFormat COM object (from MSSTDFMT.DLL). DataFormat(StdDataFormat), + /// A hosted control's persisted object. + ObjectBlob(ObjectBlob), } impl PropertyValue { @@ -801,7 +854,7 @@ impl PropertyValue { /// These strings are part of the public API contract and are suitable /// for database storage: `"Flag"`, `"Byte"`, `"Int16"`, `"Long"`, /// `"Single"`, `"Color"`, `"Str"`, `"TagStr"`, `"Bounds"`, - /// `"ClientRect"`, `"Font"`, `"Picture"`, and `"DataFormat"`. + /// `"ClientRect"`, `"Font"`, `"Picture"`, `"DataFormat"` and `"ObjectBlob"`. pub fn as_str(&self) -> &'static str { match self { Self::Flag => "Flag", @@ -818,6 +871,7 @@ impl PropertyValue { Self::Font(_) => "Font", Self::Picture(_) => "Picture", Self::DataFormat(_) => "DataFormat", + Self::ObjectBlob(_) => "ObjectBlob", } } @@ -872,6 +926,7 @@ impl fmt::Display for PropertyValue { Self::Font(font) => write!(f, "{font}"), Self::Picture(pic) => write!(f, "{pic}"), Self::DataFormat(df) => write!(f, "{df}"), + Self::ObjectBlob(blob) => write!(f, "{blob}"), } } } @@ -912,6 +967,13 @@ impl<'a> PropertyIter<'a> { } } + /// Creates an iterator over `data` that starts decoding at `pos`, so the + /// properties' offsets stay those of the whole stream (a hosted + /// control's, whose ProgID comes first). + pub fn new_at(data: &'a [u8], ctype: FormControlType, pos: usize) -> Self { + Self { data, pos, ctype } + } + /// Returns the offset in the stream of the next byte to decode: once /// the iterator has ended, that of the `0xFF` terminator when it ended /// there. @@ -1068,6 +1130,17 @@ impl<'a> Iterator for PropertyIter<'a> { self.pos = self.pos.checked_add(1)?; // consume opcode byte let value_offset = self.pos; + if desc.prop_type == PropType::ObjectBlob { + let (blob, consumed) = ObjectBlob::parse(self.data.get(self.pos..)?)?; + self.pos = self.pos.checked_add(consumed)?; + return Some(Property { + name: desc.name, + index: opcode, + value: PropertyValue::ObjectBlob(blob), + offset: value_offset, + }); + } + if desc.prop_type == PropType::Flag { return Some(Property { name: desc.name, diff --git a/tests/api.rs b/tests/api.rs index 15057cf..63b2823 100644 --- a/tests/api.rs +++ b/tests/api.rs @@ -12,26 +12,36 @@ mod common; -use std::collections::BTreeMap; +use std::{collections::BTreeMap, fs, sync::Arc}; use visualbasic::{ VbProject, imports::ImportSymbol, pcode::{ - calltarget::{CallResolver, CallSignature, Callee}, - decoder::Instruction, + calltarget::{ + CallResolver, CallSignature, Callee, InterfaceCatalog, InterfaceMember, InvokeKind, + LateTarget, RuntimeInterfaces, SlotInterfaces, + }, + decoder::{Instruction, ProcedureReturn}, framevar::{FrameOwner, FrameResolver, FrameVar}, - stackeffect::{Pop, Push}, + movement::{Fill, Move, Place}, + operand::Operand, + semantics::{ArgumentOrder, CallKind, OpcodeSemantics}, + stackeffect::{Pop, PrSource, Push}, + stacksim::{Cut, InstructionStack, ProcedureStack}, }, project::{MethodEntry, PCodeMethod}, - vb::constantpool::PoolEntry, + vb::{ + constantpool::PoolEntry, control::Guid, controlprop::ControlPropertyType, + designer::Designer, + }, }; -use crate::common::fixture; +use crate::common::{fixture, projects}; /// Reads fixture `name`, leaked so its project outlives the test's borrows. fn project(name: &str) -> &'static VbProject<'static> { - let bytes: &'static [u8] = Box::leak(std::fs::read(fixture(name)).unwrap().into_boxed_slice()); + let bytes: &'static [u8] = Box::leak(fs::read(fixture(name)).unwrap().into_boxed_slice()); Box::leak(Box::new(VbProject::from_bytes(bytes).unwrap())) } @@ -331,10 +341,8 @@ fn pool_entries_match_their_opcodes() { }; for insn in method.instructions().unwrap().flatten() { let index = match insn.operands[0] { - Some(visualbasic::pcode::operand::Operand::ConstPoolIndex(i)) => i, - Some(visualbasic::pcode::operand::Operand::ExternalCall { - import, .. - }) => import, + Some(Operand::ConstPoolIndex(i)) => i, + Some(Operand::ExternalCall { import, .. }) => import, _ => continue, }; let family = match insn.info.mnemonic { @@ -450,9 +458,8 @@ fn names_runtime_imports() { /// Every instruction that loads Pr says where from, with its operands. #[test] fn every_pr_load_has_a_source() { - use visualbasic::pcode::stackeffect::PrSource; let mut kinds: BTreeMap = BTreeMap::new(); - for name in crate::common::projects() { + for name in projects() { let project = project(&name); for object in project.objects().unwrap() { for entry in object.unwrap().methods().unwrap() { @@ -496,7 +503,6 @@ fn every_pr_load_has_a_source() { /// cleanup table's types for the locals the runtime releases. #[test] fn declares_frame_slots() { - use visualbasic::vb::controlprop::ControlPropertyType; let project = project("types"); let main = method(project, 0, 3); let instructions: Vec = main.instructions().unwrap().flatten().collect(); @@ -600,7 +606,7 @@ fn summarizes_error_handling() { #[test] fn runtime_signatures_match_their_calls() { let mut checked = 0; - for name in crate::common::projects() { + for name in projects() { let project = project(&name); let resolver = CallResolver::new(project).unwrap(); for (object_index, object) in project.objects().unwrap().enumerate() { @@ -644,7 +650,6 @@ fn object_index(project: &'static VbProject<'static>, name: &str) -> u16 { /// 256 control getters, then the object's own slots in method-link order. #[test] fn resolves_form_vtables() { - use visualbasic::vb::designer::Designer; let forms = project("forms"); let resolver = CallResolver::new(forms).unwrap(); let board = object_index(forms, "Board"); @@ -723,9 +728,8 @@ fn resolves_form_vtables() { /// from the frame. #[test] fn describes_procedure_returns() { - use visualbasic::pcode::decoder::ProcedureReturn; let mut forms = BTreeMap::new(); - for name in crate::common::projects() { + for name in projects() { let project = project(&name); for object in project.objects().unwrap() { for entry in object.unwrap().methods().unwrap() { @@ -733,10 +737,7 @@ fn describes_procedure_returns() { continue; }; for insn in method.instructions().unwrap().flatten() { - if !matches!( - insn.info.semantics, - visualbasic::pcode::semantics::OpcodeSemantics::Return - ) { + if !matches!(insn.info.semantics, OpcodeSemantics::Return) { assert!(insn.procedure_return().is_none()); continue; } @@ -846,7 +847,6 @@ fn reads_line_numbers() { /// argument on top like a late-bound call. #[test] fn resolves_raised_events() { - use visualbasic::pcode::semantics::{ArgumentOrder, CallKind, OpcodeSemantics}; let events = project("events"); let resolver = CallResolver::new(events).unwrap(); let source = object_index(events, "Source"); @@ -890,9 +890,8 @@ fn resolves_raised_events() { /// operands resolved. #[test] fn describes_movements() { - use visualbasic::pcode::movement::{Fill, Move, Place}; let mut moved = 0; - for name in crate::common::projects() { + for name in projects() { let project = project(&name); for object in project.objects().unwrap() { for entry in object.unwrap().methods().unwrap() { @@ -936,10 +935,6 @@ fn describes_movements() { /// simulate without a failure. #[test] fn resolves_the_control_array_object() { - use visualbasic::pcode::{ - calltarget::RuntimeInterfaces, - stacksim::{Cut, InstructionStack, ProcedureStack}, - }; let forms = project("forms"); let board = object_index(forms, "Board"); let resolver = CallResolver::new(forms).unwrap(); @@ -972,11 +967,6 @@ fn resolves_the_control_array_object() { /// it describes; without it they stay [`Callee::External`]. #[test] fn resolves_through_an_interface_catalog() { - use std::sync::Arc; - use visualbasic::{ - pcode::calltarget::{InterfaceCatalog, InterfaceMember, InvokeKind}, - vb::control::Guid, - }; let forms = project("forms"); let board = object_index(forms, "Board"); let plain = CallResolver::new(forms).unwrap(); @@ -1043,7 +1033,6 @@ fn resolves_through_an_interface_catalog() { /// one slot. The procedure simulates without a failure. #[test] fn resolves_member_variable_accessors() { - use visualbasic::pcode::stacksim::{Cut, InstructionStack, ProcedureStack}; let members = project("members"); let program = object_index(members, "Program"); let resolver = CallResolver::new(members).unwrap(); @@ -1129,7 +1118,6 @@ fn resolves_designer_vtables() { /// `rtcErrObj` returned, `_ErrObject`. #[test] fn resolves_calls_through_slot_interfaces() { - use visualbasic::pcode::calltarget::{RuntimeInterfaces, SlotInterfaces}; let iraw = "{5D1E7A10-6C2B-4E1A-9B7F-3A2C1D0E0F02}"; let externals = |name: &str| { let project = project(name); @@ -1146,8 +1134,9 @@ fn resolves_calls_through_slot_interfaces() { let mut last_load = None; for (insn, record) in code.iter().zip(&stack.instructions) { let pr = match record { - visualbasic::pcode::stacksim::InstructionStack::Reached { pr, .. } - | visualbasic::pcode::stacksim::InstructionStack::Cut { pr, .. } => *pr, + InstructionStack::Reached { pr, .. } | InstructionStack::Cut { pr, .. } => { + *pr + } _ => last_load, }; if let Some(source) = insn.pr_source() { @@ -1190,16 +1179,6 @@ fn resolves_calls_through_slot_interfaces() { /// stored last. #[test] fn slots_take_the_interface_a_call_returns() { - use std::sync::Arc; - - use visualbasic::{ - pcode::{ - calltarget::{InterfaceCatalog, InterfaceMember, InvokeKind, SlotInterfaces}, - stackeffect::PrSource, - }, - vb::control::Guid, - }; - /// `IRaw`'s `GetSelf` (0x38), `GetDouble` (0x1C) and `GetUnknown` /// (0x34), `GetSelf` returning `IRaw` and `GetUnknown` `IUnknown` when /// `typed`. Both results pass through the same temporary (`var_E4`). @@ -1249,21 +1228,21 @@ fn slots_take_the_interface_a_call_returns() { // Pr where the simulation reached, else the last Pr load before // the instruction (a call with no catalog entry cuts the path). let mut last_load = None; - let prs: Vec<_> = code - .iter() - .zip(&stack.instructions) - .map(|(insn, record)| { - let pr = match record { - visualbasic::pcode::stacksim::InstructionStack::Reached { pr, .. } - | visualbasic::pcode::stacksim::InstructionStack::Cut { pr, .. } => *pr, - _ => last_load, - }; - if let Some(source) = insn.pr_source() { - last_load = Some(source); - } - pr - }) - .collect(); + let prs: Vec<_> = + code.iter() + .zip(&stack.instructions) + .map(|(insn, record)| { + let pr = match record { + InstructionStack::Reached { pr, .. } + | InstructionStack::Cut { pr, .. } => *pr, + _ => last_load, + }; + if let Some(source) = insn.pr_source() { + last_load = Some(source); + } + pr + }) + .collect(); for (index, insn) in code.iter().enumerate() { let pr = prs[index]; let Some(call) = resolver.resolve_with_slots(object, insn, pr.as_ref(), &slots) @@ -1284,9 +1263,7 @@ fn slots_take_the_interface_a_call_returns() { .iter() .find(|i| i.info.mnemonic == "FStAdFunc") .unwrap(); - let Some(Some(visualbasic::pcode::operand::Operand::StackVar(target))) = - store.operands.first() - else { + let Some(Some(Operand::StackVar(target))) = store.operands.first() else { panic!("{store:?}"); }; let then_resolved = code.iter().enumerate().any(|(at, later)| { @@ -1358,8 +1335,6 @@ fn slots_take_the_interface_a_call_returns() { /// `VCallHresult` names `IRaw` on its copy of the parameter. #[test] fn arguments_carry_interfaces_between_procedures() { - use visualbasic::pcode::calltarget::SlotInterfaces; - let vtable = project("vtable"); let program = object_index(vtable, "Program"); let resolver = CallResolver::new(vtable).unwrap(); @@ -1410,9 +1385,7 @@ fn late_targets( resolver: &CallResolver<'static, 'static>, object: u16, index: u16, -) -> Vec<(i32, Option)> { - use visualbasic::pcode::stacksim::InstructionStack; - +) -> Vec<(i32, Option)> { let method = method(project, object, usize::from(index)); let code: Vec = method.instructions().unwrap().flatten().collect(); let (stack, slots) = resolver.simulate_procedure(object, &code, method.pcode_bytes()); @@ -1447,8 +1420,6 @@ fn late_targets( /// an object sets, a call calls). #[test] fn late_calls_reach_a_hosted_user_controls_procedures() { - use visualbasic::pcode::calltarget::{InvokeKind, LateTarget}; - let project = project_with_dispids(); let resolver = CallResolver::new(project).unwrap(); let host = object_index(project, "Host"); @@ -1515,15 +1486,6 @@ fn late_calls_reach_a_hosted_user_controls_procedures() { /// catalog they stay unresolved. #[test] fn late_calls_reach_a_hosted_controls_extender() { - use std::sync::Arc; - - use visualbasic::{ - pcode::calltarget::{ - InterfaceCatalog, InterfaceMember, InvokeKind, LateTarget, RuntimeInterfaces, - }, - vb::control::Guid, - }; - /// `_VBControlExtender`'s members at the DISPIDs `VB6.OLB` declares. struct Extender; impl InterfaceCatalog for Extender { @@ -1676,13 +1638,6 @@ fn late_calls_reach_a_hosted_controls_extender() { /// interface. #[test] fn late_calls_reach_an_activex_controls_class() { - use std::sync::Arc; - - use visualbasic::{ - pcode::calltarget::{InterfaceCatalog, InterfaceMember, InvokeKind, LateTarget}, - vb::control::Guid, - }; - /// Any member of any interface, named by its interface's IID. struct Any; impl InterfaceCatalog for Any { @@ -1794,13 +1749,6 @@ fn late_calls_reach_an_activex_controls_class() { /// class is known, given a catalog that describes every external member. #[test] fn every_call_by_dispid_reaches_a_member() { - use std::sync::Arc; - - use visualbasic::{ - pcode::calltarget::{InterfaceCatalog, InterfaceMember, InvokeKind}, - vb::control::Guid, - }; - /// Every member of every interface, each invoked every way. struct Every; impl InterfaceCatalog for Every { diff --git a/tests/common/mod.rs b/tests/common/mod.rs index c4e8535..76d05a4 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -2,13 +2,16 @@ #![allow(dead_code)] -use std::path::{Path, PathBuf}; +use std::{ + fs, + path::{Path, PathBuf}, +}; /// The fixture projects: every directory of `tests/fixtures` holding /// `/.exe` (or `.dll`, `.ocx`), sorted by name. pub fn projects() -> Vec { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); - let mut names: Vec = std::fs::read_dir(&root) + let mut names: Vec = fs::read_dir(&root) .expect("fixtures directory") .filter_map(|entry| entry.ok()?.file_name().into_string().ok()) .filter(|name| fixture(name).is_file()) diff --git a/tests/descriptors.rs b/tests/descriptors.rs index 19aa41a..9e5ab34 100644 --- a/tests/descriptors.rs +++ b/tests/descriptors.rs @@ -12,6 +12,8 @@ mod common; +use std::fs; + use visualbasic::{ VbObject, VbProject, pcode::decoder::PoolEntryRole, @@ -32,7 +34,7 @@ use crate::common::{fixture, projects}; /// Reads fixture `name`, leaked so its project outlives the test's borrows. fn project(name: &str) -> &'static VbProject<'static> { - let bytes: &'static [u8] = Box::leak(std::fs::read(fixture(name)).unwrap().into_boxed_slice()); + let bytes: &'static [u8] = Box::leak(fs::read(fixture(name)).unwrap().into_boxed_slice()); Box::leak(Box::new(VbProject::from_bytes(bytes).unwrap())) } @@ -332,3 +334,49 @@ fn header_and_type_library_references_have_their_size() { tails.dedup(); assert_eq!(tails, [0x02085A90]); } + +/// Each connected sink slot of a P-Code object names the procedure it calls: +/// `Listener`'s `m_Source` handlers in slot order (`events`), and the hosted +/// `Winsock1` control's four, whose sink leads with its extender's events +/// (`activex`). A natively compiled class has no method table to resolve +/// them in (`events-native`). +#[test] +fn sink_slots_name_their_handler_procedures() { + let handlers = |name: &str, object_name: &str, control: &str| -> Vec> { + let project = project(name); + let object = object(project, object_name); + object + .events(None) + .unwrap() + .into_iter() + .filter(|b| b.control_name == control) + .map(|b| { + b.method_index.map(|index| { + object + .method_name(index) + .ok() + .and_then(|n| n.as_str()) + .map(|n| n.into_owned()) + .unwrap_or_default() + }) + }) + .collect() + }; + assert_eq!( + handlers("events", "Listener", "m_Source"), + [ + Some("m_Source_Started".to_string()), + Some("m_Source_Ticked".to_string()), + Some("m_Source_Named".to_string()), + ] + ); + // `Client`'s handlers resolve, though its name table leaves them unnamed. + let winsock = handlers("activex", "Client", "Winsock1"); + assert_eq!(winsock.len(), 4); + assert!(winsock.iter().all(Option::is_some), "{winsock:?}"); + assert!( + handlers("events-native", "Listener", "m_Source") + .iter() + .all(Option::is_none) + ); +} diff --git a/tests/extents.rs b/tests/extents.rs index d7b51fc..8975578 100644 --- a/tests/extents.rs +++ b/tests/extents.rs @@ -12,7 +12,7 @@ mod common; -use std::collections::BTreeSet; +use std::{collections::BTreeSet, fs}; use goblin::{ options::ParseMode, @@ -31,7 +31,7 @@ use crate::common::{fixture, projects}; /// Reads fixture `name`, leaked so its project outlives the test's borrows. fn project(name: &str) -> (&'static [u8], &'static VbProject<'static>) { - let bytes: &'static [u8] = Box::leak(std::fs::read(fixture(name)).unwrap().into_boxed_slice()); + let bytes: &'static [u8] = Box::leak(fs::read(fixture(name)).unwrap().into_boxed_slice()); ( bytes, Box::leak(Box::new(VbProject::from_bytes(bytes).unwrap())), @@ -177,53 +177,65 @@ fn every_kind_is_found() { assert!(found.contains(kind), "{name}: no {kind:?}"); } }; - use StructureKind::*; expect( "forms", &[ - VbHeader, - ProjectData, - ObjectTable, - ProjectInfo2, - EventSource, - ObjectDescriptor, - ObjectInfo, - OptionalObjectInfo, - PrivateObjectDescriptor, - MethodTable, - MethodLinkTable, - PointerTable, - Name, - Guid, - FunctionType, - ConstantPool, - StringConstant, - ProcedureDescriptor, - Pcode, - ControlInfo, - EventSinkVtable, - GuiTableEntry, - FormData, - TypeLibReference, + StructureKind::VbHeader, + StructureKind::ProjectData, + StructureKind::ObjectTable, + StructureKind::ProjectInfo2, + StructureKind::EventSource, + StructureKind::ObjectDescriptor, + StructureKind::ObjectInfo, + StructureKind::OptionalObjectInfo, + StructureKind::PrivateObjectDescriptor, + StructureKind::MethodTable, + StructureKind::MethodLinkTable, + StructureKind::PointerTable, + StructureKind::Name, + StructureKind::Guid, + StructureKind::FunctionType, + StructureKind::ConstantPool, + StructureKind::StringConstant, + StructureKind::ProcedureDescriptor, + StructureKind::Pcode, + StructureKind::ControlInfo, + StructureKind::EventSinkVtable, + StructureKind::GuiTableEntry, + StructureKind::FormData, + StructureKind::TypeLibReference, ], ); - expect("ocx", &[Component, ComRegistration]); - expect("events", &[DispidMap]); + expect( + "ocx", + &[StructureKind::Component, StructureKind::ComRegistration], + ); + expect("events", &[StructureKind::DispidMap]); expect( "types", - &[ExternalTable, DeclareDescriptor, OptionalDefaults], + &[ + StructureKind::ExternalTable, + StructureKind::DeclareDescriptor, + StructureKind::OptionalDefaults, + ], + ); + expect( + "members", + &[StructureKind::Member, StructureKind::InterfaceReference], + ); + expect("late", &[StructureKind::MemberName]); + expect("coverage", &[StructureKind::RecordLayout]); + expect( + "typerefs", + &[StructureKind::RecordReference, StructureKind::RecordLayout], ); - expect("members", &[Member, InterfaceReference]); - expect("late", &[MemberName]); - expect("coverage", &[RecordLayout]); - expect("typerefs", &[RecordReference, RecordLayout]); expect( "errors-native", &[ - UnwindRecord, - ErrorHandlerTable, - ResumeTable, - LineNumberTable, + StructureKind::UnwindRecord, + StructureKind::ErrorHandlerTable, + StructureKind::ResumeTable, + StructureKind::LineNumberTable, ], ); } diff --git a/tests/fixtures.rs b/tests/fixtures.rs index cb1a325..4f7ede8 100644 --- a/tests/fixtures.rs +++ b/tests/fixtures.rs @@ -12,7 +12,7 @@ mod common; -use std::collections::BTreeSet; +use std::{collections::BTreeSet, fs}; use visualbasic::{VbProject, project::MethodEntry}; @@ -27,7 +27,7 @@ use crate::common::{fixture, projects}; fn every_procedure_decodes_to_its_end() { let mut procedures = 0usize; for name in &projects() { - let bytes = std::fs::read(fixture(name)).expect("fixture readable"); + let bytes = fs::read(fixture(name)).expect("fixture readable"); let project = VbProject::from_bytes(&bytes).expect("a VB6 project"); for object in project.objects().expect("objects") { let object = object.expect("object"); diff --git a/tests/hosted.rs b/tests/hosted.rs new file mode 100644 index 0000000..f149983 --- /dev/null +++ b/tests/hosted.rs @@ -0,0 +1,227 @@ +//! A hosted control's record (an ActiveX control, a project's UserControl: +//! type 0xFF) states its extender's properties after its ProgID: its place, +//! index and tab index, around the object it persisted. Every fixture's +//! source states them too, so the source is the oracle. + +#![allow( + clippy::arithmetic_side_effects, + clippy::expect_used, + clippy::indexing_slicing, + clippy::panic, + clippy::unwrap_used +)] + +mod common; + +use std::{collections::BTreeMap, fs, path::Path}; + +use common::{fixture, projects}; +use visualbasic::{ + VbObject, VbProject, + vb::{ + formdata::{FormControlType, FormDataParser}, + property::PropertyValue, + }, +}; + +/// The project of fixture `name`, alive for the test. +fn project(name: &str) -> &'static VbProject<'static> { + let bytes: &'static [u8] = Box::leak(fs::read(fixture(name)).unwrap().into_boxed_slice()); + Box::leak(Box::new(VbProject::from_bytes(bytes).unwrap())) +} + +/// The object named `name`. +fn object(project: &'static VbProject<'static>, name: &str) -> VbObject<'static, 'static> { + project + .objects() + .unwrap() + .map(Result::unwrap) + .find(|o| o.name().unwrap() == name) + .unwrap_or_else(|| panic!("no object {name}")) +} + +/// The form data of the designer `name`. +fn form_data(project: &'static VbProject<'static>, name: &str) -> FormDataParser<'static> { + let designer = object(project, name); + project + .gui_entries() + .unwrap() + .find_map(|entry| { + designer + .form_data_from_gui_entry(&entry) + .filter(|data| data.form_name() == name) + }) + .unwrap_or_else(|| panic!("{name}: no form data")) +} + +/// What a source file states of its hosted controls: the designer's name, +/// then per control (by name and index) its `Left`, `Top`, `Width`, +/// `Height` and `TabIndex`. +type Stated = ( + String, + BTreeMap<(String, Option), BTreeMap>, +); + +/// Reads the hosted controls of the designer source `text`: each +/// `Begin . ` block whose library is not `VB`, its +/// own lines only (`BeginProperty` blocks and nested controls skipped). +fn stated(text: &str) -> Option { + let mut designer = None; + let mut open: Vec)>> = Vec::new(); + let mut in_property = 0; + let mut controls = BTreeMap::new(); + for line in text.lines().map(str::trim) { + if line.starts_with("BeginProperty") { + in_property += 1; + } else if line.starts_with("EndProperty") { + in_property -= 1; + } else if let Some(rest) = line.strip_prefix("Begin ") { + let mut words = rest.split_whitespace(); + let class = words.next().unwrap(); + let name = words.next().unwrap().to_string(); + if designer.is_none() { + designer = Some(name); + open.push(None); + } else if class.starts_with("VB.") { + open.push(None); + } else { + open.push(Some((name, BTreeMap::new()))); + } + } else if line == "End" { + if let Some(Some((name, values))) = open.pop() { + let index = values.get("Index").copied(); + controls.insert((name, index), values); + } + } else if in_property == 0 + && let Some(Some((_, values))) = open.last_mut() + && let Some((key, value)) = line.split_once('=') + && let Ok(number) = value.split('\'').next().unwrap().trim().parse::() + { + values.insert(key.trim().to_string(), number); + } + } + Some((designer?, controls)) +} + +/// Every hosted control of every fixture decodes its extender's properties +/// to the stream's terminator, and its place, index and tab index are the +/// ones its source states, except where the designer writes another value: `Bounds` for a control drawn at run time +/// (`forms` Gauge1: 120, 2280, 1500, 600), `Left` and `Top` alone for one +/// that is not (`activex` CommonDialog1: 1680, 120), after its persisted +/// object. +#[test] +fn a_hosted_controls_place_is_its_sources() { + let mut checked = 0; + let mut mismatches = Vec::new(); + for name in projects() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(&name); + let mut sources: Vec<_> = fs::read_dir(&dir) + .unwrap() + .filter_map(|entry| entry.ok().map(|e| e.path())) + .filter(|path| { + matches!( + path.extension().and_then(|e| e.to_str()), + Some("frm" | "ctl" | "pag" | "dob") + ) + }) + .collect(); + sources.sort(); + for source in sources { + let Some((designer, controls)) = stated(&fs::read_to_string(&source).unwrap()) else { + continue; + }; + if controls.is_empty() { + continue; + } + let data = form_data(project(&name), &designer); + for ((control, index), values) in &controls { + let record = data + .controls() + .iter() + .find(|r| { + r.name() == control.as_str() && r.array_index().map(i64::from) == *index + }) + .unwrap_or_else(|| panic!("{name}/{designer}: no record {control}")); + assert_eq!(record.control_type(), FormControlType::Unknown(0xFF)); + let mut iter = record.properties(); + let mut decoded = BTreeMap::new(); + for property in iter.by_ref() { + match property.value { + PropertyValue::Bounds(b) => { + decoded.insert("Left", i64::from(b.left)); + decoded.insert("Top", i64::from(b.top)); + decoded.insert("Width", i64::from(b.width)); + decoded.insert("Height", i64::from(b.height)); + } + PropertyValue::Long(v) => { + decoded.insert(property.name, i64::from(v)); + } + PropertyValue::Int16(v) => { + decoded.insert(property.name, i64::from(v)); + } + _ => {} + } + } + // The stream ends at its terminator, which the record's raw + // bytes leave out. + assert!( + iter.at_terminator() || iter.position() == record.raw_properties().len(), + "{name}/{designer}/{control}: decoding stopped at {} of {}", + iter.position(), + record.raw_properties().len() + ); + for key in ["Left", "Top", "Width", "Height", "Index", "TabIndex"] { + if decoded.get(key) != values.get(key) { + mismatches.push(format!( + "{name}/{designer}/{control}.{key}: {:?} stated {:?}", + decoded.get(key), + values.get(key) + )); + } + } + checked += 1; + } + } + } + // Where the compiled record holds another value than the source, as the + // designer writes it (`extender` Board): a control invisible at run time + // (Ghost1) stores its place without a size, and neither it nor one that + // cannot take the focus (NoFocus1) has a tab index; the tab slots they + // leave (2 and 4) are given to the later Light1 and Coords1. + assert_eq!( + mismatches, + [ + "extender/Board/Coords1.TabIndex: Some(4) stated Some(8)", + "extender/Board/Ghost1.Width: None stated Some(1500)", + "extender/Board/Ghost1.Height: None stated Some(600)", + "extender/Board/Ghost1.TabIndex: None stated Some(4)", + "extender/Board/Light1.TabIndex: Some(2) stated Some(9)", + "extender/Board/NoFocus1.TabIndex: None stated Some(2)", + ] + ); + assert!(checked >= 10, "only {checked} hosted controls checked"); +} + +/// The header's words at 0x59 and 0x5D are lengths, not the form's size: +/// the form's stream runs from 0x5D for the first, and its first child +/// record starts the second's bytes after 0x5D (`forms` Board 483 and 87, +/// its client size 4680 x 3090 twips in its `ClientSize`). +#[test] +fn the_header_states_the_streams_lengths() { + let data = form_data(project("forms"), "Board"); + assert_eq!(data.header().stream_size().unwrap(), 483); + assert_eq!(data.header().properties_size().unwrap(), 87); + let client = data + .form_properties_decoded() + .find_map(|p| match p.value { + PropertyValue::ClientRect(r) => Some((r.width, r.height)), + _ => None, + }) + .unwrap(); + assert_eq!(client, (4680, 3090)); + let first = data.controls().first().unwrap(); + // The record starts with its marker byte there; its size field follows. + assert_eq!(first.offset_in_blob(), 0x5D + 87 + 1); +} diff --git a/tests/stack.rs b/tests/stack.rs index f91299e..df2fbd0 100644 --- a/tests/stack.rs +++ b/tests/stack.rs @@ -22,6 +22,7 @@ mod common; use std::{ collections::{BTreeMap, BTreeSet}, fmt::Write, + fs, }; use visualbasic::{ @@ -29,6 +30,7 @@ use visualbasic::{ pcode::{ calltarget::{CallResolver, CallSignature, SlotInterfaces}, decoder::Instruction, + operand::Operand, semantics::OpcodeSemantics, stackeffect::PrSource, stacksim::{Cut, InstructionStack, ProcedureStack}, @@ -122,9 +124,10 @@ impl Report { .iter() .filter(|i| { matches!(i.info.semantics, OpcodeSemantics::GoSub) - && i.operands.iter().flatten().any(|o| { - matches!(o, visualbasic::pcode::operand::Operand::JumpTable { .. }) - }) + && i.operands + .iter() + .flatten() + .any(|o| matches!(o, Operand::JumpTable { .. })) }) .count(); for conflict in &stack.merge_conflicts { @@ -182,8 +185,7 @@ type Perturb = fn simulate_all(perturb: &Perturb) -> Report { let mut report = Report::default(); for name in &projects() { - let bytes: &'static [u8] = - Box::leak(std::fs::read(fixture(name)).unwrap().into_boxed_slice()); + let bytes: &'static [u8] = Box::leak(fs::read(fixture(name)).unwrap().into_boxed_slice()); let project: &'static VbProject<'static> = Box::leak(Box::new(VbProject::from_bytes(bytes).unwrap())); let resolver = CallResolver::new(project).unwrap(); @@ -265,7 +267,7 @@ fn a_wrong_arity_breaks_the_balance() { fn coverage_census() { let mut counts: BTreeMap<(u8, u8), (usize, &'static str)> = BTreeMap::new(); for name in &projects() { - let bytes = std::fs::read(fixture(name)).unwrap(); + let bytes = fs::read(fixture(name)).unwrap(); let project = VbProject::from_bytes(&bytes).unwrap(); for object in project.objects().unwrap() { for entry in object.unwrap().methods().unwrap() { diff --git a/tests/structures.rs b/tests/structures.rs index 470b054..8c1205c 100644 --- a/tests/structures.rs +++ b/tests/structures.rs @@ -15,22 +15,29 @@ mod common; use std::{ collections::{BTreeMap, HashSet}, + fs, + path::Path, time::{Duration, Instant}, }; use visualbasic::{ - CompilationMode, EntrypointKind, Error, MethodEntry, RecognitionFailure, VbObject, VbProject, - project::{CodeEntry, CodeEntryKind, MethodLinkKind, MethodNameResult, NameOwner}, + CodeEntrypoint, CompilationMode, EntrypointKind, Error, MethodEntry, RecognitionFailure, + VbObject, VbProject, + project::{CodeEntry, CodeEntryKind, Instancing, MethodLinkKind, MethodNameResult, NameOwner}, vb::{ comreg::ComRegData, constantpool::PoolEntry, control::Guid, controlprop::{ControlPropertyEntry, ControlPropertyType, RecordLayout}, + designer::Designer, external::{CallApiStub, ConversionKind, ExternalKind}, + formdata::FormControlType, functype::ArgType, member::MemberKind, native::{ProcUnwindInfo, ProcedureUnwind}, projectinfo2::{ControlTypeIter, ProjectInfo2, read_name_strings}, + property::{ControlBounds, PropertyValue}, + publicbytes::ClassFormPublicBytes, }, }; @@ -38,7 +45,7 @@ use crate::common::{fixture, projects}; /// Reads fixture `name`, leaked so its project outlives the test's borrows. fn project(name: &str) -> &'static VbProject<'static> { - let bytes: &'static [u8] = Box::leak(std::fs::read(fixture(name)).unwrap().into_boxed_slice()); + let bytes: &'static [u8] = Box::leak(fs::read(fixture(name)).unwrap().into_boxed_slice()); Box::leak(Box::new(VbProject::from_bytes(bytes).unwrap())) } @@ -162,8 +169,8 @@ fn comreg_flags_name_the_user_controls() { } } -/// `as_typelib` answers only for TypeLib entries, `as_declare` only for -/// Declares. +/// `as_global_object` answers only for global object entries, `as_declare` +/// only for Declares. #[test] fn external_entries_check_their_kind() { let exprs = project("exprs"); @@ -172,27 +179,24 @@ fn external_entries_check_their_kind() { assert_eq!(entries.len(), 2); for entry in &entries { assert_eq!(entry.kind().unwrap(), ExternalKind::DeclareFunction); - assert!(entry.as_typelib(map).is_none()); + assert!(entry.as_global_object(map).is_none()); assert!(entry.as_declare(map).is_some()); } let dispid = project("dispid"); let map = dispid.address_map(); - let typelib = dispid + let global = dispid .externals() .unwrap() .map(Result::unwrap) - .find(|e| e.kind().unwrap() == ExternalKind::TypeLib) + .find(|e| e.kind().unwrap() == ExternalKind::GlobalObject) .unwrap(); - assert!(typelib.as_declare(map).is_none()); + assert!(global.as_declare(map).is_none()); + let object = global.as_global_object(map).unwrap(); assert_eq!( - typelib - .as_typelib(map) - .unwrap() - .typelib_guid(map) - .unwrap() - .to_string(), + object.clsid(map).unwrap().to_string(), "{FCFB3D23-A0FA-1068-A738-08002B3371B5}" ); + assert_ne!(object.data_slot_va().unwrap(), 0); } /// A Declare's external table entry is its DllFunctionCall descriptor: by @@ -240,9 +244,7 @@ fn declare_entries_are_dllfunctioncall_descriptors() { } /// The entries `(offset, type)` of a variable descriptor table. -fn entries( - table: &visualbasic::vb::publicbytes::ClassFormPublicBytes<'_>, -) -> Vec<(u16, ControlPropertyType)> { +fn entries(table: &ClassFormPublicBytes<'_>) -> Vec<(u16, ControlPropertyType)> { table .control_entries() .map(|e| (e.frame_offset().unwrap(), e.property_type())) @@ -1501,7 +1503,7 @@ fn project_path_is_utf16() { /// starts `push imm32` without it is not a VB6 file. #[test] fn entry_point_push_needs_the_magic() { - let bytes = std::fs::read(fixture("hello")).unwrap(); + let bytes = fs::read(fixture("hello")).unwrap(); let pe = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize; let entry_rva = u32::from_le_bytes(bytes[pe + 0x28..pe + 0x2C].try_into().unwrap()); // .text is mapped at file offset == RVA in the fixtures. @@ -1533,7 +1535,7 @@ fn entry_point_push_needs_the_magic() { #[test] fn corrupt_counts_end_quickly() { let path = fixture("calls"); - let bytes = std::fs::read(&path).unwrap(); + let bytes = fs::read(&path).unwrap(); let clean = project("calls"); let counter = object(clean, "Counter"); let opt = counter.optional_info().unwrap(); @@ -1564,7 +1566,7 @@ fn corrupt_counts_end_quickly() { ); assert!(controls <= mutant.len() / 0x28); // The other objects' entry points are those of the clean file. - let program = |entries: &[visualbasic::CodeEntrypoint<'_>]| -> Vec { + let program = |entries: &[CodeEntrypoint<'_>]| -> Vec { entries .iter() .filter(|e| e.object_index == Some(0)) @@ -1578,7 +1580,7 @@ fn corrupt_counts_end_quickly() { assert!(!program(&entries).is_empty()); // exprs: a corrupt external count still yields the two Declares first. - let bytes = std::fs::read(fixture("exprs")).unwrap(); + let bytes = fs::read(fixture("exprs")).unwrap(); let clean = project("exprs"); let pd = clean.vb_header().project_data_va().unwrap(); let count_offset = clean.address_map().va_to_offset(pd + 0x238).unwrap(); @@ -1736,7 +1738,6 @@ fn hosted_controls_name_their_extender_events() { /// UserControl and a PropertyPage (`ocx`, an OCX). #[test] fn designers_of_every_kind() { - use visualbasic::vb::designer::Designer; for (fixture, name, designer) in [ ("mdi", "Frame", Designer::MdiForm), ("mdi", "Child", Designer::Form), @@ -1791,7 +1792,6 @@ fn method_links_in_vtable_order() { /// `PaletteMode = 0`, `ScaleMode = 1` with the default drawing flags). #[test] fn designer_records_decode_with_their_own_table() { - use visualbasic::vb::{formdata::FormControlType, property::PropertyValue}; for (fixture, name, form_type, property, value) in [ ( "forms", @@ -1869,7 +1869,6 @@ fn designer_records_decode_with_their_own_table() { /// stored as 2400). #[test] fn control_bounds_and_coordinates() { - use visualbasic::vb::property::{ControlBounds, PropertyValue}; let project = project("geometry"); let layout = object(project, "Layout"); let form_data = project @@ -1938,7 +1937,6 @@ fn extender_flags_follow_misc_status() { /// by-value Variant. #[test] fn event_conversions_by_parameter_type() { - use ConversionKind::*; let project = project("extender"); let coords = project .components() @@ -1954,24 +1952,27 @@ fn event_conversions_by_parameter_type() { kinds, [ vec![ - (0, false, XPosPixels), - (1, false, YPosPixels), - (2, false, XSizePixels), - (3, false, YSizePixels) + (0, false, ConversionKind::XPosPixels), + (1, false, ConversionKind::YPosPixels), + (2, false, ConversionKind::XSizePixels), + (3, false, ConversionKind::YSizePixels) ], vec![ - (0, false, XPosHimetric), - (1, false, YPosHimetric), - (2, false, XSizeHimetric), - (3, false, YSizeHimetric) + (0, false, ConversionKind::XPosHimetric), + (1, false, ConversionKind::YPosHimetric), + (2, false, ConversionKind::XSizeHimetric), + (3, false, ConversionKind::YSizeHimetric) ], vec![], vec![], - vec![(0, false, Variant)], + vec![(0, false, ConversionKind::Variant)], vec![], ] ); - assert_eq!(XSizeHimetric.stdole_type(), Some("OLE_XSIZE_HIMETRIC")); + assert_eq!( + ConversionKind::XSizeHimetric.stdole_type(), + Some("OLE_XSIZE_HIMETRIC") + ); assert_eq!(coords.control_flags(), 0x2057); } @@ -1984,12 +1985,10 @@ fn event_conversions_by_parameter_type() { /// `FontTransparent`; a menu's items follow it in the menu section. #[test] fn form_records_match_their_source() { - use visualbasic::vb::{formdata::FormControlType, property::PropertyValue}; - // `(control, property, value)` from the `.frm`: `Begin VB. // ` blocks, `BeginProperty` blocks skipped, comments dropped. - let source = std::fs::read_to_string( - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/props/Props.frm"), + let source = fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/props/Props.frm"), ) .unwrap(); let mut expected: Vec<(String, String, String)> = Vec::new(); @@ -2175,8 +2174,6 @@ fn form_records_match_their_source() { /// private, and a module or a designer object has none. #[test] fn classes_report_their_instancing() { - use visualbasic::project::Instancing; - let server = project("server"); for (class, instancing) in [ ("Hidden", Instancing::Private),