Refactor and move Linux code to separate branch

This commit is contained in:
a2x
2024-04-03 02:59:30 +11:00
parent 86dc0fa8f6
commit 3a935f5d73
229 changed files with 705 additions and 121739 deletions

View File

@@ -1,16 +1,16 @@
use std::env;
use log::debug;
use memflow::prelude::v1::*;
use pelite::pattern;
use pelite::pe64::{Pe, PeView};
use serde::{Deserialize, Serialize};
use skidscan_macros::signature;
use crate::error::{Error, Result};
use crate::source_engine::KeyboardKey;
use crate::source2::KeyboardKey;
/// Represents a key button.
#[derive(Debug, Deserialize, Serialize)]
pub struct Button {
pub name: String,
@@ -18,27 +18,21 @@ pub struct Button {
}
pub fn buttons(process: &mut IntoProcessInstanceArcBox<'_>) -> Result<Vec<Button>> {
let (module_name, sig) = match env::consts::OS {
"linux" => (
"libclient.so",
signature!("48 8B 15 ? ? ? ? 48 89 83 ? ? ? ? 48 85 D2"),
),
"windows" => (
"client.dll",
signature!("48 8B 15 ? ? ? ? 48 85 D2 74 ? 0F 1F 40"),
),
os => panic!("unsupported os: {}", os),
};
let module = process.module_by_name(&module_name)?;
let module = process.module_by_name("client.dll")?;
let buf = process.read_raw(module.base, module.size as _)?;
let list_addr = sig
.scan(&buf)
.and_then(|ptr| process.read_addr64_rip(module.base + ptr).ok())
.ok_or_else(|| Error::Other("unable to read button list address"))?;
let view = PeView::from_bytes(&buf)?;
read_buttons(process, &module, list_addr)
let mut save = [0; 2];
if !view
.scanner()
.finds_code(pattern!("488b15${'} 4885d2 74? 0f1f40"), &mut save)
{
return Err(Error::Other("unable to find button list signature"));
}
read_buttons(process, &module, module.base + save[1])
}
fn read_buttons(
@@ -70,6 +64,7 @@ fn read_buttons(
key_ptr = key.next;
}
// Sort buttons by name.
buttons.sort_unstable_by(|a, b| a.name.cmp(&b.name));
Ok(buttons)

View File

@@ -1,19 +1,20 @@
use std::collections::BTreeMap;
use std::env;
use log::debug;
use memflow::prelude::v1::*;
use pelite::pattern;
use pelite::pe64::{Pe, PeView};
use serde::{Deserialize, Serialize};
use skidscan_macros::signature;
use crate::error::Result;
use crate::source_engine::InterfaceReg;
use crate::source2::InterfaceReg;
pub type InterfaceMap = BTreeMap<String, Vec<Interface>>;
/// Represents an exposed interface.
#[derive(Debug, Deserialize, Serialize)]
pub struct Interface {
pub name: String,
@@ -21,23 +22,24 @@ pub struct Interface {
}
pub fn interfaces(process: &mut IntoProcessInstanceArcBox<'_>) -> Result<InterfaceMap> {
let sig = match env::consts::OS {
"linux" => signature!("48 8B 1D ? ? ? ? 48 85 DB 74 ? 49 89 FC"),
"windows" => signature!("4C 8B 0D ? ? ? ? 4C 8B D2 4C 8B D9"),
os => panic!("unsupported os: {}", os),
};
process
.module_list()?
.iter()
.filter_map(|module| {
let buf = process.read_raw(module.base, module.size as _).ok()?;
let list_addr = sig
.scan(&buf)
.and_then(|ptr| process.read_addr64_rip(module.base + ptr).ok())?;
let view = PeView::from_bytes(&buf).ok()?;
read_interfaces(process, module, list_addr)
let mut save = [0; 2];
if !view
.scanner()
.finds_code(pattern!("4c8b0d${'} 4c8bd2 4c8bd9"), &mut save)
{
return None;
}
read_interfaces(process, module, module.base + save[1])
.ok()
.filter(|ifaces| !ifaces.is_empty())
.map(|ifaces| Ok((module.name.to_string(), ifaces)))
@@ -73,6 +75,7 @@ fn read_interfaces(
reg_ptr = reg.next;
}
// Sort interfaces by name.
ifaces.sort_unstable_by(|a, b| a.name.cmp(&b.name));
Ok(ifaces)

View File

@@ -1,95 +1,141 @@
use std::collections::BTreeMap;
use std::mem;
use std::str::FromStr;
use log::{debug, error};
use log::debug;
use memflow::prelude::v1::*;
use serde::{Deserialize, Serialize};
use pelite::pattern;
use pelite::pattern::{save_len, Atom};
use pelite::pe64::{Pe, PeView};
use crate::config::{Operation, Signature, CONFIG};
use crate::error::{Error, Result};
use phf::{phf_map, Map};
pub type OffsetMap = BTreeMap<String, Vec<Offset>>;
use crate::error::Result;
#[derive(Debug, Deserialize, Serialize)]
pub struct Offset {
pub name: String,
pub value: u32,
pub type OffsetMap = BTreeMap<String, BTreeMap<String, u32>>;
macro_rules! pattern_map {
($($module:ident => {
$($name:expr => $pattern:expr $(=> $callback:expr)?),+ $(,)?
}),+ $(,)?) => {
$(
mod $module {
use super::*;
pub(super) const PATTERNS: Map<
&'static str,
(
&'static [Atom],
Option<fn(&PeView, &mut BTreeMap<String, u32>, u32)>,
),
> = phf_map! {
$($name => ($pattern, $($callback)?)),+
};
pub fn offsets(view: PeView<'_>) -> BTreeMap<String, u32> {
let mut map = BTreeMap::new();
for (&name, (pat, callback)) in &PATTERNS {
let mut save = vec![0; save_len(pat)];
if !view.scanner().finds_code(pat, &mut save) {
continue;
}
let rva = save[1];
map.insert(name.to_string(), rva);
if let Some(callback) = callback {
callback(&view, &mut map, rva);
}
}
for (name, value) in &map {
debug!(
"found offset: {} at {:#X} ({}.dll + {:#X})",
name,
*value as u64 + view.optional_header().ImageBase,
stringify!($module),
value
);
}
map
}
}
)+
};
}
pattern_map! {
client => {
"dwCSGOInput" => pattern!("4c8b0d${*{'}} 488d045b") => Some(|view, map, rva| {
let mut save = [0; 2];
if view.scanner().finds_code(pattern!("498d81u4 4803c7"), &mut save) {
map.insert("dwViewAngles".to_string(), rva + save[1]);
}
}),
"dwEntityList" => pattern!("488935${'} 4885f6") => None,
"dwGameEntitySystem" => pattern!("488b1d${'} 48891d") => None,
"dwGameEntitySystem_getHighestEntityIndex" => pattern!("8b81u2?? 8902 488bc2 c3 cccccccc 48895c24? 48896c24") => None,
"dwGameRules" => pattern!("48890d${'} 8b0d${} ff15") => None,
"dwGlobalVars" => pattern!("48890d${'} 488941") => None,
"dwGlowManager" => pattern!("488b05${'} c3 cccccccccccccccc 8b41") => None,
"dwLocalPlayerController" => pattern!("488b05${'} 4885c0 74? 8b88") => None,
"dwPlantedC4" => pattern!("488b15${'} ffc0 488d4c24") => None,
"dwPrediction" => pattern!("488d05${'} c3 cccccccccccccccc 4883ec? 8b0d") => Some(|_view, map, rva| {
map.insert("dwLocalPlayerPawn".to_string(), rva + 0x138);
}),
"dwSensitivity" => pattern!("488b05${'} 488b40? f3410f59f4") => None,
"dwSensitivity_sensitivity" => pattern!("ff50u1 4c8bc6 488d55? 488bcf e8${} 84c0 0f85${} 4c8d45? 8bd3 488bcf e8${} e9${} f30f1006") => None,
"dwViewMatrix" => pattern!("488d0d${'} 48c1e006") => None,
"dwViewRender" => pattern!("488905${'} 488bc8 4885c0") => None,
},
engine2 => {
"dwBuildNumber" => pattern!("8905${'} 488d0d${} ff15${} e9") => None,
"dwNetworkGameClient" => pattern!("48893d${'} 488d15") => None,
"dwNetworkGameClient_deltaTick" => pattern!("8983u4 40b7") => None,
"dwNetworkGameClient_getLocalPlayer" => pattern!("4883c0u1 488d0440 458b04c7") => Some(|_view, map, rva| {
// .text 48 83 C0 0A add rax, 0Ah
// .text 48 8D 04 40 lea rax, [rax+rax*2]
// .text 45 8B 04 C7 mov r8d, [r15+rax*8]
map.insert("dwNetworkGameClient_getLocalPlayer".to_string(), (rva + (rva * 2)) * 8);
}),
"dwNetworkGameClient_getMaxClients" => pattern!("8b81u2?? c3cccccccccccccccccc 8b81${} ffc0") => None,
"dwNetworkGameClient_signOnState" => pattern!("448b81u2?? 488d0d") => None,
"dwWindowHeight" => pattern!("8b05${'} 8903") => None,
"dwWindowWidth" => pattern!("8b05${'} 8907") => None,
},
input_system => {
"dwInputSystem" => pattern!("488905${'} 488d05") => None,
},
matchmaking => {
"dwGameTypes" => pattern!("488d0d${'} 33d2") => Some(|_view, map, rva| {
map.insert("dwGameTypes_mapName".to_string(), rva + 0x120);
}),
},
}
pub fn offsets(process: &mut IntoProcessInstanceArcBox<'_>) -> Result<OffsetMap> {
let mut map = BTreeMap::new();
for (module_name, sigs) in CONFIG.signatures.iter().flatten() {
let modules: [(&str, fn(PeView) -> BTreeMap<String, u32>); 4] = [
("client.dll", client::offsets),
("engine2.dll", engine2::offsets),
("inputsystem.dll", input_system::offsets),
("matchmaking.dll", matchmaking::offsets),
];
for (module_name, callback) in &modules {
let module = process.module_by_name(module_name)?;
let buf = process.read_raw(module.base, module.size as _)?;
let mut offsets: Vec<_> = sigs
.iter()
.filter_map(|sig| match read_offset(process, &module, sig) {
Ok(offset) => Some(offset),
Err(err) => {
error!("{}", err);
let view = PeView::from_bytes(&buf)?;
None
}
})
.collect();
if !offsets.is_empty() {
offsets.sort_unstable_by(|a, b| a.name.cmp(&b.name));
map.insert(module_name.to_string(), offsets);
}
map.insert(module_name.to_string(), callback(view));
}
Ok(map)
}
fn read_offset(
process: &mut IntoProcessInstanceArcBox<'_>,
module: &ModuleInfo,
signature: &Signature,
) -> Result<Offset> {
let buf = process.read_raw(module.base, module.size as _)?;
let addr = skidscan::Signature::from_str(&signature.pattern)?
.scan(&buf)
.ok_or_else(|| Error::SignatureNotFound(signature.name.clone()))?;
let mut result = module.base + addr;
for op in &signature.operations {
result = match op {
Operation::Add { value } => result + *value,
Operation::Rip { offset, len } => {
let offset: i32 = process.read(result + offset.unwrap_or(3))?;
(result + offset) + len.unwrap_or(7)
}
Operation::Read => process.read_addr64(result)?,
Operation::Slice { start, end } => {
let buf = process.read_raw(result + *start, end - start)?;
let mut bytes = [0; mem::size_of::<usize>()];
bytes[..buf.len()].copy_from_slice(&buf);
usize::from_le_bytes(bytes).into()
}
Operation::Sub { value } => result - *value,
};
}
let value = (result - module.base)
.try_into()
.map_or_else(|_| result.to_umem() as u32, |v| v);
debug!("found offset: {} at {:#X}", signature.name, value);
Ok(Offset {
name: signature.name.clone(),
value,
})
}

View File

@@ -1,18 +1,19 @@
use std::collections::BTreeMap;
use std::ffi::CStr;
use std::mem;
use std::ops::Add;
use std::{env, mem};
use log::debug;
use memflow::prelude::v1::*;
use pelite::pattern;
use pelite::pe64::{Pe, PeView};
use serde::{Deserialize, Serialize};
use skidscan_macros::signature;
use crate::error::{Error, Result};
use crate::source_engine::*;
use crate::source2::*;
pub type SchemaMap = BTreeMap<String, (Vec<Class>, Vec<Enum>)>;
@@ -42,7 +43,6 @@ pub struct ClassField {
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Enum {
pub name: String,
pub ty: String,
pub alignment: u8,
pub size: u16,
pub members: Vec<EnumMember>,
@@ -54,7 +54,7 @@ pub struct EnumMember {
pub value: i64,
}
#[derive(Debug, Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TypeScope {
pub name: String,
pub classes: Vec<Class>,
@@ -79,15 +79,10 @@ fn read_class_binding(
) -> Result<Class> {
let binding = binding_ptr.read(process)?;
let module_name = binding.module_name.read_string(process).map(|s| {
let file_ext = match env::consts::OS {
"linux" => ".so",
"windows" => ".dll",
os => panic!("unsupported os: {}", os),
};
format!("{}.{}", s, file_ext)
})?;
let module_name = binding
.module_name
.read_string(process)
.map(|s| format!("{}.dll", s))?;
let name = binding.name.read_string(process)?.to_string();
@@ -135,15 +130,15 @@ fn read_class_binding_fields(
let field = field_ptr.read(process)?;
if field.schema_type.is_null() {
if field.type_.is_null() {
return Err(Error::Other("field schema type is null"));
}
let name = field.name.read_string(process)?.to_string();
let schema_type = field.schema_type.read(process)?;
let type_ = field.type_.read(process)?;
// TODO: Parse this properly.
let ty = schema_type.name.read_string(process)?.replace(" ", "");
let ty = type_.name.read_string(process)?.replace(" ", "");
Ok(ClassField {
name,
@@ -178,16 +173,12 @@ fn read_class_binding_metadata(
let metadata = match name.as_str() {
"MNetworkChangeCallback" => unsafe {
let name = network_value
.union_data
.name_ptr
.read_string(process)?
.to_string();
let name = network_value.u.name_ptr.read_string(process)?.to_string();
ClassMetadata::NetworkChangeCallback { name }
},
"MNetworkVarNames" => unsafe {
let var_value = network_value.union_data.var_value;
let var_value = network_value.u.var_value;
let name = var_value.name.read_string(process)?.to_string();
let ty = var_value.ty.read_string(process)?.replace(" ", "");
@@ -208,21 +199,18 @@ fn read_enum_binding(
) -> Result<Enum> {
let binding = binding_ptr.read(process)?;
let name = binding.name.read_string(process)?.to_string();
let members = read_enum_binding_members(process, &binding)?;
debug!(
"found enum: {} at {:#X} (type name: {}) (alignment: {}) (members count: {})",
"found enum: {} at {:#X} (alignment: {}) (members count: {})",
name,
binding_ptr.to_umem(),
binding.type_name(),
binding.alignment,
binding.size,
);
Ok(Enum {
name,
ty: binding.type_name().to_string(),
alignment: binding.alignment,
size: binding.size,
members,
@@ -235,17 +223,17 @@ fn read_enum_binding_members(
) -> Result<Vec<EnumMember>> {
(0..binding.size)
.map(|i| {
let enumerator_info_ptr: Pointer64<SchemaEnumeratorInfoData> = binding
let enum_info_ptr: Pointer64<SchemaEnumeratorInfoData> = binding
.enum_info
.address()
.add(i * mem::size_of::<SchemaEnumeratorInfoData>() as u16)
.into();
let enumerator_info = enumerator_info_ptr.read(process)?;
let name = enumerator_info.name.read_string(process)?.to_string();
let enum_info = enum_info_ptr.read(process)?;
let name = enum_info.name.read_string(process)?.to_string();
let value = {
let value = unsafe { enumerator_info.union_data.ulong } as i64;
let value = unsafe { enum_info.u.ulong } as i64;
if value == i64::MAX {
-1
@@ -260,27 +248,21 @@ fn read_enum_binding_members(
}
fn read_schema_system(process: &mut IntoProcessInstanceArcBox<'_>) -> Result<SchemaSystem> {
let (module_name, sig) = match env::consts::OS {
"linux" => (
"libschemasystem.so",
signature!("48 8D 35 ? ? ? ? 48 8D 3D ? ? ? ? E8 ? ? ? ? 48 8D 15 ? ? ? ? 48 8D 35 ? ? ? ? 48 8D 3D"),
),
"windows" => (
"schemasystem.dll",
signature!("48 89 05 ? ? ? ? 4C 8D 45"),
),
os => panic!("unsupported os: {}", os),
};
let module = process.module_by_name(&module_name)?;
let module = process.module_by_name("schemasystem.dll")?;
let buf = process.read_raw(module.base, module.size as _)?;
let addr = sig
.scan(&buf)
.and_then(|ptr| process.read_addr64_rip(module.base + ptr).ok())
.ok_or_else(|| Error::Other("unable to read schema system address"))?;
let view = PeView::from_bytes(&buf)?;
let schema_system: SchemaSystem = process.read(addr)?;
let mut save = [0; 2];
if !view
.scanner()
.finds_code(pattern!("488905${'} 4c8d45"), &mut save)
{
return Err(Error::Other("unable to find schema system signature"));
}
let schema_system: SchemaSystem = process.read(module.base + save[1]).data_part()?;
if schema_system.num_registrations == 0 {
return Err(Error::Other("no schema system registrations found"));
@@ -297,8 +279,7 @@ fn read_type_scopes(
(0..type_scopes.size)
.map(|i| {
let type_scope_ptr = type_scopes.get(process, i as _)?;
let type_scope = type_scope_ptr.read(process)?;
let type_scope = type_scopes.get(process, i as _)?.read(process)?;
let name = unsafe { CStr::from_ptr(type_scope.name.as_ptr()) }
.to_string_lossy()
@@ -319,9 +300,8 @@ fn read_type_scopes(
.collect();
debug!(
"found type scope: {} at {:#X} (classes count: {}) (enums count: {})",
"found type scope: {} (classes: {}) (enums: {})",
name,
type_scope_ptr.to_umem(),
classes.len(),
enums.len()
);

View File

@@ -1,76 +0,0 @@
use std::collections::HashMap;
use std::sync::LazyLock;
use std::{env, fs};
use serde::{Deserialize, Serialize};
pub static CONFIG: LazyLock<Config> = LazyLock::new(|| {
let file_name = get_config_file_name();
let content = fs::read_to_string(&file_name).unwrap_or_else(|_| {
panic!(
"unable to read config file: {}\nmake sure the file is placed in the same directory as the cs2-dumper executable",
file_name
)
});
serde_json::from_str(&content).expect("unable to parse config file")
});
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum Operation {
/// Adds the specified value to the current address.
Add { value: usize },
/// Resolves the absolute address of a RIP-relative address.
Rip {
offset: Option<usize>,
len: Option<usize>,
},
/// Reads the value at the current address, treating it as a pointer.
Read,
/// Extracts a range of bytes from the current address and interprets them as a value.
Slice { start: usize, end: usize },
/// Subtracts the specified value from the current address.
Sub { value: usize },
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
/// Name of the process.
pub executable: String,
/// List of signatures to search for.
pub signatures: Vec<HashMap<String, Vec<Signature>>>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Signature {
/// Name of the signature.
pub name: String,
/// An IDA-style pattern containing the bytes to search for.
pub pattern: String,
/// List of operations to perform on the matched address.
pub operations: Vec<Operation>,
}
/// Returns the correct config file name, depending on the target OS.
fn get_config_file_name() -> &'static str {
// Assume that if the user has provided a connector name, they are targetting the Windows
// version of the game.
if env::args().any(|arg| arg.starts_with("--connector") || arg.starts_with("-c")) {
"config_win.json"
} else {
match env::consts::OS {
"linux" => "config_linux.json",
"windows" => "config_win.json",
os => panic!("unsupported os: {}", os),
}
}
}

View File

@@ -5,23 +5,20 @@ pub enum Error {
#[error(transparent)]
Fmt(#[from] std::fmt::Error),
#[error("index {idx} is out of bounds for array with length {len}")]
IndexOutOfBounds { idx: usize, len: usize },
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Memflow(#[from] memflow::error::Error),
#[error(transparent)]
Pelite(#[from] pelite::Error),
#[error(transparent)]
Serde(#[from] serde_json::Error),
#[error("unable to parse signature")]
SignatureInvalid,
#[error("unable to find signature for: {0}")]
SignatureNotFound(String),
#[error("index {idx} is out of bounds for array with length {len}")]
OutOfBounds { idx: usize, len: usize },
#[error("{0}")]
Other(&'static str),
@@ -34,11 +31,4 @@ impl<T> From<memflow::error::PartialError<T>> for Error {
}
}
impl From<skidscan::SignatureParseError> for Error {
#[inline]
fn from(_err: skidscan::SignatureParseError) -> Self {
Error::SignatureInvalid
}
}
pub type Result<T> = std::result::Result<T, Error>;

View File

@@ -1,8 +1,6 @@
#![feature(lazy_cell)]
use std::env;
use std::path::PathBuf;
use std::time::Instant;
use std::{env, fs};
use clap::*;
@@ -12,15 +10,15 @@ use memflow::prelude::v1::*;
use simplelog::{ColorChoice, TermLogger};
use config::CONFIG;
use error::Result;
use output::Results;
mod analysis;
mod config;
mod error;
mod output;
mod source_engine;
mod source2;
const PROCESS_NAME: &str = "cs2.exe";
fn main() -> Result<()> {
let start_time = Instant::now();
@@ -28,9 +26,6 @@ fn main() -> Result<()> {
let matches = parse_args();
let (conn_name, conn_args, indent_size, out_dir) = extract_args(&matches)?;
// Create the output directory if it doesn't exist.
fs::create_dir_all(&out_dir)?;
let os = if let Some(conn_name) = conn_name {
let inventory = Inventory::scan();
@@ -45,7 +40,7 @@ fn main() -> Result<()> {
memflow_native::create_os(&Default::default(), Default::default())?
};
let mut process = os.into_process_by_name(&CONFIG.executable)?;
let mut process = os.into_process_by_name(PROCESS_NAME)?;
let buttons = analysis::buttons(&mut process)?;
let interfaces = analysis::interfaces(&mut process)?;

View File

@@ -1,5 +1,4 @@
use std::collections::BTreeMap;
use std::env;
use std::fmt::Write;
use super::{Button, CodeGen, Results};
@@ -10,7 +9,7 @@ impl CodeGen for Vec<Button> {
fn to_cs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
fmt.block("namespace CS2Dumper", false, |fmt| {
writeln!(fmt, "// Module: {}", get_module_name())?;
writeln!(fmt, "// Module: client.dll")?;
fmt.block("public static class Buttons", false, |fmt| {
for button in self {
@@ -35,7 +34,7 @@ impl CodeGen for Vec<Button> {
writeln!(fmt, "#include <cstddef>\n")?;
fmt.block("namespace cs2_dumper", false, |fmt| {
writeln!(fmt, "// Module: {}", get_module_name())?;
writeln!(fmt, "// Module: client.dll")?;
fmt.block("namespace buttons", false, |fmt| {
for button in self {
@@ -58,10 +57,10 @@ impl CodeGen for Vec<Button> {
let content = {
let buttons: BTreeMap<_, _> = self
.iter()
.map(|button| (&button.name, button.value))
.map(|button| (button.name.as_str(), button.value))
.collect();
BTreeMap::from_iter([(get_module_name(), buttons)])
BTreeMap::from_iter([("client.dll", buttons)])
};
serde_json::to_string_pretty(&content).map_err(Into::into)
@@ -69,10 +68,13 @@ impl CodeGen for Vec<Button> {
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(fmt, "#![allow(non_upper_case_globals, unused)]\n")?;
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, unused)]\n"
)?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
writeln!(fmt, "// Module: {}", get_module_name())?;
writeln!(fmt, "// Module: client.dll")?;
fmt.block("pub mod buttons", false, |fmt| {
for button in self {
@@ -91,12 +93,3 @@ impl CodeGen for Vec<Button> {
})
}
}
#[inline]
fn get_module_name() -> &'static str {
match env::consts::OS {
"linux" => "libclient.so",
"windows" => "client.dll",
_ => panic!("unsupported os"),
}
}

View File

@@ -50,8 +50,9 @@ impl<'a> Formatter<'a> {
#[inline]
fn push_indentation(&mut self) {
if self.indent_level > 0 {
self.out
.push_str(&" ".repeat(self.indent_level * self.indent_size));
let indentation = " ".repeat(self.indent_level * self.indent_size);
self.out.push_str(&indentation);
}
}
}

View File

@@ -3,7 +3,7 @@ use std::fmt::Write;
use heck::{AsPascalCase, AsSnakeCase};
use super::{format_module_name, CodeGen, InterfaceMap, Results};
use super::{CodeGen, InterfaceMap, Results};
use crate::error::Result;
@@ -17,7 +17,7 @@ impl CodeGen for InterfaceMap {
fmt.block(
&format!(
"public static class {}",
AsPascalCase(format_module_name(module_name))
AsPascalCase(Self::sanitize_name(module_name))
),
false,
|fmt| {
@@ -52,7 +52,10 @@ impl CodeGen for InterfaceMap {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!("namespace {}", AsSnakeCase(format_module_name(module_name))),
&format!(
"namespace {}",
AsSnakeCase(Self::sanitize_name(module_name))
),
false,
|fmt| {
for iface in ifaces {
@@ -94,7 +97,10 @@ impl CodeGen for InterfaceMap {
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(fmt, "#![allow(non_upper_case_globals, unused)]\n")?;
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, unused)]\n"
)?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod interfaces", false, |fmt| {
@@ -102,7 +108,7 @@ impl CodeGen for InterfaceMap {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!("pub mod {}", AsSnakeCase(format_module_name(module_name))),
&format!("pub mod {}", AsSnakeCase(Self::sanitize_name(module_name))),
false,
|fmt| {
for iface in ifaces {

View File

@@ -1,6 +1,6 @@
use std::fmt::Write;
use std::fs;
use std::path::Path;
use std::{env, fs};
use chrono::{DateTime, Utc};
@@ -54,6 +54,11 @@ trait CodeGen {
/// Converts an [`Item`] to formatted Rust code.
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String>;
#[inline]
fn sanitize_name(name: &str) -> String {
name.replace(|c: char| !c.is_alphanumeric(), "_")
}
fn write_content<F>(&self, results: &Results, indent_size: usize, callback: F) -> Result<String>
where
F: FnOnce(&mut Formatter<'_>) -> Result<()>,
@@ -150,6 +155,9 @@ impl Results {
// TODO: Make this user-configurable.
const FILE_EXTS: &[&str] = &["cs", "hpp", "json", "rs"];
// Create the output directory if it doesn't exist.
fs::create_dir_all(&out_dir)?;
let items = [
("buttons", Item::Buttons(&self.buttons)),
("interfaces", Item::Interfaces(&self.interfaces)),
@@ -158,6 +166,7 @@ impl Results {
self.dump_items(&items, out_dir.as_ref(), indent_size, FILE_EXTS)?;
// Write a new file for each module.
for (module_name, (classes, enums)) in &self.schemas {
let schemas = [(module_name.clone(), (classes.clone(), enums.clone()))].into();
@@ -180,7 +189,7 @@ impl Results {
) -> Result<()> {
let file_path = out_dir.as_ref().join(format!("{}.{}", file_name, file_ext));
fs::write(file_path, content)?;
fs::write(&file_path, content)?;
Ok(())
}
@@ -190,15 +199,12 @@ impl Results {
process: &mut IntoProcessInstanceArcBox<'_>,
out_dir: P,
) -> Result<()> {
self.dump_file(
out_dir.as_ref(),
"info",
"json",
&serde_json::to_string_pretty(&json!({
"timestamp": self.timestamp.to_rfc3339(),
"build_number": self.read_build_number(process).unwrap_or(0),
}))?,
)
let content = &serde_json::to_string_pretty(&json!({
"timestamp": self.timestamp.to_rfc3339(),
"build_number": self.read_build_number(process).unwrap_or(0),
}))?;
self.dump_file(out_dir.as_ref(), "info", "json", &content)
}
fn dump_item<P: AsRef<Path>>(
@@ -236,16 +242,12 @@ impl Results {
self.offsets
.iter()
.find_map(|(module_name, offsets)| {
offsets
.iter()
.find(|o| o.name == "dwBuildNumber")
.and_then(|offset| {
let module_base = process.module_by_name(module_name).ok()?;
let offset = offsets.iter().find(|(name, _)| *name == "dwBuildNumber")?;
let module = process.module_by_name(module_name).ok()?;
process.read(module_base.base + offset.value).ok()
})
process.read(module.base + offset.1).ok()
})
.ok_or_else(|| Error::Other("unable to read build number".into()))
.ok_or(Error::Other("unable to read build number"))
}
fn write_banner(&self, fmt: &mut Formatter<'_>) -> Result<()> {
@@ -255,18 +257,3 @@ impl Results {
Ok(())
}
}
pub fn format_module_name(module_name: &String) -> String {
let file_ext = match env::consts::OS {
"linux" => ".so",
"windows" => ".dll",
os => panic!("unsupported os: {}", os),
};
module_name.strip_suffix(file_ext).unwrap().to_string()
}
#[inline]
pub fn sanitize_name(name: &str) -> String {
name.replace(|c: char| !c.is_alphanumeric(), "_")
}

View File

@@ -1,9 +1,8 @@
use std::collections::BTreeMap;
use std::fmt::Write;
use heck::{AsPascalCase, AsSnakeCase};
use super::{format_module_name, CodeGen, OffsetMap, Results};
use super::{CodeGen, OffsetMap, Results};
use crate::error::Result;
@@ -17,16 +16,12 @@ impl CodeGen for OffsetMap {
fmt.block(
&format!(
"public static class {}",
AsPascalCase(format_module_name(module_name))
AsPascalCase(Self::sanitize_name(module_name))
),
false,
|fmt| {
for offset in offsets {
writeln!(
fmt,
"public const nint {} = {:#X};",
offset.name, offset.value
)?;
for (name, value) in offsets {
writeln!(fmt, "public const nint {} = {:#X};", name, value)?;
}
Ok(())
@@ -52,14 +47,17 @@ impl CodeGen for OffsetMap {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!("namespace {}", AsSnakeCase(format_module_name(module_name))),
&format!(
"namespace {}",
AsSnakeCase(Self::sanitize_name(module_name))
),
false,
|fmt| {
for offset in offsets {
for (name, value) in offsets {
writeln!(
fmt,
"constexpr std::ptrdiff_t {} = {:#X};",
offset.name, offset.value
name, value
)?;
}
@@ -77,24 +75,15 @@ impl CodeGen for OffsetMap {
}
fn to_json(&self, _results: &Results, _indent_size: usize) -> Result<String> {
let content: BTreeMap<_, _> = self
.iter()
.map(|(module_name, offsets)| {
let offsets: BTreeMap<_, _> = offsets
.iter()
.map(|offset| (&offset.name, offset.value))
.collect();
(module_name, offsets)
})
.collect();
serde_json::to_string_pretty(&content).map_err(Into::into)
serde_json::to_string_pretty(self).map_err(Into::into)
}
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(fmt, "#![allow(non_upper_case_globals, unused)]\n")?;
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, unused)]\n"
)?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod offsets", false, |fmt| {
@@ -102,15 +91,11 @@ impl CodeGen for OffsetMap {
writeln!(fmt, "// Module: {}", module_name)?;
fmt.block(
&format!("pub mod {}", AsSnakeCase(format_module_name(module_name))),
&format!("pub mod {}", AsSnakeCase(Self::sanitize_name(module_name))),
false,
|fmt| {
for offset in offsets {
writeln!(
fmt,
"pub const {}: usize = {:#X};",
offset.name, offset.value
)?;
for (name, value) in offsets {
writeln!(fmt, "pub const {}: usize = {:#X};", name, value)?;
}
Ok(())

View File

@@ -5,7 +5,7 @@ use heck::{AsPascalCase, AsSnakeCase};
use serde_json::json;
use super::{format_module_name, sanitize_name, CodeGen, Formatter, Results, SchemaMap};
use super::{CodeGen, Formatter, Results, SchemaMap};
use crate::analysis::ClassMetadata;
use crate::error::Result;
@@ -15,6 +15,11 @@ impl CodeGen for SchemaMap {
self.write_content(results, indent_size, |fmt| {
fmt.block("namespace CS2Dumper.Schemas", false, |fmt| {
for (module_name, (classes, enums)) in self {
// Skip empty modules.
if classes.is_empty() && enums.is_empty() {
continue;
}
writeln!(fmt, "// Module: {}", module_name)?;
writeln!(fmt, "// Classes count: {}", classes.len())?;
writeln!(fmt, "// Enums count: {}", enums.len())?;
@@ -22,16 +27,16 @@ impl CodeGen for SchemaMap {
fmt.block(
&format!(
"public static class {}",
AsPascalCase(format_module_name(module_name))
AsPascalCase(Self::sanitize_name(module_name))
),
false,
|fmt| {
for enum_ in enums {
let ty = match enum_.ty.as_str() {
"uint8" => "byte",
"uint16" => "ushort",
"uint32" => "uint",
"uint64" => "ulong",
let ty = match enum_.alignment {
1 => "byte",
2 => "ushort",
4 => "uint",
8 => "ulong",
_ => continue,
};
@@ -39,7 +44,11 @@ impl CodeGen for SchemaMap {
writeln!(fmt, "// Members count: {}", enum_.size)?;
fmt.block(
&format!("public enum {} : {}", sanitize_name(&enum_.name), ty),
&format!(
"public enum {} : {}",
Self::sanitize_name(&enum_.name),
ty
),
false,
|fmt| {
let members = enum_
@@ -60,7 +69,7 @@ impl CodeGen for SchemaMap {
let parent_name = class
.parent
.as_ref()
.map(|parent| format!("{}", sanitize_name(&parent.name)))
.map(|parent| Self::sanitize_name(&parent.name))
.unwrap_or_else(|| "None".to_string());
writeln!(fmt, "// Parent: {}", parent_name)?;
@@ -71,7 +80,10 @@ impl CodeGen for SchemaMap {
}
fmt.block(
&format!("public static class {}", sanitize_name(&class.name)),
&format!(
"public static class {}",
Self::sanitize_name(&class.name)
),
false,
|fmt| {
for field in &class.fields {
@@ -107,20 +119,28 @@ impl CodeGen for SchemaMap {
fmt.block("namespace cs2_dumper", false, |fmt| {
fmt.block("namespace schemas", false, |fmt| {
for (module_name, (classes, enums)) in self {
// Skip empty modules.
if classes.is_empty() && enums.is_empty() {
continue;
}
writeln!(fmt, "// Module: {}", module_name)?;
writeln!(fmt, "// Classes count: {}", classes.len())?;
writeln!(fmt, "// Enums count: {}", enums.len())?;
fmt.block(
&format!("namespace {}", AsSnakeCase(format_module_name(module_name))),
&format!(
"namespace {}",
AsSnakeCase(Self::sanitize_name(module_name))
),
false,
|fmt| {
for enum_ in enums {
let ty = match enum_.ty.as_str() {
"uint8" => "uint8_t",
"uint16" => "uint16_t",
"uint32" => "uint32_t",
"uint64" => "uint64_t",
let ty = match enum_.alignment {
1 => "uint8_t",
2 => "uint16_t",
4 => "uint32_t",
8 => "uint64_t",
_ => continue,
};
@@ -130,7 +150,7 @@ impl CodeGen for SchemaMap {
fmt.block(
&format!(
"enum class {} : {}",
sanitize_name(&enum_.name),
Self::sanitize_name(&enum_.name),
ty
),
true,
@@ -153,7 +173,7 @@ impl CodeGen for SchemaMap {
let parent_name = class
.parent
.as_ref()
.map(|parent| format!("{}", sanitize_name(&parent.name)))
.map(|parent| Self::sanitize_name(&parent.name))
.unwrap_or_else(|| "None".to_string());
writeln!(fmt, "// Parent: {}", parent_name)?;
@@ -164,7 +184,7 @@ impl CodeGen for SchemaMap {
}
fmt.block(
&format!("namespace {}", sanitize_name(&class.name)),
&format!("namespace {}", Self::sanitize_name(&class.name)),
false,
|fmt| {
for field in &class.fields {
@@ -229,7 +249,7 @@ impl CodeGen for SchemaMap {
.collect();
(
sanitize_name(&class.name),
Self::sanitize_name(&class.name),
json!({
"parent": class.parent.as_ref().map(|parent| &parent.name),
"fields": fields,
@@ -248,11 +268,19 @@ impl CodeGen for SchemaMap {
.map(|member| (&member.name, member.value))
.collect();
let ty = match enum_.alignment {
1 => "uint8",
2 => "uint16",
4 => "uint32",
8 => "uint64",
_ => "unknown",
};
(
sanitize_name(&enum_.name),
Self::sanitize_name(&enum_.name),
json!({
"alignment": enum_.alignment,
"type": enum_.ty,
"type": ty,
"members": members,
}),
)
@@ -274,25 +302,33 @@ impl CodeGen for SchemaMap {
fn to_rs(&self, results: &Results, indent_size: usize) -> Result<String> {
self.write_content(results, indent_size, |fmt| {
writeln!(fmt, "#![allow(non_upper_case_globals, unused)]\n")?;
writeln!(
fmt,
"#![allow(non_upper_case_globals, non_camel_case_types, unused)]\n"
)?;
fmt.block("pub mod cs2_dumper", false, |fmt| {
fmt.block("pub mod schemas", false, |fmt| {
for (module_name, (classes, enums)) in self {
// Skip empty modules.
if classes.is_empty() && enums.is_empty() {
continue;
}
writeln!(fmt, "// Module: {}", module_name)?;
writeln!(fmt, "// Classes count: {}", classes.len())?;
writeln!(fmt, "// Enums count: {}", enums.len())?;
fmt.block(
&format!("pub mod {}", AsSnakeCase(format_module_name(module_name))),
&format!("pub mod {}", AsSnakeCase(Self::sanitize_name(module_name))),
false,
|fmt| {
for enum_ in enums {
let ty = match enum_.ty.as_str() {
"uint8" => "u8",
"uint16" => "u16",
"uint32" => "u32",
"uint64" => "u64",
let ty = match enum_.alignment {
1 => "u8",
2 => "u16",
4 => "u32",
8 => "u64",
_ => continue,
};
@@ -303,7 +339,7 @@ impl CodeGen for SchemaMap {
&format!(
"#[repr({})]\npub enum {}",
ty,
sanitize_name(&enum_.name),
Self::sanitize_name(&enum_.name),
),
false,
|fmt| {
@@ -327,7 +363,7 @@ impl CodeGen for SchemaMap {
let parent_name = class
.parent
.as_ref()
.map(|parent| format!("{}", sanitize_name(&parent.name)))
.map(|parent| Self::sanitize_name(&parent.name))
.unwrap_or_else(|| "None".to_string());
writeln!(fmt, "// Parent: {}", parent_name)?;
@@ -338,7 +374,7 @@ impl CodeGen for SchemaMap {
}
fmt.block(
&format!("pub mod {}", sanitize_name(&class.name)),
&format!("pub mod {}", Self::sanitize_name(&class.name)),
false,
|fmt| {
for field in &class.fields {

View File

@@ -0,0 +1,3 @@
pub use input::*;
pub mod input;

View File

@@ -5,7 +5,7 @@ use super::{SchemaMetadataEntryData, SchemaType};
#[repr(C)]
pub struct SchemaClassFieldData {
pub name: Pointer64<ReprCString>,
pub schema_type: Pointer64<SchemaType>,
pub type_: Pointer64<SchemaType>,
pub offset: u32,
pub metadata_count: u32,
pub metadata: Pointer64<SchemaMetadataEntryData>,

View File

@@ -26,7 +26,7 @@ pub struct SchemaClassInfoData {
pad_0040: [u8; 0x8],
pub static_metadata: Pointer64<SchemaMetadataEntryData>,
pub type_scope: Pointer64<SchemaSystemTypeScope>,
pub schema_type: Pointer64<SchemaType>,
pub type_: Pointer64<SchemaType>,
pad_0060: [u8; 0x10],
}

View File

@@ -19,17 +19,4 @@ pub struct SchemaEnumInfoData {
pad_0038: [u8; 0xC],
}
impl SchemaEnumInfoData {
#[inline]
pub fn type_name(&self) -> &str {
match self.alignment {
1 => "uint8",
2 => "uint16",
4 => "uint32",
8 => "uint64",
_ => "unknown",
}
}
}
unsafe impl Pod for SchemaEnumInfoData {}

View File

@@ -5,7 +5,7 @@ use super::SchemaMetadataEntryData;
#[repr(C)]
pub struct SchemaEnumeratorInfoData {
pub name: Pointer64<ReprCString>,
pub union_data: SchemaEnumeratorInfoDataUnion,
pub u: SchemaEnumeratorInfoDataUnion,
pub metadata_count: u32,
pub metadata: Pointer64<SchemaMetadataEntryData>,
}

View File

@@ -12,7 +12,7 @@ unsafe impl Pod for SchemaMetadataEntryData {}
#[repr(C)]
pub struct SchemaNetworkValue {
pub union_data: SchemaNetworkValueUnion,
pub u: SchemaNetworkValueUnion,
}
unsafe impl Pod for SchemaNetworkValue {}

View File

@@ -2,18 +2,8 @@ use memflow::prelude::v1::*;
use super::SchemaSystemTypeScope;
use crate::source_engine::UtlVector;
use crate::source2::UtlVector;
#[cfg(target_os = "linux")]
#[repr(C)]
pub struct SchemaSystem {
pad_0000: [u8; 0x1F8],
pub type_scopes: UtlVector<Pointer64<SchemaSystemTypeScope>>,
pad_01a0: [u8; 0x120],
pub num_registrations: u32,
}
#[cfg(target_os = "windows")]
#[repr(C)]
pub struct SchemaSystem {
pad_0000: [u8; 0x190],

View File

@@ -4,20 +4,8 @@ use memflow::prelude::v1::*;
use super::{SchemaClassBinding, SchemaEnumBinding};
use crate::source_engine::UtlTsHash;
use crate::source2::UtlTsHash;
#[cfg(target_os = "linux")]
#[repr(C)]
pub struct SchemaSystemTypeScope {
pad_0000: [u8; 0x8],
pub name: [c_char; 256],
pad_0108: [u8; 0x518],
pub class_bindings: UtlTsHash<Pointer64<SchemaClassBinding>>,
pad_05f0: [u8; 0x2810],
pub enum_bindings: UtlTsHash<Pointer64<SchemaEnumBinding>>,
}
#[cfg(target_os = "windows")]
#[repr(C)]
pub struct SchemaSystemTypeScope {
pad_0000: [u8; 0x8],

View File

@@ -1,6 +1,6 @@
use memflow::prelude::v1::*;
use super::{SchemaClassInfoData, SchemaEnumBinding, SchemaSystemTypeScope};
use super::{SchemaClassBinding, SchemaEnumBinding, SchemaSystemTypeScope};
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
@@ -88,7 +88,7 @@ unsafe impl Pod for SchemaType {}
#[repr(C)]
pub union SchemaTypeUnion {
pub schema_type: Pointer64<SchemaType>,
pub class_info: Pointer64<SchemaClassInfoData>,
pub class_binding: Pointer64<SchemaClassBinding>,
pub enum_binding: Pointer64<SchemaEnumBinding>,
pub array: SchemaArray,
pub atomic: SchemaAtomic,

View File

@@ -5,16 +5,16 @@ use memflow::prelude::v1::*;
use crate::error::{Error, Result};
#[repr(C)]
pub struct UtlVector<T: Sized + Pod> {
pub struct UtlVector<T: Copy + Sized + Pod> {
pub size: u32,
pub mem: Pointer64<T>,
}
impl<T: Sized + Pod> UtlVector<T> {
impl<T: Copy + Sized + Pod> UtlVector<T> {
#[inline]
pub fn get(&self, process: &mut IntoProcessInstanceArcBox<'_>, idx: usize) -> Result<T> {
if idx >= self.size as usize {
return Err(Error::IndexOutOfBounds {
return Err(Error::OutOfBounds {
idx,
len: self.size as usize,
});
@@ -26,4 +26,4 @@ impl<T: Sized + Pod> UtlVector<T> {
}
}
unsafe impl<T: Sized + Pod> Pod for UtlVector<T> {}
unsafe impl<T: Copy + Sized + Pod> Pod for UtlVector<T> {}

View File

@@ -1,3 +0,0 @@
pub use input::KeyboardKey;
pub mod input;