shader.rs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //! Survey shader containers: bitcode, console additions and native code.
  2. use std::borrow::Cow;
  3. use std::collections::BTreeMap;
  4. use std::path::PathBuf;
  5. use anyhow::Result;
  6. use victory_game::sgd5;
  7. use victory_shader::gfx10::{self, Instruction};
  8. use victory_shader::{Container, DxilProgram, FourCC, HwStage, ShaderError, native_programs};
  9. /// Files above this size are skipped (read whole into memory for now).
  10. pub(crate) const MAX_FILE: u64 = 2 << 30;
  11. /// A shader container in a file: as is, or packed in an SGD5 record.
  12. pub(crate) enum Source<'a> {
  13. Raw { offset: usize, data: &'a [u8] },
  14. Packed(sgd5::Record<'a>),
  15. }
  16. impl Source<'_> {
  17. /// The container bytes; `None` if a packed record is corrupt.
  18. pub(crate) fn bytes(&self) -> Option<Cow<'_, [u8]>> {
  19. match self {
  20. Source::Raw { data, .. } => Some(Cow::Borrowed(data)),
  21. Source::Packed(r) => r.unpack().map(Cow::Owned),
  22. }
  23. }
  24. pub(crate) fn label(&self) -> String {
  25. match self {
  26. Source::Raw { offset, .. } => format!("@{offset:#x}"),
  27. Source::Packed(r) => format!("@{:#x} {}", r.offset, r.name.unwrap_or("?")),
  28. }
  29. }
  30. }
  31. /// The packed records of SGD5 data, and every container stored as is (the
  32. /// executable keeps some records uncompressed), found by its magic.
  33. pub(crate) fn sources(data: &[u8]) -> Vec<Source<'_>> {
  34. let mut out: Vec<Source<'_>> = Vec::new();
  35. if sgd5::is_sgd5(data) {
  36. out.extend(sgd5::records(data).map(Source::Packed));
  37. }
  38. let raw = memchr::memmem::find_iter(data, b"DXBC")
  39. .filter(|&offset| Container::parse(&data[offset..]).is_ok())
  40. .map(|offset| Source::Raw {
  41. offset,
  42. data: &data[offset..],
  43. });
  44. out.extend(raw);
  45. out
  46. }
  47. #[derive(Default)]
  48. struct Totals {
  49. containers: usize,
  50. with_dxil_part: usize,
  51. with_bitcode: usize,
  52. standard_layout: usize,
  53. xdat: usize,
  54. xbop: usize,
  55. kinds: BTreeMap<String, usize>,
  56. with_native: usize,
  57. native_stages: BTreeMap<HwStage, usize>,
  58. native_errors: BTreeMap<String, usize>,
  59. decoded: usize,
  60. instructions: usize,
  61. unnamed: BTreeMap<String, usize>,
  62. decode_errors: BTreeMap<&'static str, usize>,
  63. files_with_shaders: usize,
  64. }
  65. pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
  66. let paths = crate::default_paths(paths)?;
  67. let mut t = Totals::default();
  68. for root in &paths {
  69. for entry in walkdir::WalkDir::new(root)
  70. .into_iter()
  71. .filter_map(Result::ok)
  72. {
  73. if !entry.file_type().is_file() {
  74. continue;
  75. }
  76. let path = entry.path();
  77. if entry.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE {
  78. eprintln!("skipping large file {}", path.display());
  79. continue;
  80. }
  81. let Ok(data) = std::fs::read(path) else {
  82. continue;
  83. };
  84. let mut found_here = 0;
  85. for source in sources(&data) {
  86. let Some(bytes) = source.bytes() else {
  87. eprintln!("corrupt record {}{}", path.display(), source.label());
  88. continue;
  89. };
  90. let Ok(container) = Container::parse(&bytes) else {
  91. continue;
  92. };
  93. found_here += 1;
  94. t.containers += 1;
  95. let dxil = container.part(FourCC::DXIL).or(container.part(FourCC::ACCC));
  96. t.with_dxil_part += usize::from(dxil.is_some());
  97. let program = dxil.and_then(|p| DxilProgram::parse(p.data).ok());
  98. let mut listing = Vec::new();
  99. // Independent of the bitcode: titles may strip it.
  100. let native = match dxil.map(|p| native_programs(p.data)) {
  101. Some(Ok(programs)) if !programs.is_empty() => {
  102. t.with_native += 1;
  103. let mut list = Vec::new();
  104. for n in &programs {
  105. *t.native_stages.entry(n.stage).or_default() += 1;
  106. list.push(format!("{:?} {} B", n.stage, n.code.len()));
  107. if disasm {
  108. listing.push(format!(" {:?} stage I/O: {:?}", n.stage, n.io));
  109. listing.extend(n.layout.iter().map(|p| format!(" {p:?}")));
  110. listing.extend(n.used.iter().map(|u| format!(" {u:?}")));
  111. }
  112. match gfx10::decode(&n.code) {
  113. Ok(insts) => {
  114. t.decoded += 1;
  115. t.instructions += insts.len();
  116. for i in insts.iter().filter(|i| i.name().is_none()) {
  117. let key = format!("{:?} {:#x}", i.encoding, i.opcode);
  118. *t.unnamed.entry(key).or_default() += 1;
  119. }
  120. if disasm {
  121. listing.extend(
  122. insts.iter().map(|i| format_instruction(i, n.wave64)),
  123. );
  124. }
  125. }
  126. Err(e) => {
  127. let reason = match e {
  128. ShaderError::Isa { reason, .. } => reason,
  129. _ => "other",
  130. };
  131. *t.decode_errors.entry(reason).or_default() += 1;
  132. list.push(format!("({e})"));
  133. }
  134. }
  135. }
  136. format!(", native {}", list.join(" "))
  137. }
  138. Some(Err(e)) => {
  139. *t.native_errors.entry(e.to_string()).or_default() += 1;
  140. format!(", native: {e}")
  141. }
  142. _ => String::new(),
  143. };
  144. let line = match &program {
  145. Some(p) => {
  146. t.with_bitcode += 1;
  147. let x = p.xbox_extras();
  148. t.standard_layout += usize::from(p.is_standard_layout());
  149. t.xdat += usize::from(x.xdat);
  150. t.xbop += usize::from(x.xbop);
  151. *t.kinds.entry(format!("{:?}", p.kind)).or_default() += 1;
  152. format!(
  153. "{:?} sm{}.{} bitcode {} B, xdat {}, xbop {}",
  154. p.kind,
  155. p.shader_model.0,
  156. p.shader_model.1,
  157. p.bitcode.len(),
  158. x.xdat,
  159. x.xbop
  160. )
  161. }
  162. None => "no parsable DXIL program".to_owned(),
  163. } + &native;
  164. if verbose {
  165. // As a run's log and a replay name it (`hash=`).
  166. let hash = blake3::hash(&bytes).to_hex();
  167. println!("{}{} #{}: {line}", path.display(), source.label(), &hash[..16]);
  168. for l in &listing {
  169. println!("{l}");
  170. }
  171. }
  172. }
  173. t.files_with_shaders += usize::from(found_here > 0);
  174. }
  175. }
  176. println!(
  177. "containers found {} (in {} files)",
  178. t.containers, t.files_with_shaders
  179. );
  180. println!(" with DXIL part {}", t.with_dxil_part);
  181. println!(" with LLVM bitcode {}", t.with_bitcode);
  182. println!(" PC-standard layout {}", t.standard_layout);
  183. println!(" XDAT prefix {}", t.xdat);
  184. println!(" xbop trailer {}", t.xbop);
  185. for (k, n) in &t.kinds {
  186. println!(" {k:<20} {n}");
  187. }
  188. println!(" with native code {}", t.with_native);
  189. for (stage, n) in &t.native_stages {
  190. println!(" {:<18} {n}", format!("{stage:?}"));
  191. }
  192. for (e, n) in &t.native_errors {
  193. println!(" native unreadable {n}: {e}");
  194. }
  195. if t.with_native > 0 {
  196. println!(
  197. " decoded programs {} ({} instructions)",
  198. t.decoded, t.instructions
  199. );
  200. for (e, n) in &t.decode_errors {
  201. println!(" decode failed {n}: {e}");
  202. }
  203. let mut unnamed: Vec<_> = t.unnamed.iter().collect();
  204. unnamed.sort_by_key(|&(_, n)| std::cmp::Reverse(*n));
  205. for (op, n) in unnamed.iter().take(10) {
  206. println!(" opcode not in table {op} x{n}");
  207. }
  208. }
  209. if t.containers == 0 {
  210. println!("(none found: shaders may sit in compressed or encrypted archives)");
  211. }
  212. Ok(())
  213. }
  214. fn format_instruction(i: &Instruction, wave64: bool) -> String {
  215. let words: Vec<_> = i.words.iter().map(|w| format!("{w:08X}")).collect();
  216. let text = match i.name() {
  217. Some(_) => i.text(wave64),
  218. None => format!("<{:?} {:#x}>", i.encoding, i.opcode),
  219. };
  220. format!(" {:06x}: {:<44} {text}", i.offset, words.join(" "))
  221. }