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,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 {