├── assets ├── ghidra_decompile.png └── instruction_search.png ├── scripts ├── startamb.sh ├── conv_offset.sh ├── newdump.sh └── extract_start_pcs.py ├── patch └── fs-uae-3.0.5_dump.patch ├── Cargo.toml ├── src ├── cli.rs ├── memdump.rs ├── utils.rs ├── main.rs ├── cpustep.rs └── dump.rs ├── Cargo.lock ├── README.md └── LICENSE /assets/ghidra_decompile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kermitfrog/Amiga-Re-Engineering/HEAD/assets/ghidra_decompile.png -------------------------------------------------------------------------------- /assets/instruction_search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kermitfrog/Amiga-Re-Engineering/HEAD/assets/instruction_search.png -------------------------------------------------------------------------------- /scripts/startamb.sh: -------------------------------------------------------------------------------- 1 | #!/bin/zsh 2 | #fs-uae /home/harddisk/arek/documents/FS-UAE/Configurations/Ambermoon.fs-uae 3 | fs-uae /home/harddisk/arek/documents/FS-UAE/Configurations/EAmbermoon.fs-uae 4 | 5 | -------------------------------------------------------------------------------- /scripts/conv_offset.sh: -------------------------------------------------------------------------------- 1 | O=0x06F3D1D8 2 | while true ; do 3 | read offset 4 | echo is 5 | qalc -b 16 $O+0x$offset | cut -dx -f2 6 | echo or 7 | qalc -b 16 $O-0x$offset | cut -dx -f2 8 | echo '\n' 9 | done 10 | -------------------------------------------------------------------------------- /patch/fs-uae-3.0.5_dump.patch: -------------------------------------------------------------------------------- 1 | diff -rwu fs-uae-3.0.5/src/debug.cpp ../fs-uae-3.0.5/src/debug.cpp 2 | --- fs-uae-3.0.5/src/debug.cpp 2019-05-17 19:57:50.000000000 +0200 3 | +++ ../fs-uae-3.0.5/src/debug.cpp 2021-01-02 14:13:28.132873433 +0100 4 | @@ -5258,7 +5258,9 @@ 5 | console_out (_T(">")); 6 | console_flush (); 7 | debug_linecounter = 0; 8 | - v = console_get (input, MAX_LINEWIDTH); 9 | + v = 1; 10 | + input[0] = 't'; 11 | + input[1] = '\n'; 12 | if (v < 0) 13 | return; 14 | if (v == 0) 15 | -------------------------------------------------------------------------------- /scripts/newdump.sh: -------------------------------------------------------------------------------- 1 | #!/bin/zsh 2 | #/home/harddisk/arek/projects/_patching/fs-uae-3.0.5/fs-uae /home/harddisk/arek/documents/FS-UAE/Configurations/Ambermoon.fs-uae > /tmp/opcode.log 3 | /home/harddisk/arek/projects/_patching/fs-uae-3.0.5/fs-uae /home/harddisk/arek/documents/FS-UAE/Configurations/EAmbermoon.fs-uae > /tmp/opcode.log 4 | 5 | echo "description: (empty for dont copy)" 6 | read desc 7 | if [ "$desc" = "" ] ; then 8 | exit 0 9 | fi 10 | mkdir $desc 11 | mv /tmp/opcode.log $desc 12 | cp offset $desc/ 13 | #cd $desc 14 | #/home/harddisk/arek/amiga/ambm/dump-analyzers/extract_start_pcs.py . 15 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dump-analyzer" 3 | version = "0.1.0" 4 | authors = ["Arkadiusz Guzinski "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | bincode = "1.3.1" 11 | rustc-serialize = "0.3.25" 12 | serde = {version = "1.0", features = ["derive"]} 13 | serde_derive = "1.0.118" 14 | serde-big-array = "0.3.0" 15 | array-init = "1.0.0" 16 | walkdir = "2" 17 | twoway = "0.2.2" 18 | roxmltree = "0.14.0" 19 | clap = "3.0.0-beta.2" 20 | 21 | [build-dependencies] 22 | clap = "3.0.0-beta.2" 23 | clap_generate = "3.0.0-beta.2" 24 | serde = {version = "1.0", features = ["derive"]} 25 | serde_derive = "1.0.118" 26 | serde-big-array = "0.3.0" 27 | rustc-serialize = "0.3.25" 28 | -------------------------------------------------------------------------------- /scripts/extract_start_pcs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import os 3 | import sys 4 | 5 | # Extracting starting pcs is actually better done with dump-analyzer p now 6 | # This script is kept, because of the PC history file it creates 7 | PC = 1 8 | 9 | dump_dir = sys.argv[1] 10 | if len(sys.argv) > 2: 11 | max_count = sys.argv[2] 12 | else: 13 | max_count = 1 14 | 15 | if not os.path.isdir(dump_dir): 16 | exit(1) 17 | 18 | if not os.path.isfile(dump_dir + '/hist'): 19 | os.system("ack -B1 \'Next PC:\' " + dump_dir + "/opcode.log | ack -v \'Next PC:\' | ack -v \'^--$\' > " + dump_dir + "/pcs") 20 | os.system("cut -f1 -d\\ " + dump_dir + "/pcs | sort | uniq -c | sort -n > " + dump_dir + "/hist") 21 | 22 | with open(dump_dir + "/hist") as hist: 23 | line = hist.readline().split() 24 | pc_start = int(line[PC], 16) 25 | pc_last = pc_start 26 | while True: 27 | line = hist.readline().split() 28 | if int(line[0]) > max_count: 29 | exit(0) 30 | 31 | pc_new = int(line[PC], 16) 32 | if pc_new > pc_last + 10: 33 | print("{0:0>8X}".format(pc_start)) 34 | pc_start = pc_new 35 | pc_last = pc_new 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | use clap::{Arg, App, ValueHint, AppSettings}; 2 | 3 | pub fn args() -> clap::App<'static> { 4 | App::new("Dump-Analyzer") 5 | .setting(AppSettings::ArgRequiredElseHelp) 6 | .setting(AppSettings::VersionlessSubcommands) 7 | .author("Arkadiusz Guzinski ") 8 | .about("Helps you make sense of hacked FS-UAE instruction dump\nFor most commands\n\ 9 | ... dir is a directory containing the associated data, see help-fs for filename details\n\ 10 | ... pc is the program counter (value displayed above \"Next PC:\") in hex\n\ 11 | ... count is number of instructions before|after pc (depending on subcommand) 12 | ") 13 | .arg(Arg::new("compact").short('s').global(true) 14 | .about("use compact mode for summary") 15 | ) 16 | .arg(Arg::new("colors").short('c').global(true) 17 | .about("use console colors") 18 | ) 19 | .arg(Arg::new("no-colors").short('b').global(true) 20 | .about("disable console colors").conflicts_with("colors") 21 | ) 22 | .arg(Arg::new("indent").short('i').global(true) 23 | .about("intent by [num] spaces") 24 | .takes_value(true) 25 | ) 26 | .arg(Arg::new("offset-mode").short('o').global(true) 27 | .about("print program counters as..") 28 | .possible_values(&["dump", "translated", "both"]) 29 | ) 30 | .arg(Arg::new("function-names").short('n').global(true) 31 | .about("print function names if possible") 32 | .possible_values(&["never", "entry", "always"]) 33 | ) 34 | .arg(Arg::new("traps").short('t').global(true) 35 | .about("show interrupts (traps)") 36 | ) 37 | 38 | .subcommand(App::new("search-value").visible_aliases(&["d", "D"]) 39 | .setting(AppSettings::ArgRequiredElseHelp) 40 | .about("searches for a value (dec) in one or more dumps") 41 | .arg(Arg::new("dir val").multiple(true).min_values(2).required(true) 42 | .value_hint(ValueHint::DirPath)// TODO make this work... why doesn't it? 43 | .about("pairs of directory with dump and a search value in decimal") 44 | ) 45 | ) 46 | 47 | .subcommand(App::new("print-mem-commands").visible_alias("m") 48 | .setting(AppSettings::ArgRequiredElseHelp) 49 | .about("print commands to get memdump only for related addresses from fs-uae debugger") 50 | .long_about("print commands to get memdump only for related addresses from fs-uae debugger\n\ 51 | This may be useful if you want to look at the memory yourself.\n\ 52 | For getting all memory it's probably better to simply use the 'S' debugger command") 53 | .arg(Arg::new("dir").required(true).index(1) 54 | .value_hint(ValueHint::DirPath) 55 | .about("directory containing memory dump") 56 | ) 57 | .arg(Arg::new("pc").required(true).index(2) 58 | .value_hint(ValueHint::Other) 59 | .about("program counter (hex)") 60 | ) 61 | .arg(Arg::new("count").required(true).index(3) 62 | .value_hint(ValueHint::Other) 63 | .about("lines of memory around the actual data") 64 | ) 65 | ) 66 | 67 | .subcommand(App::new("summary-long").visible_aliases(&["i", "I"]) 68 | .setting(AppSettings::ArgRequiredElseHelp) 69 | .about("print summary of instructions leading to pc (uses linux terminal colors)") 70 | .arg(Arg::new("dir").required(true).index(1) 71 | .value_hint(ValueHint::DirPath) 72 | .about("directory containing the dump") 73 | ) 74 | .arg(Arg::new("pc").required(true).index(2) 75 | .about("program counter (hex)") 76 | .value_hint(ValueHint::Other) 77 | ) 78 | .arg(Arg::new("count").required(true).index(3) 79 | .about("number of instructions to print before pc") 80 | .value_hint(ValueHint::Other) 81 | ) 82 | .arg(Arg::new("val").multiple(true).index(4) 83 | .about("values to highlight; format is as printed (hex)") 84 | .value_hint(ValueHint::Other) 85 | ) 86 | ) 87 | 88 | .subcommand(App::new("summary").visible_aliases(&["s", "S"]) 89 | .setting(AppSettings::ArgRequiredElseHelp) 90 | .about("print compact summary of instructions leading to pc") 91 | .arg(Arg::new("dir").required(true).index(1) 92 | .value_hint(ValueHint::DirPath) 93 | .about("directory containing the dump") 94 | ) 95 | .arg(Arg::new("pc").required(true).index(2) 96 | .about("program counter (hex)") 97 | .value_hint(ValueHint::Other) 98 | ) 99 | .arg(Arg::new("count").required(true).index(3) 100 | .about("number of instructions to print before pc") 101 | .value_hint(ValueHint::Other) 102 | ) 103 | .arg(Arg::new("val").multiple(true).index(4) 104 | .about("values to highlight; format is as printed (hex)") 105 | .value_hint(ValueHint::Other) 106 | ) 107 | ) 108 | 109 | .subcommand(App::new("print-ghidra-search-pattern").visible_alias("g") 110 | .setting(AppSettings::ArgRequiredElseHelp) 111 | .about("generate ghidra instruction pattern search text for code at pc") 112 | .arg(Arg::new("dir").required(true).index(1) 113 | .about("directory containing the dump") 114 | .value_hint(ValueHint::DirPath) 115 | ) 116 | .arg(Arg::new("pc").required(true).index(2) 117 | .about("program counter (hex)") 118 | .value_hint(ValueHint::Other) 119 | ) 120 | .arg(Arg::new("count").index(3) 121 | .about("number of instructions to print after pc (default: 30)") 122 | .value_hint(ValueHint::Other) 123 | ) 124 | ) 125 | 126 | .subcommand(App::new("starting-pcs").visible_aliases(&["p", "P"]) 127 | .setting(AppSettings::ArgRequiredElseHelp) 128 | .about("print starting pcs for functions that are called just once in dump") 129 | .arg(Arg::new("dir").required(true).index(1) 130 | .about("directory containing the dump") 131 | .value_hint(ValueHint::DirPath) 132 | ) 133 | ) 134 | 135 | .subcommand(App::new("map-data").visible_alias("M") 136 | .setting(AppSettings::ArgRequiredElseHelp) 137 | .about("map data to memory dump") 138 | .arg(Arg::new("dir").required(true).index(1) 139 | .about("directory containing the memory dump") 140 | .value_hint(ValueHint::DirPath) 141 | ) 142 | .arg(Arg::new("data-dir").required(true).index(2) 143 | .value_hint(ValueHint::DirPath) 144 | ) 145 | ) 146 | 147 | .subcommand(App::new("stack").visible_aliases(&["t", "T"]) 148 | .setting(AppSettings::ArgRequiredElseHelp) 149 | .about("print call hierarchy leading to pc") 150 | .arg(Arg::new("dir").required(true).index(1) 151 | .about("directory containing the dump") 152 | .value_hint(ValueHint::DirPath) 153 | ) 154 | .arg(Arg::new("pc").required(true).index(2) 155 | .about("program counter (hex)") 156 | .value_hint(ValueHint::Other) 157 | ) 158 | ) 159 | 160 | .subcommand(App::new("registers").visible_aliases(&["io", "IO"]) 161 | .setting(AppSettings::ArgRequiredElseHelp) 162 | .about(" print register states at specific pcs") 163 | .arg(Arg::new("dir").required(true).index(1) 164 | .about("directory containing the dump") 165 | .value_hint(ValueHint::DirPath) 166 | ) 167 | .arg(Arg::new("pc_start").required(true).index(2) 168 | .about("program counter at start of a function (hex)") 169 | .value_hint(ValueHint::Other) 170 | ) 171 | .arg(Arg::new("pc_end").required(true).index(3) 172 | .about("program counter at end of a function (hex)") 173 | .value_hint(ValueHint::Other) 174 | ) 175 | ) 176 | 177 | .subcommand(App::new("memset-diff").visible_alias("sd") 178 | .setting(AppSettings::ArgRequiredElseHelp) 179 | .about("print differences between sets of memory dumps. dir contains directories named set_id") 180 | .arg(Arg::new("set_dir").required(true).index(1) 181 | .about("dir containing directories named set_id (see help-fs)") 182 | .value_hint(ValueHint::DirPath) 183 | ) 184 | ) 185 | 186 | .subcommand(App::new("calls").visible_aliases(&["c", "C"]) 187 | .setting(AppSettings::ArgRequiredElseHelp) 188 | .about("print call hierarchy of dump") 189 | .arg(Arg::new("dir").required(true).index(1) 190 | .about("directory containing the dump") 191 | .value_hint(ValueHint::DirPath) 192 | ) 193 | ) 194 | 195 | .subcommand(App::new("help-fs").about("print info about the expected file structure")) 196 | } -------------------------------------------------------------------------------- /src/memdump.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2020 Arkadiusz Guzinski 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | use std::fs; 18 | use std::fs::File; 19 | use std::io::{BufReader, BufRead, Read}; 20 | use std::cmp::{min, max}; 21 | use walkdir::WalkDir; 22 | use twoway; 23 | use std::collections::BTreeSet; 24 | use std::process::exit; 25 | use std::ops::Index; 26 | 27 | pub struct MemDump { 28 | /// structure for a partial memory dump 29 | parts: Vec 30 | } 31 | 32 | struct MemPart { 33 | /// structure for a consecutive part of MemDump 34 | from: u32, 35 | to: u32, 36 | data: Vec, 37 | } 38 | 39 | impl MemDump { 40 | /// create empty MemDump 41 | pub fn new() -> MemDump { MemDump { parts: Vec::new() } } 42 | 43 | /// load MemDump from directory path 44 | pub fn from_dir(path: String) -> std::io::Result { 45 | let mut mem_dump = MemDump { parts: Vec::new() }; 46 | let paths = fs::read_dir(&path)?; 47 | for dir_entry_opt in paths { 48 | let dir_entry = dir_entry_opt?; 49 | let fname_os = dir_entry.file_name(); 50 | let fname = fname_os.to_str().unwrap_or(""); 51 | match u32::from_str_radix(fname, 16) { 52 | Ok(offset) => { 53 | let file = File::open(dir_entry.path())?; 54 | mem_dump.load_from_bin(file, offset)?; 55 | } 56 | _ => {} 57 | } 58 | } 59 | if mem_dump.parts.len() > 0 { 60 | return Ok(mem_dump); 61 | } 62 | 63 | let file = File::open(path.to_owned() + "/mem")?; 64 | MemDump::load_from_text(file) 65 | } 66 | 67 | /// load MemPart from a file in directory path. filename is the starting address in hex (no 0x) 68 | fn load_from_bin(&mut self, mut file: File, start: u32) -> std::io::Result<()> { 69 | // let size = file. 70 | let mut data = Vec::new(); 71 | file.read_to_end(&mut data)?; 72 | self.parts.push(MemPart { from: start, to: data.len() as u32 + start, data }); 73 | Ok(()) 74 | } 75 | 76 | /// load MemDump from a file called mem in directory path 77 | /// expects fs-uae memdump from debugger, '>' removed, newline at end 78 | fn load_from_text(file: File) -> std::io::Result { 79 | let mut buf_reader = BufReader::new(file); 80 | let mut part = MemPart { from: 0, to: 0, data: Vec::new() }; 81 | let mut mem_dump = MemDump { parts: Vec::new() }; 82 | 83 | loop { 84 | let mut line = Default::default(); 85 | let n = buf_reader.read_line(&mut line)?; 86 | if n <= 48 { 87 | break; 88 | } 89 | let addr = u32::from_str_radix(line.get(0..=7).unwrap(), 16).unwrap(); 90 | if part.from == 0 { 91 | part.from = addr; 92 | } else if part.to + 16 < addr { 93 | mem_dump.parts.push(part); 94 | part = MemPart { from: addr, to: addr + 15, data: Vec::new() }; 95 | } 96 | part.to = addr + 15; 97 | let mut offset = 0; 98 | let mut gap = false; 99 | for _ in 0..16 { 100 | let val = line.get(offset + 9..=offset + 10).unwrap_or_default(); 101 | part.data.push(u8::from_str_radix(val, 16).unwrap_or_default()); 102 | offset += if gap { 3 } else { 2 }; 103 | gap = !gap; 104 | } 105 | } 106 | mem_dump.parts.push(part); 107 | Ok(mem_dump) 108 | } 109 | 110 | /// returns count bytes from MemDump at address addr, or "??" if addr is not in current dump 111 | pub fn get_mem_at(&self, addr: u32, count: usize) -> String { 112 | for part in &self.parts { 113 | if (part.from..=part.to).contains(&addr) { 114 | let from = (addr & 0xffffffe - part.from) as usize; 115 | let to = min(from + max(count, 4), part.to as usize); 116 | let mut r = format!("{:08X}= ", addr); 117 | for i in 0..(to - from) { 118 | r += format!("{:02x}", part.data[i]).as_str(); 119 | } 120 | return r; 121 | } 122 | } 123 | format!("{:08X}: ??", addr) 124 | } 125 | 126 | pub fn map_data(&self, path: String, offset: u32) -> std::io::Result<()> { 127 | println!("File\tIndex\tMem\tTranslated\tSize"); 128 | for entry_opt in WalkDir::new(path) { 129 | let entry = entry_opt?; 130 | 131 | let full_path = entry.path(); 132 | // println!("File = {}", full_path.to_str().unwrap()); 133 | let mut components = entry.path().components().rev(); 134 | if let Some(name) = components.next() { 135 | if let Some(dir) = components.next() { 136 | match File::open(full_path) { 137 | Ok(file) => 138 | self.map_data_for(file, 139 | format!("{}\t{}\t", 140 | dir.as_os_str().to_str().unwrap_or_default(), 141 | name.as_os_str().to_str().unwrap_or_default()), 142 | offset), 143 | _ => println!("failed reading file {}", full_path.to_str().unwrap_or_default()) 144 | } 145 | }; 146 | }; 147 | } 148 | 149 | Ok(()) 150 | } 151 | 152 | fn map_data_for(&self, mut file: File, pre: String, offset: u32) { 153 | let mut data = Vec::new(); 154 | if let Ok(_) = file.read_to_end(&mut data) { 155 | if !MemDump::check_entropy(&data) { 156 | return; 157 | } 158 | for part in self.parts.iter() { 159 | let mut last_pos = 0; 160 | let start = part.from as usize; 161 | let s_mod = (part.from - offset) as usize; 162 | loop { 163 | let slice = &part.data.as_slice()[last_pos..]; 164 | // println!("BLUB!!!! {} {}", slice.len(), data.len()); 165 | if let Some(pos) = twoway::find_bytes(&slice, data.as_slice()) { 166 | // if let Some(pos) = MemDump::find_bytes(&slice, data.as_slice()) { 167 | if last_pos > pos { 168 | break; 169 | } 170 | println!("{}0x{:08X}\t0x{:08X}\t{}", &pre, 171 | start + pos, 172 | s_mod + pos, 173 | data.len() 174 | ); 175 | last_pos = pos + 1; 176 | } else { break; } 177 | } 178 | } 179 | } 180 | } 181 | 182 | fn check_entropy(data: &Vec) -> bool { 183 | let mut size = data.len(); 184 | for byte in data.iter() { 185 | if *byte == 0 { 186 | size -= 1 187 | } 188 | } 189 | size >= 8 190 | } 191 | 192 | pub fn diff_only(&self, other: &MemDump, only: Option>, invert: bool) -> BTreeSet { 193 | if self.parts.len() != other.parts.len() { 194 | exit(1); 195 | } 196 | let mut results: BTreeSet = BTreeSet::new(); 197 | match only { 198 | Some(only) => { 199 | for i in only.iter() { 200 | if (self[*i] == other[*i]) == invert { 201 | results.insert(*i); 202 | } 203 | } 204 | }, 205 | None => { 206 | for i in 0..self.parts.len() { 207 | let l_part = &self.parts[i]; 208 | let r_part = &other.parts[i]; 209 | if l_part.from != r_part.from || l_part.to != r_part.to { 210 | exit(1); 211 | } 212 | for j in 0..l_part.data.len() { 213 | if (l_part.data[j] == r_part.data[j]) == invert { 214 | results.insert(j as u32 + l_part.from); 215 | } 216 | } 217 | } 218 | } 219 | } 220 | results 221 | } 222 | 223 | /* fn find_bytes(text: &[u8], pattern: &[u8]) -> Option { 224 | println!("blub!!!! {} {}", text.len(), pattern.len()); 225 | 'outer: for i in 0..text.len() - pattern.len() { 226 | println!("blub {}", i); 227 | 'inner: for j in 0..pattern.len() { 228 | println!("bla {} {}", i, j); 229 | if text[i] != pattern[j] { 230 | continue 'outer; 231 | } 232 | } 233 | return Some(i); 234 | } 235 | None 236 | }*/ 237 | } 238 | 239 | impl ToString for MemDump { 240 | /// output as from fs-uae 241 | fn to_string(&self) -> String { 242 | let mut s = String::new(); 243 | s += "MemDump["; 244 | for part in self.parts.iter() { 245 | s += format!("{:08X} - {:08X} ok = {},", part.from, part.to, part.to - part.from == part.data.len() as u32).as_str(); 246 | } 247 | s += "]"; 248 | s 249 | } 250 | } 251 | 252 | impl Index for MemDump { 253 | type Output = u8; 254 | 255 | fn index(&self, index: u32) -> &Self::Output { 256 | for part in &self.parts { 257 | if (part.from..=part.to).contains(&index) { 258 | return &part.data[(index - part.from) as usize] 259 | } 260 | } 261 | return &self.parts[0].data[0] 262 | } 263 | } -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "array-init" 7 | version = "1.0.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "a51c983d65b6691893a791e55aa8bda43bbd9b11f947e5a9581710362277cc95" 10 | 11 | [[package]] 12 | name = "atty" 13 | version = "0.2.14" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 16 | dependencies = [ 17 | "hermit-abi", 18 | "libc", 19 | "winapi", 20 | ] 21 | 22 | [[package]] 23 | name = "autocfg" 24 | version = "1.0.1" 25 | source = "registry+https://github.com/rust-lang/crates.io-index" 26 | checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" 27 | 28 | [[package]] 29 | name = "bincode" 30 | version = "1.3.1" 31 | source = "registry+https://github.com/rust-lang/crates.io-index" 32 | checksum = "f30d3a39baa26f9651f17b375061f3233dde33424a8b72b0dbe93a68a0bc896d" 33 | dependencies = [ 34 | "byteorder", 35 | "serde", 36 | ] 37 | 38 | [[package]] 39 | name = "bitflags" 40 | version = "1.2.1" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" 43 | 44 | [[package]] 45 | name = "byteorder" 46 | version = "1.3.4" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" 49 | 50 | [[package]] 51 | name = "clap" 52 | version = "3.0.0-beta.2" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "4bd1061998a501ee7d4b6d449020df3266ca3124b941ec56cf2005c3779ca142" 55 | dependencies = [ 56 | "atty", 57 | "bitflags", 58 | "clap_derive", 59 | "indexmap", 60 | "lazy_static", 61 | "os_str_bytes", 62 | "strsim", 63 | "termcolor", 64 | "textwrap", 65 | "unicode-width", 66 | "vec_map", 67 | ] 68 | 69 | [[package]] 70 | name = "clap_derive" 71 | version = "3.0.0-beta.2" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | checksum = "370f715b81112975b1b69db93e0b56ea4cd4e5002ac43b2da8474106a54096a1" 74 | dependencies = [ 75 | "heck", 76 | "proc-macro-error", 77 | "proc-macro2", 78 | "quote", 79 | "syn", 80 | ] 81 | 82 | [[package]] 83 | name = "clap_generate" 84 | version = "3.0.0-beta.2" 85 | source = "registry+https://github.com/rust-lang/crates.io-index" 86 | checksum = "adf420f8b687b628d2915ccfd43a660c437a170432e3fbcb66944e8717a0d68f" 87 | dependencies = [ 88 | "clap", 89 | ] 90 | 91 | [[package]] 92 | name = "dump-analyzer" 93 | version = "0.1.0" 94 | dependencies = [ 95 | "array-init", 96 | "bincode", 97 | "clap", 98 | "clap_generate", 99 | "roxmltree", 100 | "rustc-serialize", 101 | "serde", 102 | "serde-big-array", 103 | "serde_derive", 104 | "twoway", 105 | "walkdir", 106 | ] 107 | 108 | [[package]] 109 | name = "hashbrown" 110 | version = "0.9.1" 111 | source = "registry+https://github.com/rust-lang/crates.io-index" 112 | checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" 113 | 114 | [[package]] 115 | name = "heck" 116 | version = "0.3.2" 117 | source = "registry+https://github.com/rust-lang/crates.io-index" 118 | checksum = "87cbf45460356b7deeb5e3415b5563308c0a9b057c85e12b06ad551f98d0a6ac" 119 | dependencies = [ 120 | "unicode-segmentation", 121 | ] 122 | 123 | [[package]] 124 | name = "hermit-abi" 125 | version = "0.1.18" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "322f4de77956e22ed0e5032c359a0f1273f1f7f0d79bfa3b8ffbc730d7fbcc5c" 128 | dependencies = [ 129 | "libc", 130 | ] 131 | 132 | [[package]] 133 | name = "indexmap" 134 | version = "1.6.1" 135 | source = "registry+https://github.com/rust-lang/crates.io-index" 136 | checksum = "4fb1fa934250de4de8aef298d81c729a7d33d8c239daa3a7575e6b92bfc7313b" 137 | dependencies = [ 138 | "autocfg", 139 | "hashbrown", 140 | ] 141 | 142 | [[package]] 143 | name = "lazy_static" 144 | version = "1.4.0" 145 | source = "registry+https://github.com/rust-lang/crates.io-index" 146 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 147 | 148 | [[package]] 149 | name = "libc" 150 | version = "0.2.84" 151 | source = "registry+https://github.com/rust-lang/crates.io-index" 152 | checksum = "1cca32fa0182e8c0989459524dc356b8f2b5c10f1b9eb521b7d182c03cf8c5ff" 153 | 154 | [[package]] 155 | name = "memchr" 156 | version = "2.3.4" 157 | source = "registry+https://github.com/rust-lang/crates.io-index" 158 | checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525" 159 | 160 | [[package]] 161 | name = "os_str_bytes" 162 | version = "2.4.0" 163 | source = "registry+https://github.com/rust-lang/crates.io-index" 164 | checksum = "afb2e1c3ee07430c2cf76151675e583e0f19985fa6efae47d6848a3e2c824f85" 165 | 166 | [[package]] 167 | name = "proc-macro-error" 168 | version = "1.0.4" 169 | source = "registry+https://github.com/rust-lang/crates.io-index" 170 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" 171 | dependencies = [ 172 | "proc-macro-error-attr", 173 | "proc-macro2", 174 | "quote", 175 | "syn", 176 | "version_check", 177 | ] 178 | 179 | [[package]] 180 | name = "proc-macro-error-attr" 181 | version = "1.0.4" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" 184 | dependencies = [ 185 | "proc-macro2", 186 | "quote", 187 | "version_check", 188 | ] 189 | 190 | [[package]] 191 | name = "proc-macro2" 192 | version = "1.0.24" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" 195 | dependencies = [ 196 | "unicode-xid", 197 | ] 198 | 199 | [[package]] 200 | name = "quote" 201 | version = "1.0.7" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" 204 | dependencies = [ 205 | "proc-macro2", 206 | ] 207 | 208 | [[package]] 209 | name = "roxmltree" 210 | version = "0.14.0" 211 | source = "registry+https://github.com/rust-lang/crates.io-index" 212 | checksum = "bf58a7d05b28e14b1e8902fa04c4d5d6109f5450ef71a5e6597f66e53f541504" 213 | dependencies = [ 214 | "xmlparser", 215 | ] 216 | 217 | [[package]] 218 | name = "rustc-serialize" 219 | version = "0.3.25" 220 | source = "registry+https://github.com/rust-lang/crates.io-index" 221 | checksum = "fe834bc780604f4674073badbad26d7219cadfb4a2275802db12cbae17498401" 222 | 223 | [[package]] 224 | name = "same-file" 225 | version = "1.0.6" 226 | source = "registry+https://github.com/rust-lang/crates.io-index" 227 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 228 | dependencies = [ 229 | "winapi-util", 230 | ] 231 | 232 | [[package]] 233 | name = "serde" 234 | version = "1.0.118" 235 | source = "registry+https://github.com/rust-lang/crates.io-index" 236 | checksum = "06c64263859d87aa2eb554587e2d23183398d617427327cf2b3d0ed8c69e4800" 237 | dependencies = [ 238 | "serde_derive", 239 | ] 240 | 241 | [[package]] 242 | name = "serde-big-array" 243 | version = "0.3.0" 244 | source = "registry+https://github.com/rust-lang/crates.io-index" 245 | checksum = "52309f7932ab258e58bcf73cc89037e307ffef3bcfb7ce7a246580c26f81dc55" 246 | dependencies = [ 247 | "serde", 248 | "serde_derive", 249 | ] 250 | 251 | [[package]] 252 | name = "serde_derive" 253 | version = "1.0.118" 254 | source = "registry+https://github.com/rust-lang/crates.io-index" 255 | checksum = "c84d3526699cd55261af4b941e4e725444df67aa4f9e6a3564f18030d12672df" 256 | dependencies = [ 257 | "proc-macro2", 258 | "quote", 259 | "syn", 260 | ] 261 | 262 | [[package]] 263 | name = "strsim" 264 | version = "0.10.0" 265 | source = "registry+https://github.com/rust-lang/crates.io-index" 266 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 267 | 268 | [[package]] 269 | name = "syn" 270 | version = "1.0.54" 271 | source = "registry+https://github.com/rust-lang/crates.io-index" 272 | checksum = "9a2af957a63d6bd42255c359c93d9bfdb97076bd3b820897ce55ffbfbf107f44" 273 | dependencies = [ 274 | "proc-macro2", 275 | "quote", 276 | "unicode-xid", 277 | ] 278 | 279 | [[package]] 280 | name = "termcolor" 281 | version = "1.1.2" 282 | source = "registry+https://github.com/rust-lang/crates.io-index" 283 | checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4" 284 | dependencies = [ 285 | "winapi-util", 286 | ] 287 | 288 | [[package]] 289 | name = "textwrap" 290 | version = "0.12.1" 291 | source = "registry+https://github.com/rust-lang/crates.io-index" 292 | checksum = "203008d98caf094106cfaba70acfed15e18ed3ddb7d94e49baec153a2b462789" 293 | dependencies = [ 294 | "unicode-width", 295 | ] 296 | 297 | [[package]] 298 | name = "twoway" 299 | version = "0.2.2" 300 | source = "registry+https://github.com/rust-lang/crates.io-index" 301 | checksum = "c57ffb460d7c24cd6eda43694110189030a3d1dfe418416d9468fd1c1d290b47" 302 | dependencies = [ 303 | "memchr", 304 | "unchecked-index", 305 | ] 306 | 307 | [[package]] 308 | name = "unchecked-index" 309 | version = "0.2.2" 310 | source = "registry+https://github.com/rust-lang/crates.io-index" 311 | checksum = "eeba86d422ce181a719445e51872fa30f1f7413b62becb52e95ec91aa262d85c" 312 | 313 | [[package]] 314 | name = "unicode-segmentation" 315 | version = "1.7.1" 316 | source = "registry+https://github.com/rust-lang/crates.io-index" 317 | checksum = "bb0d2e7be6ae3a5fa87eed5fb451aff96f2573d2694942e40543ae0bbe19c796" 318 | 319 | [[package]] 320 | name = "unicode-width" 321 | version = "0.1.8" 322 | source = "registry+https://github.com/rust-lang/crates.io-index" 323 | checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" 324 | 325 | [[package]] 326 | name = "unicode-xid" 327 | version = "0.2.1" 328 | source = "registry+https://github.com/rust-lang/crates.io-index" 329 | checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" 330 | 331 | [[package]] 332 | name = "vec_map" 333 | version = "0.8.2" 334 | source = "registry+https://github.com/rust-lang/crates.io-index" 335 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" 336 | 337 | [[package]] 338 | name = "version_check" 339 | version = "0.9.2" 340 | source = "registry+https://github.com/rust-lang/crates.io-index" 341 | checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed" 342 | 343 | [[package]] 344 | name = "walkdir" 345 | version = "2.3.1" 346 | source = "registry+https://github.com/rust-lang/crates.io-index" 347 | checksum = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" 348 | dependencies = [ 349 | "same-file", 350 | "winapi", 351 | "winapi-util", 352 | ] 353 | 354 | [[package]] 355 | name = "winapi" 356 | version = "0.3.9" 357 | source = "registry+https://github.com/rust-lang/crates.io-index" 358 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 359 | dependencies = [ 360 | "winapi-i686-pc-windows-gnu", 361 | "winapi-x86_64-pc-windows-gnu", 362 | ] 363 | 364 | [[package]] 365 | name = "winapi-i686-pc-windows-gnu" 366 | version = "0.4.0" 367 | source = "registry+https://github.com/rust-lang/crates.io-index" 368 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 369 | 370 | [[package]] 371 | name = "winapi-util" 372 | version = "0.1.5" 373 | source = "registry+https://github.com/rust-lang/crates.io-index" 374 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 375 | dependencies = [ 376 | "winapi", 377 | ] 378 | 379 | [[package]] 380 | name = "winapi-x86_64-pc-windows-gnu" 381 | version = "0.4.0" 382 | source = "registry+https://github.com/rust-lang/crates.io-index" 383 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 384 | 385 | [[package]] 386 | name = "xmlparser" 387 | version = "0.13.3" 388 | source = "registry+https://github.com/rust-lang/crates.io-index" 389 | checksum = "114ba2b24d2167ef6d67d7d04c8cc86522b87f490025f39f0303b7db5bf5e3d8" 390 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2020 Arkadiusz Guzinski 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | use std::collections::BTreeSet; 19 | use std::fs::{File}; 20 | use std::io::{BufReader, BufRead, Read}; 21 | use std::cmp::Ordering; 22 | use clap::{ArgMatches, Values}; 23 | use crate::utils::Visibility::{Hidden, Brief}; 24 | use std::path::{PathBuf}; 25 | use roxmltree::{Document, ParsingOptions}; 26 | use std::iter::Peekable; 27 | 28 | #[derive(Eq, PartialEq)] 29 | pub enum Visibility { Hidden, Brief, Verbose } 30 | 31 | /// stores variables for formatting the output 32 | pub struct FormatHelper { 33 | /// replace occurrences of value1 with value2 - used for terminal colors / bold 34 | pub repl: Vec<(String, String)>, 35 | /// use compact (1 line per instruction) output? 36 | pub compact: bool, 37 | /// use colors? 38 | pub colors: bool, 39 | /// how much space to use to indent per step of the call hierarchy 40 | pub indent: i16, 41 | /// pc offset for disassembler 42 | pub offset_mod: u32, 43 | pub print_both_offsets: bool, 44 | pub func_names: Visibility, 45 | /// 46 | pub show_interrupt: Visibility, 47 | info: GhidraInfo, 48 | } 49 | 50 | #[derive(Eq)] 51 | struct GhidraFun { 52 | pub start: u32, 53 | pub end: u32, 54 | pub name: String, 55 | } 56 | 57 | struct GhidraInfo { 58 | functions: BTreeSet, 59 | offset: u32, 60 | } 61 | 62 | impl FormatHelper { 63 | /// highlights values, by replacing them with colored versions 64 | pub fn col(&self, s: String) -> String { 65 | if !self.colors { 66 | return s; 67 | } 68 | let mut t = s.to_owned(); 69 | // TODO this is buggy - need to work through list, then see if something can be found at 70 | // index. currently returning after first occurence, to prevent buggy output 71 | for (v, r) in &self.repl { 72 | if let Some(i) = s.find(v) { 73 | if i % 2 == 0 { 74 | t.replace_range((t.len() - v.len())..t.len(), r.as_str()); 75 | return t.to_string(); 76 | } 77 | } 78 | } 79 | t.to_string() 80 | } 81 | 82 | /// return val as hex string, highlighting values, by replacing them with colored versions 83 | pub fn col_reg(&self, val: u32) -> String { 84 | let mut s = format!("{:08X}", val); 85 | for (v, r) in &self.repl { 86 | if s.ends_with(&v.as_str()) { 87 | s.replace_range((8 - v.len())..8, r.as_str()); 88 | } 89 | } 90 | s 91 | } 92 | 93 | /// construct FormatHelper with highlighting for certain values 94 | /// 95 | /// highlight: values to be colored 96 | pub fn for_values(highlight: &Values, compact: bool) -> FormatHelper { 97 | // pub fn for_values(highlight: &Vec, compact: bool) -> FormatHelper { 98 | // prepare colors 99 | let colors = [ 100 | "\x1b[32m", // green 101 | "\x1b[35m", // magenta 102 | "\x1b[36m", // cyan 103 | "\x1b[34m", // blue 104 | "\x1b[31m", // red 105 | "\x1b[33m", // yellow 106 | ]; 107 | let mut replacements: Vec<(String, String)> = Vec::new(); 108 | replacements.reserve(highlight.len()); 109 | for (h, i) in highlight.to_owned().zip(0..) { 110 | // for (h, i) in highlight.iter().zip(0..) { 111 | replacements.push((h.to_string(), format!("{}{}\x1b[0m", 112 | colors.get(i % colors.len()).unwrap(), h))); 113 | } 114 | FormatHelper { 115 | repl: replacements, 116 | compact, 117 | colors: true, 118 | indent: 2, 119 | offset_mod: 0, 120 | print_both_offsets: true, 121 | func_names: Visibility::Verbose, 122 | show_interrupt: Visibility::Brief, 123 | info: GhidraInfo { functions: BTreeSet::new(), offset: 0 }, 124 | } 125 | } 126 | 127 | /// construct FormatHelper without highlighting 128 | pub fn simple(compact: bool) -> FormatHelper { 129 | FormatHelper { 130 | repl: Vec::new(), 131 | compact, 132 | colors: false, 133 | indent: 2, 134 | offset_mod: 0, 135 | print_both_offsets: true, 136 | func_names: Visibility::Brief, 137 | show_interrupt: Visibility::Brief, 138 | info: GhidraInfo { functions: BTreeSet::new(), offset: 0 }, 139 | } 140 | } 141 | 142 | pub fn finalize(mut self, args: &ArgMatches) -> FormatHelper { 143 | if args.value_of("colors").is_some() { 144 | self.colors = true; 145 | } else if args.value_of("nocolors").is_some() { 146 | self.colors = false; 147 | } 148 | 149 | if let Some(indent) = args.value_of("indent") { 150 | self.indent = i16::from_str_radix(indent, 10).unwrap_or(2); 151 | } 152 | 153 | match args.value_of("offset-mode") { 154 | Some("dump") => { 155 | self.offset_mod = 0; 156 | self.print_both_offsets = false; 157 | } 158 | Some("translated") => { 159 | self.offset_mod = FormatHelper::get_offset(&args); 160 | self.print_both_offsets = false 161 | } 162 | Some("both") => { 163 | self.offset_mod = FormatHelper::get_offset(&args); 164 | self.print_both_offsets = true 165 | } 166 | _ => { 167 | if self.print_both_offsets { 168 | self.offset_mod = FormatHelper::get_offset(&args); 169 | } 170 | } 171 | } 172 | 173 | match args.value_of("function-names") { 174 | Some("never") => self.func_names = Hidden, 175 | Some("entry") => self.func_names = Brief, 176 | Some("always") => self.func_names = Visibility::Verbose, 177 | _ => {} 178 | } 179 | 180 | if self.func_names != Hidden { 181 | self.info.load(args, self.offset_mod); 182 | } 183 | 184 | if args.is_present("traps") { 185 | self.show_interrupt = Brief; 186 | } 187 | 188 | // todo load ghidra info 189 | 190 | return self; 191 | } 192 | 193 | /// load offset from path/offset or 0 if file is missing 194 | pub fn get_offset(args: &ArgMatches) -> u32 { 195 | let file_offset = FormatHelper::file_in_dir_or_parent(&args, "offset"); 196 | match file_offset { 197 | Some(file) => { 198 | let mut buf_reader = BufReader::new(file); 199 | let mut s = String::new(); 200 | let _ = buf_reader.read_line(&mut s); 201 | u32::from_str_radix(&s.trim_end(), 16).unwrap_or_default() 202 | } 203 | None => 0u32 204 | } 205 | } 206 | 207 | pub fn with_offset(&self, address: u32) -> u32 { 208 | return if address >= self.offset_mod { 209 | address - self.offset_mod 210 | } else { 211 | address + 0xf0000000 212 | }; 213 | } 214 | 215 | pub fn pc(&self, pc: u32) -> String { 216 | match (&self.func_names, &self.print_both_offsets) { 217 | (Hidden, false) => format!("{:08X}", self.with_offset(pc)), 218 | (Hidden, true) => format!("{:08X} ({:08X})", self.with_offset(pc), pc), 219 | (_, false) => { 220 | if let Some(s) = self.info.name_for(pc) { 221 | format!("{} ({:08X})", s, self.with_offset(pc)) 222 | } else { 223 | format!("{:08X}", self.with_offset(pc)) 224 | } 225 | } 226 | (_, true) => { 227 | if let Some(s) = self.info.name_for(pc) { 228 | format!("{} ({:08X}, {:08X})", s, self.with_offset(pc), pc) 229 | } else { 230 | format!("{:08X} ({:08X})", self.with_offset(pc), pc) 231 | } 232 | } 233 | } 234 | } 235 | 236 | pub fn padding(&self, depth: i16) -> String { 237 | let pad_max: usize = 60; 238 | let pad: usize = if depth >= 0 { (depth * self.indent) as usize } else { 0 }; 239 | // let pad_inline = if compact {0i16} else { pad }; 240 | return if pad <= pad_max { 241 | format!("{:>width$}", "", width = pad) 242 | } else { 243 | format!("{:>width$} ", depth, width = pad_max - 2) 244 | }; 245 | } 246 | 247 | pub fn file_in_dir_or_parent(args: &ArgMatches, f_name: &str) -> Option { 248 | let mut p: Peekable; 249 | let mut path = PathBuf::from( 250 | if let Some(d) = args.value_of("dir") { 251 | d 252 | } else if let Some(d) = args.value_of("set_dir") { 253 | d 254 | } else if let Some(d) = args.values_of("dir val") 255 | { 256 | if d.len() < 2 { 257 | return None; 258 | } 259 | p = d.peekable(); 260 | p.peek().unwrap() 261 | } else { 262 | return None; 263 | }); 264 | path.push(f_name); 265 | if !path.exists() { 266 | path.pop(); 267 | path.pop(); 268 | path.push(f_name); 269 | } 270 | if let Ok(file) = File::open(path) { 271 | Some(file) 272 | } else { 273 | None 274 | } 275 | } 276 | } 277 | 278 | impl GhidraInfo { 279 | pub fn load(&mut self, args: &ArgMatches, offset: u32) { 280 | self.offset = offset; 281 | if let Some(mut file) = FormatHelper::file_in_dir_or_parent(&args, "functions.xml") { 282 | let mut content = String::new(); 283 | if file.read_to_string(&mut content).is_err() { 284 | return; 285 | } 286 | match Document::parse_with_options(content.as_str(), ParsingOptions { allow_dtd: true }) { 287 | Ok(xml) => 288 | if let Some(funs) = xml.descendants() 289 | .find(|&n| n.has_tag_name("FUNCTIONS")) { 290 | for fun in funs.children() { 291 | let mut gf = GhidraFun::new(); 292 | if let Some(name) = fun.attribute("NAME") { 293 | gf.name = name.into(); 294 | } else { continue; } 295 | 296 | if let Some(addresses) = fun.children() 297 | .find(|&n| n.has_tag_name("ADDRESS_RANGE")) { 298 | if let Some(val) = addresses.attribute("START") { 299 | gf.start = u32::from_str_radix(val, 16).unwrap_or(0) 300 | } else { continue; } 301 | 302 | if let Some(val) = addresses.attribute("END") { 303 | gf.end = u32::from_str_radix(val, 16).unwrap_or(0) 304 | } else { continue; } 305 | } else { continue; } 306 | 307 | if gf.start != 0 && gf.end != 0 { 308 | self.functions.insert(gf); 309 | } 310 | } 311 | }, 312 | Err(e) => println!("Error loading functions.xml: {}", e) 313 | } 314 | } 315 | } 316 | 317 | pub fn name_for(&self, address: u32) -> Option { 318 | let pc = address.wrapping_sub(self.offset); 319 | let tmp = GhidraFun { start: pc, end: pc, name: String::new() }; 320 | if let Some(closest) = self.functions.range(..=tmp).next_back() { 321 | if (closest.start..=closest.end).contains(&pc) { 322 | return Some(closest.name.to_owned()); 323 | } 324 | } 325 | None 326 | } 327 | } 328 | 329 | impl GhidraFun { 330 | pub fn new() -> GhidraFun { 331 | GhidraFun { start: 0, end: 0, name: String::new() } 332 | } 333 | } 334 | 335 | impl Ord for GhidraFun { 336 | fn cmp(&self, other: &Self) -> Ordering { 337 | self.start.cmp(&other.start) 338 | } 339 | } 340 | 341 | impl PartialOrd for GhidraFun { 342 | fn partial_cmp(&self, other: &Self) -> Option { 343 | Some(self.cmp(other)) 344 | } 345 | } 346 | 347 | impl PartialEq for GhidraFun { 348 | fn eq(&self, other: &Self) -> bool { 349 | self.start == other.start 350 | } 351 | } -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2020 Arkadiusz Guzinski 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | mod cpustep; 18 | mod dump; 19 | mod memdump; 20 | mod utils; 21 | mod cli; 22 | 23 | extern crate serde; 24 | extern crate serde_derive; 25 | #[macro_use] 26 | extern crate serde_big_array; 27 | 28 | use std::{fs}; 29 | use crate::dump::Dump; 30 | use crate::memdump::MemDump; 31 | use crate::utils::{FormatHelper}; 32 | use std::collections::{BTreeMap, HashMap, BTreeSet}; 33 | use core::cmp; 34 | use clap::{ArgMatches}; 35 | 36 | extern crate rustc_serialize; 37 | 38 | fn main() -> std::io::Result<()> { 39 | /* 40 | Logic: mode dir val [dir val]{*} 41 | if !opcode.bin -> transform opcode.log to opcode.bin 42 | */ 43 | let matches = cli::args().get_matches(); 44 | 45 | match matches.subcommand() { 46 | Some(("calls", sub_args)) => show_calls(&sub_args), 47 | Some(("help-fs", _)) => print_help_fs(), 48 | Some(("map-data", sub_args)) => map_data_to_mem(&sub_args), 49 | Some(("memset-diff", sub_args)) => mem_set_diff(&sub_args), 50 | Some(("print-ghidra-search-pattern", sub_args)) => print_ghidra_search_pattern(&sub_args), 51 | Some(("print-mem-commands", sub_args)) => print_mem_commands(&sub_args), // get mem info commands :: dump pc num_before 52 | Some(("registers", sub_args)) => in_out_state(&sub_args), 53 | Some(("search-value", sub_args)) => search_value(&sub_args), // search for value in dump :: dir val [dir val] .. 54 | Some(("stack", sub_args)) => stack(&sub_args), 55 | Some(("starting-pcs", sub_args)) => print_starting_pcs(&sub_args), 56 | Some(("summary", sub_args)) => summary(&sub_args, true), // inspect dir pc pre [highlight str]* 57 | Some(("summary-long", sub_args)) => summary(&sub_args, false), // summary dir pc pre [highlight str]* 58 | _ => println!("Unknown") 59 | } 60 | Ok(()) 61 | } 62 | 63 | fn print_help_fs() { 64 | println!("{}", 65 | "This program expects the data to be inside a directory, following a specific naming scheme\n\ 66 | dir contains:\n\ 67 | opcode.log this is the instruction dump, as generated by the modified FS-UAE.\n\ 68 | opcode.bin is the above, preprocessed to a binary format for faster loading. 69 | it may be necessary to delete after an update of the program or opcode.log\n\ 70 | offset file containing only one hex value that can be subtracted from the program 71 | counter to print the direct address for Ghidra or similar tools.\n\ 72 | mem memory dump in text form\n\ 73 | [0-9,A-F]{8} binary memory dump - the preferred way.. the name is a 8-digit hexadecimal 74 | value, equal to the starting address, e.g. 00000000 or 07000000\n\ 75 | functions.xml Ghidra xml export, containing function information.\n\ 76 | \n\ 77 | offset and functions.xml will be used from parent of dir, if not found\n\ 78 | \n\ 79 | For the memset-diff command, set_dir expects a directory, containing directories with memory\n\ 80 | dumps, all applying to the same range of memory. These directories are named set_id, where 81 | set is the name of the set 82 | id can be anything not containing underscores\n\ 83 | Then the command will print the positions of values that differ between all memory dumps of\n\ 84 | different sets, but are equal within a set." 85 | ) 86 | } 87 | 88 | /* 89 | {} [d|m|i|s|g|p|D|I|S|M|P|t|T|io|IO] parameters\n\ 90 | ... dir is directory containing dump, named opcode.log\n\ 91 | ... pc is the program counter (value displayed above \"Next PC:\") in dump\n\ 92 | ... count is number of instructions before pc\n\n\ 93 | d => search for value (dec) in dump\n\ 94 | $ d dir val [dir val] .. \n\n\ 95 | m => print commands to get memdump for related addresses from fs-uae debugger\n\ 96 | $ m dir pc count\n\n\ 97 | i => print summary of instructions leading to pc (uses linux terminal colors)\n\ 98 | val is value to highlight (format as displayed, pairs of two [0-9,A-Z])\n\ 99 | $ i dir pc count [val]* | less -R \n\n\ 100 | s => compact version of the above\n\n\ 101 | g => generate ghidra instruction pattern search text for code at pc\n\ 102 | $ g dir pc count_after\n\n\ 103 | p => print starting pcs\n\ 104 | $ p dir\n\n\ 105 | M => map data to memory dump - finds locations of files in data_dir in memory dump, ignoring data with < 8 non-zero bytes\n\ 106 | $ M dir data_dir > dataMap.csv\n\n\ 107 | t => print call hierarchy leading to pc\n\ 108 | $ t dir pc\n\n\ 109 | io => print register states at specific pcs\n\ 110 | $ io dir pc_start pc_end\n\n\ 111 | sd => print differences between sets of memory dumps. dir contains directories named set_id\n\ 112 | $ sd dir\n\n\ 113 | D|I|S|P|T => like d|i|s|p|t, but subtract value in dir/offset (one line, hex, no 0x) from pc\n\ 114 | IO => like io, but add offset value to parameters\n\ 115 | Do NOT rely on printed memory content! The values are at the time, the memory dump was made\n\ 116 | and might have changed since then!\n\ 117 | The program preprocesses opcode.log to opcode.bin for faster loading.\n\ 118 | If .log or program version has changed, you might want to delete .bin" 119 | */ 120 | 121 | /// print short version of steps leading to pc 122 | /// 123 | /// short: if true, use one line version without highlighting 124 | fn summary(args: &ArgMatches, short: bool) { 125 | let path = args.value_of("dir").unwrap_or_default(); 126 | let pc = u32::from_str_radix(args.value_of("pc").unwrap(), 16).unwrap(); 127 | let num_before = usize::from_str_radix(args.value_of("count").unwrap(), 10).unwrap(); 128 | let highlight = args.values_of("val").unwrap_or_default(); 129 | 130 | let fmt = if short { 131 | FormatHelper::simple(true) 132 | } else { 133 | FormatHelper::for_values(&highlight, false) 134 | }.finalize(args); 135 | let mem: MemDump = match MemDump::from_dir(path.to_string()) { 136 | Ok(m) => m, 137 | Err(_) => MemDump::new() 138 | }; 139 | Dump::from_dir(path.to_string()).expect("could not load dump") 140 | .inspect(mem, pc, num_before, fmt).expect("summary failed"); 141 | } 142 | 143 | /// print call hierarchy leading to pc 144 | fn stack(args: &ArgMatches) { 145 | let path = args.value_of("dir").unwrap(); 146 | let pc = u32::from_str_radix(args.value_of("pc").unwrap(), 16).unwrap(); 147 | let fmt = FormatHelper::simple(true).finalize(args); 148 | 149 | Dump::from_dir(path.to_string()).expect("could not load dump").stack(pc, fmt) 150 | .expect("failed reading dump "); 151 | } 152 | 153 | /// print complete call hierarchy 154 | fn show_calls(args: &ArgMatches) { 155 | let path = args.value_of("dir").unwrap(); 156 | let fmt = FormatHelper::simple(true).finalize(args); 157 | 158 | Dump::from_dir(path.to_string()).expect("could not load dump").calls(fmt) 159 | .expect("failed reading dump "); 160 | } 161 | 162 | /// search Dumps for a register change to a specific value 163 | /// multiple dumps (with one value each) can be specified, in which case only results that make the 164 | /// change at the same program counter in each dump are printed 165 | fn search_value(args: &ArgMatches) { 166 | // args: &Vec, use_offset: bool) { 167 | let mut dumps: Vec = Vec::new(); 168 | let mut values: Vec = Vec::new(); 169 | let fmt = FormatHelper::simple(true).finalize(args); 170 | // let offset = FormatHelper::get_offset(&args); 171 | let mut dir_val = args.values_of("dir val").unwrap_or_default(); 172 | if dir_val.len() % 2 == 1 { 173 | println!("value missing for dir"); 174 | return; 175 | } 176 | while let Some(path) = dir_val.next() { 177 | let dump_r = Dump::from_dir(path.to_string()); 178 | match dump_r { 179 | Ok(dump) => { dumps.push(dump); } 180 | Err(_) => { println!("ERROR"); } 181 | } 182 | // let dump = Dump::from_dir(path.to_string())?; 183 | // dumps.push(dump); 184 | values.push(u32::from_str_radix(dir_val.next().unwrap_or_default(), 10).unwrap_or_default()); 185 | } 186 | let mut i = 0; 187 | let mut results: Option> = None; 188 | let mut size: u8 = 1; 189 | for val in &values { 190 | size = cmp::max(size, match val { 191 | 0..=0xFF => 1, 192 | 0x100..=0xFF00 => 2, 193 | _ => 4 194 | }); 195 | } 196 | 197 | for dump in dumps { 198 | results = Some(dump.search_for_register_change(*values.get(i).unwrap(), size, results)); 199 | i += 1; 200 | } 201 | for (k, v) in results.unwrap_or_default() { 202 | println!("{}{}", fmt.pc(k), v); // TODO use FormatHelper 203 | } 204 | } 205 | 206 | fn map_data_to_mem(args: &ArgMatches) { 207 | let dump_dir = args.value_of("dir").unwrap(); 208 | let data_dir = args.value_of("data-dir").unwrap(); 209 | 210 | let offset = FormatHelper::get_offset(&args); 211 | let md = MemDump::from_dir(dump_dir.to_string()).expect("could not load memory"); 212 | md.map_data(data_dir.to_string(), offset).unwrap(); 213 | } 214 | 215 | fn in_out_state(args: &ArgMatches) { 216 | let path = args.value_of("dir").unwrap(); 217 | let dump = Dump::from_dir(path.to_string()).expect("could not load dump"); 218 | let offset = FormatHelper::get_offset(args); 219 | // TODO use FormatHelper 220 | let start = u32::from_str_radix(args.value_of("pc_start").unwrap(), 16) 221 | .expect("could not parse start") + offset; 222 | let end = u32::from_str_radix(args.value_of("pc_end").unwrap(), 16) 223 | .expect("could not parse end") + offset; 224 | dump.in_out_state(start, end); 225 | } 226 | 227 | fn print_mem_commands(args: &ArgMatches) { 228 | Dump::from_dir(args.value_of("dir").unwrap_or_default().to_string()) 229 | .expect("failed to load dump") 230 | .dump_memlist_cmds(u32::from_str_radix(args.value_of("pc") 231 | .unwrap_or_default(), 16).expect("invalid value for pc"), 232 | usize::from_str_radix(args.value_of("count").unwrap_or_default(), 10) 233 | .expect("invalid value for count")) 234 | .expect("meh!") 235 | } 236 | 237 | /// check sets of memory dumps for bytes that differ between sets, but not inside them 238 | fn mem_set_diff(args: &ArgMatches) { // TODO improve error messages 239 | let entries = fs::read_dir(args.value_of("set_dir").unwrap()) 240 | .expect("could not open dir"); 241 | let mut memdump_map: HashMap> = HashMap::new(); 242 | let offset = FormatHelper::get_offset(args); 243 | 244 | // load memdumps and group them by the part of filename before '_' 245 | for entry in entries { 246 | let entry = entry.expect("something wrong with entry"); 247 | let path = entry.path(); 248 | let file_name = entry.file_name(); 249 | let name_parts: Vec<&str> = file_name.to_str().unwrap_or_default().split('_').collect(); 250 | 251 | if name_parts.len() == 2 { 252 | let key = name_parts[0]; 253 | let mem = MemDump::from_dir(path.to_str().expect("something wrong with path").to_string()).expect("could not load mem dump"); 254 | let val = memdump_map.get_mut(key); 255 | match val { 256 | Some(e) => { 257 | e.push(mem); 258 | } 259 | None => { 260 | let mut vec: Vec = Vec::new(); 261 | vec.push(mem); 262 | memdump_map.insert(key.to_owned(), vec); 263 | } 264 | } 265 | } 266 | } 267 | 268 | // no need to have a map anymore - transfer to a Vec 269 | let mut memdump_vec: Vec> = Vec::new(); 270 | for (_, val) in memdump_map.drain() { 271 | memdump_vec.push(val); 272 | } 273 | 274 | // look up offsets that are different between each set 275 | // only the first memdump per set is checked, as the interesting parts are identical in each 276 | // memdump of a set and the false offsets will be filtered out later 277 | let mut results: Option> = None; // we use a sorted set, to get a sorted output 278 | for i in 0..memdump_vec.len() - 1 { 279 | // the first diff will check all memory, while subsequent diffs only need to check the 280 | // offsets in results 281 | for j in i + 1..memdump_vec.len() { 282 | results = Some(memdump_vec[i][0].diff_only(&memdump_vec[j][0], results, false)); 283 | } 284 | } 285 | 286 | // filter out bytes that change inside a set 287 | for vec in memdump_vec { 288 | for i in 0..vec.len() - 1 { 289 | for j in i + 1..vec.len() { 290 | results = Some(vec[i].diff_only(&vec[j], results, true)); 291 | } 292 | } 293 | } 294 | 295 | // output 296 | if offset == 0 { 297 | for r in results.expect("No Result") { 298 | println!("{:08X}", r); 299 | } 300 | } else { 301 | for r in results.expect("No Result") { 302 | println!("{:08X} {:08X}", r.wrapping_sub(offset), r); 303 | } 304 | } 305 | } 306 | 307 | fn print_ghidra_search_pattern(args: &ArgMatches) { 308 | let path = args.value_of("dir").unwrap(); 309 | let pc = u32::from_str_radix(args.value_of("pc").unwrap(), 16).unwrap(); 310 | let num_after = usize::from_str_radix( 311 | args.value_of("count").unwrap_or("30"), 10).unwrap(); 312 | Dump::from_dir(path.to_string()).expect("could not load dump") 313 | .ghidra_search(pc, num_after).expect("generating search pattern failed"); 314 | } 315 | 316 | fn print_starting_pcs(args: &ArgMatches) { 317 | let path = args.value_of("dir").unwrap(); 318 | Dump::from_dir(path.to_string()).expect("could not load dump") 319 | .starting_pcs(0); // TODO use FormatHelper 320 | } -------------------------------------------------------------------------------- /src/cpustep.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2020 Arkadiusz Guzinski 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | use std::fs::File; 18 | use std::io::{self, BufRead}; 19 | use serde::{Serialize, Deserialize}; 20 | use crate::utils::*; 21 | use crate::memdump::MemDump; 22 | 23 | // use BigArray, as this is needed to allow serde to handle arrays beyond 32 elements 24 | big_array! { BigArray; } 25 | #[derive(Serialize, Deserialize)] 26 | pub struct CpuStep { 27 | /// an instruction step, containing the info about register state from fs-uae. note is the 28 | /// instruction as disassembled by fs-uae. 29 | pub data: [u32; 8], // data registers D0-D7 30 | pub address: [u32; 8], // address registers A0-A7 (A7 is the current stack pointer) 31 | pub usp: u32, // user stack pointer 32 | pub isp: u32, // interrupt stack pointer 33 | pub sfc: u32, // source function code register - only 68010+ 34 | pub dfc: u32, // destination function code register - only 68010+ 35 | pub cacr: u32, // cache control register - only 68020+ 36 | pub vbr: u32, // vector base register - only 68010+ 37 | pub caar: u32, // cache address register - only 68020/30 38 | pub msp: u32, // master stack pointer register - only 68020+ 39 | pub t: u8, // trace enable (actually 2 bits) 40 | pub s: bool, // supervisor/user state (switch active stack 0=user, 1=interrupt/master) 41 | pub m: bool, // master/interrupt state (switch active stack 0=interrupt, 1=master) 42 | pub x: bool, // extend 43 | pub n: bool, // negative 44 | pub z: bool, // zero 45 | pub v: bool, // overflow 46 | pub c: bool, // carry 47 | pub imask: u8, // interrupt mask (actually 3 bits) 48 | pub stp: bool, 49 | pub pc: u32, 50 | pub pc_note: [u8; 24], 51 | #[serde(with = "BigArray")] 52 | pub note: [u8; 64], 53 | // 62 54 | pub pc_next: u32, 55 | } 56 | 57 | impl CpuStep { 58 | /// helper function to read a line from the dump, trying to skip output, that is not part of the 59 | /// data we are looking for. 60 | /// 61 | /// lines: BufReader with position at the beginning of the next line 62 | /// start_with: expected condition. If the line does not start with this String, skip lines 63 | /// until we find one that does. 64 | fn read_line(lines: &mut io::BufReader, start_with: &str) -> Result { 65 | loop { 66 | let mut line = String::new(); 67 | lines.read_line(&mut line).unwrap(); // potential crash acceptable... TODO better... 68 | if line.len() == 0 { 69 | return Err(0); 70 | } 71 | if line.starts_with(start_with) { 72 | return Ok(line); 73 | } 74 | } 75 | } 76 | 77 | /// helper function to parse registers (D0-D7 or A0-A7) into an array 78 | /// 79 | /// arr: array to write into 80 | /// line1 first line (containing D0-D3 or A0-A3) 81 | /// line2 second line (containing D4-D7 or A4-A7) 82 | fn set_registers(arr: &mut [u32; 8], line1: &str, line2: &str) { 83 | // assert_eq!(len(line), 56); 84 | let line = line1.get(0..line1.len() - 1).unwrap().to_owned() + line2; 85 | let mut offset = 0; 86 | for i in arr { 87 | let val = line.get(offset + 5..=offset + 12).unwrap_or_default(); 88 | *i = u32::from_str_radix(val, 16).unwrap_or_default(); 89 | offset += 14; 90 | } 91 | } 92 | 93 | /// reads one instruction step and the register contents from the dump 94 | /// 95 | /// lines: BufReader with position at the beginning of the instruction step 96 | pub fn from_dump(lines: &mut io::BufReader) -> Result { 97 | let mut d: [u32; 8] = Default::default(); 98 | let mut a: [u32; 8] = Default::default(); 99 | // CpuStep::set_registers(&mut d, line_data1, line_data2); 100 | CpuStep::set_registers(&mut d, 101 | CpuStep::read_line(lines, " D0 ")?.as_str(), 102 | CpuStep::read_line(lines, " D4 ")?.as_str()); 103 | CpuStep::set_registers(&mut a, 104 | CpuStep::read_line(lines, " A0 ")?.as_str(), 105 | CpuStep::read_line(lines, " A4 ")?.as_str()); 106 | let l5s = CpuStep::read_line(lines, "USP ")?; 107 | let line5 = l5s.as_str(); 108 | let l6s = CpuStep::read_line(lines, "CACR ")?; 109 | let line6 = l6s.as_str(); 110 | let lb = CpuStep::read_line(lines, "T=")?; 111 | let line_bits = lb.as_str(); 112 | let lp = CpuStep::read_line(lines, "")?; 113 | let line_pc = lp.as_str(); 114 | let lpn = CpuStep::read_line(lines, "Next PC")?; 115 | let line_next_pc = lpn.as_str(); 116 | 117 | let pc_note = line_pc.get(9..=32).unwrap_or_default().as_bytes(); 118 | let note = line_pc.get(34..line_pc.len()).unwrap_or_default().as_bytes(); 119 | 120 | let step = CpuStep { 121 | data: d, 122 | address: a, 123 | usp: u32::from_str_radix(line5.get(5..=12).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 124 | isp: u32::from_str_radix(line5.get(19..=26).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 125 | sfc: u32::from_str_radix(line5.get(33..=40).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 126 | dfc: u32::from_str_radix(line5.get(47..=54).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 127 | cacr: u32::from_str_radix(line6.get(5..=12).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 128 | vbr: u32::from_str_radix(line6.get(19..=26).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 129 | caar: u32::from_str_radix(line6.get(33..=40).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 130 | msp: u32::from_str_radix(line6.get(47..=54).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 131 | t: u8::from_str_radix(line_bits.get(2..=3).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 132 | s: line_bits.get(7..=7).unwrap_or("0") == "1", 133 | m: line_bits.get(11..=11).unwrap_or("0") == "1", 134 | x: line_bits.get(15..=15).unwrap_or("0") == "1", 135 | n: line_bits.get(19..=19).unwrap_or("0") == "1", 136 | z: line_bits.get(23..=23).unwrap_or("0") == "1", 137 | v: line_bits.get(27..=27).unwrap_or("0") == "1", 138 | c: line_bits.get(31..=31).unwrap_or("0") == "1", 139 | imask: u8::from_str_radix(line_bits.get(39..=39).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 140 | stp: line_bits.get(45..=45).unwrap_or("0") == "1", 141 | pc: u32::from_str_radix(line_pc.get(0..=7).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 142 | pc_note: array_init::array_init({ 143 | |i| if i < pc_note.len() { pc_note[i] } else { 0x20 } 144 | }), 145 | note: array_init::array_init({ 146 | |i| if i < note.len() - 1 { note[i] } else { 0x20 } 147 | }), 148 | pc_next: u32::from_str_radix(line_next_pc.get(9..=16).unwrap_or("0").as_ref(), 16).unwrap_or_default(), 149 | }; 150 | 151 | Ok(step) 152 | } 153 | /// returns u8 with bits signifying which data registers have changed their value to val 154 | /// 155 | /// prev: instruction to compare with 156 | /// val: value, we're looking for 157 | /// mask: bit mask for value (e.g. if we're only interested it 16 bit values) 158 | pub fn register_changed_to(&self, prev: &CpuStep, val: u32, mask: u32) -> u8 { 159 | let mut result: u8 = 0; 160 | let mut b: u8 = 1; 161 | for i in 0..=7 { 162 | if self.data[i] & mask == val && prev.data[i] & mask != val { 163 | result |= b; 164 | } 165 | // Multiplication with intended (well, here: don't care) overflow. 166 | // Otherwise, Rust will panic in debug mode (not in release) 167 | b = b.wrapping_mul(2); 168 | } 169 | result 170 | } 171 | 172 | /// returns change in call depth by this instruction 173 | pub fn depth_mod(&self) -> i16 { 174 | // ignore changes from interrupts 175 | if self.imask != 0 { 176 | return 0; 177 | } 178 | /* 179 | +1 BSR, JSR 180 | -1 RTS, RTE (RTR is called RTE in log - probably only used to return from interrupt) 181 | */ 182 | match self.note.get(0..3).unwrap_or_default() { 183 | [66, 83, 82] | [74, 83, 82] => 1, 184 | [82, 84, 83] | [82, 84, 69] => -1, 185 | _ => 0 186 | } 187 | } 188 | 189 | // pub fn depth_mod_with_interrupt(&self) -> i16 {} 190 | /// print String showing PCs at call depth change 191 | /// 192 | /// other: instruction steps to compare with 193 | /// fmt: formatting configuration 194 | /// depth: current call depth. Used for padding and modified on change. 195 | pub fn call_diff(&self, predecessor: &CpuStep, fmt: &FormatHelper, depth: &mut i16) { 196 | let mut depth_m = predecessor.depth_mod(); 197 | *depth += depth_m; 198 | if self.s && !predecessor.s { 199 | depth_m += 1; 200 | match fmt.show_interrupt { 201 | Visibility::Hidden => { return; } 202 | Visibility::Brief => { 203 | println!("{}Interrupt (mask={})", fmt.padding(*depth), self.imask); 204 | return; 205 | } 206 | Visibility::Verbose => {} 207 | } 208 | } 209 | if depth_m <= 0 { 210 | return; 211 | } 212 | println!("{}{} from {:08X}", fmt.padding(*depth), fmt.pc(self.pc), 213 | fmt.with_offset(predecessor.pc)); 214 | // std::str::from_utf8(&self.note).unwrap_or_default()).as_str(); 215 | } 216 | 217 | /// Generate String showing the difference between 2 instruction steps 218 | /// 219 | /// other: instruction steps to compare with 220 | /// mem: Memory dump (for printing possible content, an address register is pointing at) 221 | /// fmt: formatting configuration 222 | /// num: number of steps until end pc is reached. Only printed at depth change. 223 | /// depth: current call depth. Used for padding and modified on change. 224 | pub fn pretty_diff(&self, other: &CpuStep, mem: &MemDump, fmt: &FormatHelper, num: usize, depth: &mut i16) -> String { 225 | let mut s = String::new(); 226 | let pad: usize = if *depth >= 0 { (*depth * fmt.indent) as usize } else { 0 }; 227 | // let pad_inline = if compact {0i16} else { pad }; 228 | let padding = format!("{:>width$}", "", width = pad); 229 | let mut delimiter = String::new(); 230 | if fmt.compact { delimiter += " " } else { 231 | let nl = format!("\n{}", &padding); 232 | delimiter += nl.as_str(); 233 | }; 234 | 235 | // check data registers 236 | let mut print_spacing = false; 237 | for i in 0..=7 { 238 | if self.data[i] != other.data[i] { 239 | print_spacing = true; 240 | s += format!("D{} {}->{} ", i, 241 | fmt.col_reg(other.data[i]).as_str(), 242 | fmt.col_reg(self.data[i]).as_str() 243 | ).as_str(); 244 | } 245 | } 246 | if print_spacing { 247 | s += delimiter.as_str(); 248 | } 249 | // address registers are only parsed for certain instructions 250 | let note = std::str::from_utf8(&self.note).unwrap_or_default(); 251 | let print_memory = 252 | match note.get(0..0).unwrap_or_default() { 253 | "A" | "D" | "O" => true, 254 | _ => { 255 | match note.get(0..=1).unwrap_or_default() { 256 | "LS" | "RO" => true, 257 | _ => { 258 | match note.get(0..=2).unwrap_or_default() { 259 | "CMP" | "EOR" | "MUL" | "NEG" | "NOT" | "SBC" | "SUB" => true, 260 | _ => false 261 | } 262 | } 263 | } 264 | } 265 | }; 266 | if print_memory { // TODO does not always work correctly 267 | print_spacing = false; 268 | for i in 2..self.note.len() - 1 { 269 | let x = self.note.get(i..=i + 1).unwrap(); 270 | match x { 271 | [65, 48..=57] => { 272 | print_spacing = true; 273 | let idx = (x[1] - 48) as usize; 274 | let addr = self.address[idx]; 275 | s += format!("A{}: {} ", idx, fmt.col(mem.get_mem_at(addr, 4))).as_str(); 276 | } 277 | _ => {} 278 | } 279 | } 280 | if print_spacing { 281 | s += delimiter.as_str(); 282 | } 283 | } 284 | let depth_m = self.depth_mod(); 285 | if depth_m > 0 || other.depth_mod() < 0 { 286 | s += format!("\n{}##-{:<5}", padding, num).as_str(); 287 | } 288 | *depth += depth_m; 289 | if fmt.compact { 290 | s += format!("\n{}{:08X} {}", padding, fmt.with_offset(self.pc), 291 | std::str::from_utf8(&self.note).unwrap_or_default()).as_str(); 292 | } else { 293 | s += format!("\n{}\x1b[1m{:08X}\x1b[0m {}{}", padding, fmt.with_offset(self.pc), 294 | std::str::from_utf8(&self.note).unwrap_or_default(), delimiter).as_str() 295 | } 296 | s 297 | } 298 | 299 | /// print instruction in format, suitable for ghidra's instruction search feature 300 | pub fn print_for_search(&self, prev: &CpuStep) -> Result { 301 | let mut diff = (prev.pc_next - self.pc) as i32; 302 | return if diff == 0 { 303 | Ok(std::str::from_utf8(&self.pc_note).unwrap_or_default().trim_end().to_string()) 304 | } else if diff < 0 { 305 | Err("Negative step not implemented") 306 | } else if diff > 80 { 307 | Err("Big step -- aborting now") 308 | } else { 309 | let mut s = String::new(); 310 | while diff > 0 { 311 | s += "[........] "; 312 | diff -= 1; 313 | } 314 | Ok(s.trim_end().to_string()) 315 | }; 316 | } 317 | } 318 | 319 | 320 | impl ToString for CpuStep { 321 | /// output as from fs-uae 322 | fn to_string(&self) -> String { 323 | format!(" D0 {:08x} D1 {:08x} D2 {:08x} D3 {:08x}\ 324 | \n D4 {:08x} D5 {:08x} D6 {:08x} D7 {:08x}\ 325 | \n A0 {:08x} A1 {:08x} A2 {:08x} A3 {:08x}\ 326 | \n A4 {:08x} A5 {:08x} A6 {:08x} A7 {:08x}\n\ 327 | USP {:08x} ISP {:08x} SFC {:08x} DFC {:08x}\n\ 328 | CACR {:08x} VBR {:08x} CAAR {:08x} MSP {:08x}\n\ 329 | T={:02x} S={} M={} X={} N={} Z={} V={} C={} IMASK={} STP={}\n\ 330 | {:08x} {:>24} {}\n\ 331 | Next PC: {:08x}\ 332 | ", 333 | self.data[0], self.data[1], self.data[2], self.data[3], 334 | self.data[4], self.data[5], self.data[6], self.data[7], 335 | self.address[0], self.address[1], self.address[2], self.address[3], 336 | self.address[4], self.address[5], self.address[6], self.address[7], 337 | self.usp, self.isp, self.sfc, self.dfc, 338 | self.cacr, self.vbr, self.caar, self.msp, 339 | self.t, self.s as u8, self.m as u8, self.x as u8, self.n as u8, self.z as u8, 340 | self.v as u8, self.c as u8, self.imask as u8, self.stp as u8, 341 | self.pc, std::str::from_utf8(&self.pc_note).unwrap_or_default(), 342 | std::str::from_utf8(&self.note).unwrap_or_default(), 343 | self.pc_next) 344 | } 345 | } 346 | -------------------------------------------------------------------------------- /src/dump.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2020 Arkadiusz Guzinski 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | use crate::cpustep::CpuStep; 18 | use std::collections::{HashMap, BTreeMap, BTreeSet}; 19 | use std::fs::File; 20 | use std::io::{BufReader, BufWriter}; 21 | use serde::{Serialize, Deserialize}; 22 | use std; 23 | use crate::memdump::MemDump; 24 | use crate::utils::FormatHelper; 25 | use std::cmp::min; 26 | 27 | #[derive(Serialize, Deserialize)] 28 | /// represents an uae instruction dump 29 | pub struct Dump { 30 | // name: str, 31 | /// map of program counters, that are only found once in the dump. These are likely what the 32 | /// user is searching for. The second value is the number of consecutive pcs, starting with the 33 | /// first value. 34 | singles: HashMap, 35 | // PC -> Offset 36 | /// the individual instructions and their register contents 37 | steps: Vec, 38 | } 39 | 40 | impl Dump { 41 | /// loads the Dump from the directory, specified by path. Reads a cache file named opcode.bin, or 42 | /// creates it from opcode.log 43 | pub fn from_dir(path: String) -> std::io::Result { 44 | // let name = 45 | let file_res = File::open(path.to_owned() + "/opcode.bin"); 46 | match file_res { 47 | Ok(file) => { 48 | let buf_reader = BufReader::new(file); 49 | let dump: Dump = bincode::deserialize_from(buf_reader).expect("Reading failed"); 50 | Ok(dump) 51 | } 52 | Err(_) => { 53 | let file = File::open(path.to_owned() + "/opcode.log")?; 54 | let mut buf_reader = BufReader::new(file); 55 | 56 | let mut pcs: HashMap = HashMap::new(); // pc, (count, index) 57 | let mut singles_all: BTreeMap = BTreeMap::new(); 58 | let mut singles: HashMap = HashMap::new(); 59 | let mut steps: Vec = Vec::new(); 60 | let mut i = 0; 61 | loop { 62 | let step_res = CpuStep::from_dump(&mut buf_reader); 63 | match step_res { 64 | Ok(step) => { 65 | let pc = step.pc; // get Program counter 66 | // get entry for pc (or a new one with count = 0) 67 | /* this should work - why does is not? 68 | let mut e = *pcs.entry(pc).or_insert((0, i)); 69 | e.0 += 1; 70 | so instead, the longer version: 71 | */ 72 | if pcs.contains_key(&pc) { 73 | let e = pcs[&pc]; 74 | pcs.insert(pc, (e.0 + 1, e.1)); 75 | } else { 76 | pcs.insert(pc, (1, i)); 77 | } 78 | 79 | steps.push(step); 80 | i += 1; 81 | } 82 | Err(_) => break 83 | } 84 | } 85 | // get only pcs with count of 1 - in a BTreeMap because we need them sorted 86 | for (pc, (c, idx)) in pcs.drain() { 87 | if c == 1 { 88 | singles_all.insert(pc, idx); 89 | } 90 | } 91 | 92 | let mut iter = singles_all.iter(); 93 | let first = iter.next().unwrap(); 94 | let mut pc_last: u32 = *first.0; 95 | let mut pc_new: u32; 96 | singles.insert(pc_last, *first.1); 97 | for (pc, idx) in iter { 98 | pc_new = *pc; 99 | // if pc_new > pc_last + 10 { 100 | if pc_new != steps.get(singles_all[&pc_last]).unwrap().pc_next { 101 | singles.insert(*pc, *idx); 102 | // println!("({:x}, {})", pc, idx); 103 | } 104 | pc_last = pc_new; 105 | } 106 | 107 | let dump = Dump { singles, steps }; 108 | let out = File::create(path.to_owned() + "/opcode.bin")?; 109 | let mut out_buf = BufWriter::new(out); 110 | bincode::serialize_into(&mut out_buf, &dump).unwrap(); 111 | Ok(dump) 112 | } 113 | } 114 | } 115 | 116 | /// Searches individual dumped instruction for a data change to value val. 117 | /// 118 | /// If previous is not None, the result will only contain changes that were present at pcs in 119 | /// previous, as well as those found in this self. 120 | /// The function does not search the whole dump, but instead searches beginning from each key 121 | /// of self.singles and stops when reaching a lower call depth then it started with 122 | /// 123 | /// val: value to search for 124 | /// size: expected size of value in bytes (1, 2, anything else will search 4 bytes) 125 | /// previous: should be result of the last call to this function 126 | /// 127 | /// returns: Sorted Map of pc to String describing register changes 128 | pub fn search_for_register_change(&self, val: u32, size: u8, previous: Option>) 129 | -> BTreeMap { 130 | let mask: u32 = match size { 131 | 1 => 0x000000FF, 132 | 2 => 0x0000FFFF, 133 | _ => 0xFFFFFFFF 134 | }; 135 | 136 | let mut found: BTreeMap = BTreeMap::new(); 137 | for cs in self.singles.values() { 138 | found.extend(self.search_for_register_change_from(*cs, val, mask)); 139 | } 140 | 141 | match previous { 142 | None => found, 143 | Some(found_earlier) => { 144 | let mut result: BTreeMap = BTreeMap::new(); 145 | for key in found_earlier.keys() { 146 | if found.contains_key(key) { 147 | let i = *key; 148 | result.insert(i, found_earlier[&i].to_string() + found[&i].as_str()); 149 | } 150 | } 151 | result 152 | } 153 | } 154 | } 155 | 156 | /// Finds register changes to value val 157 | /// 158 | /// start: start at steps[start] 159 | /// val: value to look for 160 | /// mask: bitmask for value (all saved values are 32 bit) 161 | /// 162 | /// returns: Map of pc, description of change (e.g. ", D0: 15 -> 14") 163 | fn search_for_register_change_from(&self, start: usize, val: u32, mask: u32) 164 | -> BTreeMap { 165 | // maximum of instructions to search 166 | let mut to_go = 10000; 167 | let mut index = start; 168 | // we track depth, so we can return when reaching the function, that called the one at start 169 | let mut depth: i16 = 0; 170 | let mut last: &CpuStep = self.steps.get(index).unwrap(); 171 | let mut found: BTreeMap = BTreeMap::new(); 172 | loop { 173 | index += 1; 174 | match self.steps.get(index + 1) { 175 | Some(current) => { 176 | // println!("{}", current.to_string()); 177 | let mut res = current.register_changed_to(last, val, mask); 178 | let mut idx = 0; 179 | if res != 0 { 180 | let mut s = String::new(); 181 | while res != 0 { 182 | if res & 1 == 1 { 183 | s += format!(", @{} D{}: {:x} -> {:x} ", index, idx, 184 | last.data[idx], current.data[idx]).as_str(); 185 | } 186 | res /= 2; 187 | idx += 1; 188 | // println!("{}", current.to_string()); 189 | } 190 | found.insert(current.pc, s); 191 | } 192 | last = current; 193 | to_go -= 1; 194 | depth = depth + current.depth_mod(); 195 | if depth < 0 || to_go <= 0 { 196 | break; 197 | } 198 | } 199 | None => break 200 | } 201 | } 202 | found 203 | } 204 | 205 | /// finds first index of pc in self.steps 206 | fn first_index_of_pc(&self, pc: u32) -> Result { 207 | for idx in 0..self.steps.len() { 208 | if self.steps[idx].pc == pc { 209 | return Ok(idx); 210 | } 211 | } 212 | Err("PC not found") 213 | } 214 | 215 | /// tries to create commands, to get memdumps from uae's debug mode, containing all memory at 216 | /// the addresses that were in address registers at some time (plus some padding for context). 217 | /// So far, only works for memory directly in address registers, not for directly specified or 218 | /// accessed with offset 219 | pub fn dump_memlist_cmds(&self, pc: u32, num_before: usize) -> Result<(), &str> { 220 | // find addresses 221 | let inclusive: u32 = 128; 222 | let mut addresses: BTreeSet = BTreeSet::new(); 223 | let end = self.first_index_of_pc(pc)?; 224 | let start = if end > num_before { end - num_before } else { 0 }; 225 | for idx in start..=end { 226 | let address = self.steps.get(idx).unwrap().address; 227 | for i in 0..8 { 228 | addresses.insert(address[i]); 229 | } 230 | } 231 | 232 | // create ranges, containing those addresses 233 | let mut iter = addresses.iter(); 234 | let mut first = *iter.next().unwrap(); 235 | let mut last = first; 236 | let mut new: u32; 237 | for a in iter { 238 | new = *a; 239 | if new > last + inclusive { 240 | Dump::print_m_range(first, last); 241 | first = new; 242 | } 243 | last = new; 244 | } 245 | Ok(()) 246 | } 247 | 248 | /// prints command for dump_memlist_cmds 249 | fn print_m_range(from: u32, to: u32) { 250 | let start = from & 0xffffff80; 251 | let end = (to + 0x100) & 0xffffff80; 252 | let lines = (end - start) / 16; 253 | println!("m {:08x} {}", start, lines); 254 | } 255 | 256 | /// prints a summary of instructions and data changes, leading to pc 257 | /// 258 | /// mem: MemDump, that can (partially) resolve references in address registers (can be empty) 259 | /// pc: program counter at which to start (first occurrence in dump will be used) 260 | /// num_before: print a maximum of num_before instructions prior to pc 261 | /// fmt: contains formatting options 262 | pub fn inspect(&self, mem: MemDump, pc: u32, num_before: usize, fmt: FormatHelper) -> Result<(), &str> { 263 | // general preparation 264 | let end = self.first_index_of_pc(pc)?; 265 | let start = if end > num_before { end - num_before } else { 0 } + 1; 266 | let mut current = self.steps.get(start).expect("cpu step not found"); 267 | // get base depth 268 | let mut depth: i16 = 0; 269 | let mut min_depth: i16 = 0; 270 | for i in start..=end { 271 | depth += self.steps.get(i).expect("cpu step not found").depth_mod(); 272 | min_depth = min(min_depth, depth); 273 | } 274 | depth = 0 - min_depth; 275 | for i in start..=end { 276 | let last = current; 277 | current = self.steps.get(i).expect("cpu step not found"); 278 | print!("{}", current.pretty_diff(&last, &mem, &fmt, end - i, &mut depth)); 279 | } 280 | Ok(()) 281 | } 282 | 283 | /// print a string that can be pasted into ghidra's instruction search (hex mode) 284 | /// 285 | /// pc: instruction to start at 286 | /// num_after: include this many following instructions 287 | pub fn ghidra_search(&self, pc: u32, num_after: usize) -> Result<(), &str> { 288 | let start = self.first_index_of_pc(pc)?; 289 | let end = start + num_after; 290 | let mut current = self.steps.get(start).expect("cpu step not found"); 291 | 292 | for i in start..=end { 293 | let last = current; 294 | current = self.steps.get(i).expect("cpu step not found"); 295 | match current.print_for_search(&last) { 296 | Ok(s) => println!("{}", s), 297 | Err(e) => { 298 | println!("{}", e); 299 | return Ok(()); 300 | } 301 | } 302 | } 303 | Ok(()) 304 | } 305 | 306 | /// print call hierarchy, leading to pc 307 | /// 308 | /// pc: program counter at the bottom of the hierarchy (first occurrence in dump will be used) 309 | /// fmt: contains formatting options 310 | pub fn stack(&self, pc: u32, fmt: FormatHelper) -> Result<(), &str> { 311 | let mut idx = self.first_index_of_pc(pc)?; 312 | let mut depth: i16 = 0; 313 | let mut min_depth: i16 = 0; 314 | let mut current = self.steps.get(idx).expect("cpu step not found"); 315 | let mut lines: Vec = Vec::new(); 316 | lines.push(format!("{:08X} {}", current.pc - fmt.offset_mod, 317 | std::str::from_utf8(¤t.note).unwrap_or_default())); 318 | 319 | loop { 320 | let last = current; 321 | current = self.steps.get(idx).expect("cpu step not found"); 322 | depth -= current.depth_mod(); 323 | if depth < min_depth { 324 | lines.push(format!("{:08X} {}", last.pc - fmt.offset_mod, 325 | std::str::from_utf8(&last.note).unwrap_or_default())); 326 | min_depth = depth; 327 | } 328 | if idx == 0 { 329 | break; 330 | } 331 | idx -= 1; 332 | } 333 | 334 | for line in lines.iter().rev() { 335 | println!("{}", line); 336 | } 337 | Ok(()) 338 | } 339 | 340 | /// print full call tree 341 | /// 342 | /// fmt: contains formatting options 343 | pub fn calls(&self, fmt: FormatHelper) -> Result<(), &str> { 344 | // general preparation 345 | let mut current = self.steps.first().expect("cpu step not found"); 346 | // get base depth 347 | let mut depth: i16 = 0; 348 | let mut min_depth: i16 = 0; 349 | for i in 0..self.steps.len() { 350 | depth += self.steps.get(i).expect("cpu step not found").depth_mod(); 351 | min_depth = min(min_depth, depth); 352 | } 353 | depth = 0 - min_depth; 354 | 355 | // do output 356 | for i in 1..self.steps.len() { 357 | let last = current; 358 | current = self.steps.get(i).expect("cpu step not found"); 359 | // println!("{:08X} {}", last.pc - fmt.offset_mod, 360 | // std::str::from_utf8(&last.note).unwrap_or_default())); 361 | current.call_diff(&last, &fmt, &mut depth); 362 | } 363 | Ok(()) 364 | } 365 | 366 | /// print starting points found in dump 367 | pub fn starting_pcs(&self, offset: u32) { 368 | for pc in self.singles.keys() { 369 | println!("{:08X}", *pc - offset); 370 | } 371 | } 372 | pub fn in_out_state(&self, start: u32, end: u32) { 373 | for cpu_step in self.steps.iter() { 374 | if cpu_step.pc == start { 375 | println!("\n{}", cpu_step.to_string()); 376 | } else if cpu_step.pc == end { 377 | println!("{}\n#####################################################", cpu_step.to_string()); 378 | } 379 | } 380 | } 381 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **fs-uae-dump-analyzer** 2 | or: 3 | # An approach to reverse engineering for old amiga games... # 4 | 5 | This repository contains code I wrote to help me find out how some internals of Ambermoon work, as well as this guide on the approach I used, in order to help with this project: https://github.com/Pyrdacor/Ambermoon.net 6 | 7 | Note that I did all this on Linux so, while all the important tools should run on Windows and MacOS as well, you might need to improvise on occasion. 8 | 9 | ##### What you need: ##### 10 | 11 | * **FS-UAE**, as well as it's **source code** (https://fs-uae.net/download#linux) and whatever is needed to 12 | build it. 13 | * **Ghidra** (https://ghidra-sre.org) 14 | * the Amiga hunks loader plugin for ghidra (https://github.com/lab313ru/ghidra_amiga_ldr) 15 | * Some **basic knowledge of Assembler** (not necessarily MK68 - I just had some experience with 8085 and MIPS when I started this) and **C** 16 | * The M68K CPU Programmers Reference Manual (https://www.nxp.com/docs/en/reference-manual/M68000PRM.pdf). I also recommend MarkeyJester’s Motorola 68000 Beginner’s Tutorial (http://mrjester.hapisan.com/04_MC68/), which is less detailed, but much easier to understand. 17 | * The **rust** compiler and cargo (it's build manager) (https://www.rust-lang.org) to build the dump-analyzer. 18 | * The **unencrypted and uncompressed** executable file(s) of the Game you want to reverse engineer. If you can open the file in a hex editor and find readable strings beyond the first few hundred bytes, it's a good sign and you can continue. Otherwise you might need to use Ghidra to find out how to do that first. Maybe someone has already done it and you can find the clear version on the internet (as was the case for Ambermoon). 19 | 20 | ##### Optional (for the less important scripts): ##### 21 | 22 | * python 23 | * qalc 24 | * WSL (on windows) 25 | 26 | 27 | ##### Contents of this repository ##### 28 | 29 | * src/ Source for the dump-analyzer 30 | * patch/ patch to make FS-UAE dump info on each cpu instruction 31 | * scripts/ some optional helper scripts (or examples for scripts..) 32 | 33 | 34 | ## Introduction: The What and Why? ## 35 | * FS-UAE is the program I use to run those great Games from the 90s today. It offers the possibility to save and load snapshots of the current memory state, as well as a debug mode. Both are essential to the whole approach. 36 | * Ghidra is a suite of Software reverse engineering tools, developed by the NSA and released as open source in 2019. With the Amiga hunks plugin it is able to disassemble and analyze an amiga executable. It has a lot of useful features to help understand how that executable works. 37 | 38 | The approach presented here, uses a slightly modified version of FS-UAE to create a dump of CPU-instruction and the associated data register changes during a specific timeframe. This is then used to find the instructions for a specific functionality, known to be executed during that timeframe, and then use Ghidra to analyze it further (along with the normal FS-UAE's debug mode). 39 | 40 | Rust is used to compile a tool for analyzing the instruction dump. Knowledge of ASM and C is needed to understand Ghidra's output. 41 | 42 | ## Preparations ## 43 | 44 | 1. Download and install all the stuff mentioned above. 45 | 46 | 2. Compile modified FS-UAE (just to be clear: you need both, a modified and unmodified fs-uae): 47 | * unpack source archive 48 | 49 | * apply patch and build 50 | ``` 51 | cd /path/to/fs-uae.3.0.5 52 | patch -p1 < /path/to/fs-uae-dump-analyzer/patch/fs-uae-3.0.5_dump.patch 53 | ./configure && make 54 | strip fs-uae 55 | ``` 56 | 57 | 3. Install the Amiga hunks plugin 58 | 1. start Ghidra 59 | 2. choose File -> Install Extension 60 | 3. click on the plus icon near the top right 61 | 4. choose the plugin (the .zip archive, as downloaded) 62 | 5. make sure "ghidra_amiga_ldr" is checked 63 | 64 | 4. Compile the dump analyzer in release mode (loading files in <1 vs. 15+ seconds) 65 | ``` 66 | cd /path/to/fs-uae-dump-analyzer/ 67 | cargo build --release 68 | ``` 69 | 70 | 5. Set up a working directory and scripts to your liking. 71 | * I used a symlink to `/path/to/fs-uae-dump-analyzer/target/release/dump-analyzer` for convenience. 72 | * FS-UAE (both variants) needs to be started via command line for debug mode to work. A simple `/path/to/fsuae /path/to/configuration` will do that, but you might want to do some extra stuff for dumping. `newdump.sh` and `startamb.sh` in the scripts directory are what I used. 73 | You also need to append the following line to the config file: 74 | ``` 75 | console-debugger = 1 76 | ``` 77 | 78 | ## Taking a dump ## 79 | 80 | Ok.. so let's start with something easy and find the function that determines a readable value. In Ambermoon this would be a damage roll in battle. 81 | 1. Start the modified FS-UAE and redirect its output to a file called `opcode.log`. Writing to a RAM-Disk (tmpfs on linux) may be preferable, but I don't think it's necessary. On Linux you can adapt the `newdump.sh` script to do this. 82 | 2. Get the game started, the press `F12` and **save state**. You should use the save & load state features instead of completely restarting the game, because 1.) it's faster 2.) it ensures that the program is loaded at the same address in memory for all tests, meaning you have to find out the offset between the addresses FS-UAE and Ghidra use only once. 83 | 3. Get to the part in the game, shortly before whatever you want to analyze happens. 84 | 4. Now... **read through the next steps** first, and prepare to press `F12` and the Key, that is `D` on qwert-type keyboard layouts at the right time (e.g. `F12+E` on dvorak). This would normally start the debugger but, in our modified version, will make FS-UAE dump information on every CPU instruction it emulates. 85 | 5. If there is enough timing between triggering the action possible, trigger it. If not and you need to click your mouse to trigger it, move the pointer to the right spot. Then press `F12+E` (or whatever it is on your keyboard). If you need to trigger the action, do it now. 86 | 6. You will notice, that the emulation slows down significantly - that is FS-UAE dumping. 87 | 7. Press your middle mouse button to exit FS-UAE's focus, wait until what you wanted to happen, did happen, note the number and close the FS-UAE window (it won't stop on it's own!). 88 | 8. Wait until your shell is ready again and, if you didn't use my script, move the dump to a directory. 89 | 90 | Now let's use dump-analyzer.. 91 | Assuming in the dump from Ambermoon, Egil did 7 damage to some Monster and you saved it to a directory called `egil_7_dmg` 92 | ``` 93 | $ ./dump-analyzer d egil_7_dmg 7 94 | 00F824DA, @153626 D0: 0 -> 7 95 | 071789EA, @206809 D1: 32001b -> 320007 96 | 07178FE0, @206818 D0: 70a0000 -> 70a0007 97 | 07180D02, @207656 D5: e -> 7 98 | 07180D9A, @208452 D5: e -> 7 99 | 071828DE, @296286 D1: 68 -> 7 100 | 07182986, @296868 D1: 32 -> 7 101 | 0718298A, @296741 D0: 3b -> 7 102 | 071829AE, @296816 D1: fff9 -> 7 103 | 071829C2, @295648 D1: 5 -> 7 104 | 07182E40, @281856 D7: 8 -> 7 105 | 071836A2, @281644 D7: 8 -> 7 106 | 0718388E, @282688 D0: 6 -> 7 107 | 07185384, @283848 D0: 8 -> 7 108 | 07185392, @270730 D0: 6 -> 7 109 | 07185D88, @283728 D0: 6 -> 7 110 | 07185D8A, @283729 D2: 6 -> 7 111 | 07185E5A, @283804 D2: 8 -> 7 112 | 0718614E, @206925 D0: 0 -> 7 113 | 07186C64, @208636 D2: a0014 -> 7 114 | 07186CDA, @208664 D2: ffff -> 7 115 | 0718A4EA, @210652 D0: 8 -> 7 116 | ``` 117 | 118 | This will show a list of candidates, where that value was finally determined. Each line shows the program counter , followed by the position of the instruction inside the dump and a list of data register changes resulting in the value 7. A change like 32001b -> 320007 might still be 7, because Operations might use just 8 or 16 bits and ignore the rest. Changes at a pc like 00F824DA are usually system calls. 119 | 120 | That is still a lot of possibilities, so let's take another dump and reduce this. 121 | This time Valdyn did the attacking and did 6 damage... 122 | ``` 123 | $ ./dump-analyzer d egil_7_dmg 7 valdyn_6_dmg 6 124 | 071789EA, @206809 D1: 32001b -> 320007 , @246860 D1: 140016 -> 140006 125 | 07178FE0, @206818 D0: 70a0000 -> 70a0007 , @246869 D0: 70a0005 -> 70a0006 126 | 0718298A, @296741 D0: 3b -> 7 , @369053 D0: 35 -> 6 127 | 07182E40, @281856 D7: 8 -> 7 , @347629 D7: 7 -> 6 128 | 071836A2, @281644 D7: 8 -> 7 , @351467 D7: 7 -> 6 129 | 0718388E, @282688 D0: 6 -> 7 , @347946 D0: 5 -> 6 130 | 07185384, @283848 D0: 8 -> 7 , @357130 D0: 7 -> 6 131 | 07185392, @270730 D0: 6 -> 7 , @344005 D0: 5 -> 6 132 | 07185D88, @283728 D0: 6 -> 7 , @356998 D0: 5 -> 6 133 | 07185D8A, @283729 D2: 6 -> 7 , @356999 D2: 5 -> 6 134 | 07185E5A, @283804 D2: 8 -> 7 , @357087 D2: 7 -> 6 135 | 0718614E, @206925 D0: 0 -> 7 , @246971 D0: 0 -> 6 136 | 07186C64, @208636 D2: a0014 -> 7 , @249329 D2: 7 -> 6 137 | 07186CDA, @208664 D2: ffff -> 7 , @249357 D2: 7 -> 6 138 | 0718A4EA, @297723 D0: 8 -> 7 , @249147 D0: 7 -> 6 139 | ``` 140 | 141 | The results in the middle and the one at the end decrease or increase the value by one, so they are probably for loops. This leaves 6 candidates. We could add more dumps, but for the sake of brevity, lets just jump to the next step: the verification. 142 | What we want to find, is the instruction where the value was actually determined. It makes sense to try them in the order they were executed (number after `@`), because the value could have been saved on the stack and loaded later, before being displayed to the user. 143 | 144 | ### Verification ### 145 | Now, let's start the **unpatched** FS-UAE with the same configuration and load the same state. Do as before and press `F12+E` (or `F12+D` or whatever) - but this time we're starting the actual debug mode. You'll see something like that: 146 | ``` 147 | WARNING: Activated debugger 148 | -- stub -- activate_console 149 | D0 07170200 D1 00000000 D2 00000018 D3 1F87000C 150 | D4 000000C0 D5 0000FFFF D6 0000000C D7 00000094 151 | A0 070A8718 A1 00035148 A2 00111B24 A3 0718C28E 152 | A4 070AA0D6 A5 070A5AF6 A6 00DFF000 A7 070A5ACE 153 | USP 070A5ACE ISP 07002270 SFC 00000000 DFC 00000000 154 | CACR 00000000 VBR 00000000 CAAR 00000000 MSP 00000000 155 | T=00 S=0 M=0 X=0 N=0 Z=1 V=0 C=0 IMASK=0 STP=0 156 | 07180BB8 0828 0000 0011 BTST.B #$0000,(A0, $0011) == $070a8729 157 | Next PC: 07180bbe 158 | > 159 | 160 | ``` 161 | The value above "Next PC:" is the current PC, followed by the Operation to be executed next in hex, followed by a more human-readable interpretation of it. Besides that, the most important values are the register contents, labeled D0-D7 for data registers (where calculations are usually made) and A0-A7 for address registers (pointing to data in memory). A7 is (as far as I know) actually the stack pointer. 162 | 163 | To check our first candidate, lets add a breakpoint at it with `f`, then continue with `g`. `?` will show a command summary. 164 | ``` 165 | >f 071789EA 166 | Breakpoint added 167 | >g 168 | ``` 169 | Lets trigger the action in game and wait until it stops and the debugger displays something like 170 | ``` 171 | Breakpoint at 071789EA 172 | ``` 173 | From the line 174 | ``` 175 | 071789EA, @206809 D1: 32001b -> 320007 , @246860 D1: 140016 -> 140006 176 | ``` 177 | we know the change occurs in D1 and uses 8 or 16 bit - so let's set it to some unlikely value like 101 and continue with 178 | ``` 179 | >r D1 00c5 180 | >g 181 | ``` 182 | 183 | if you deal 101 points of damage - great that's the pc :) 184 | if not, back to debug mode, unset the breakpoint, and try the next one. There is a also `fd` command to remove all breakpoints, but it seems broken. You can list active breakpoints with `fl`. 185 | ``` 186 | >f 71789EA 187 | Breakpoint removed 188 | >f 07178FE0 189 | ``` 190 | 191 | Ok.. so we found the first code location.. what now? 192 | 193 | ## Analyzing the function ## 194 | 195 | There are some options... 196 | * Read the opcode.log, search for the pc and go up from there.. 197 | * `./dump-analyzer i egil_7_dmg 71789EA 100 7 0a` will give you a summary of the 100 steps leading to the first occurence of 71789EA in the dump, highlighting values 7 and 0a (all hex). 198 | * `./dump-analyzer s egil_7_dmg 71789EA 100` will print a more compact summary without highlighting. I found this suitable for copying into a text editor and making notes. 199 | * `./dump-analyzer m egil_7_dmg 71789EA 100` (semi-deprecated) will print commands, you can paste into the FS-UAE debugger, to make it dump associated memory, which you can save to a file called `mem` in the directory containing the dump. (remove all the leading `>` first!). This can improve the summaries above a bit - but don't forget that it's just the memory state at the exact time you pasted the commands!I made this before noticing the `S` command, that can dump whole memory ranges to a file. But this may still be useful if you want to view a reduced part of memory in a text editor. `dump-analyzer` can read both this text output and the binary version. 200 | 201 | These can help, because you see what actually happened this specific time. For most of the work however, the main tool will now be Ghidra - so start it. 202 | A full guide to Ghidra is outside the scope of this Readme (I guess it's a tutorial by now..), so I just concentrate on the first steps and the things that seemed most useful to me - besides I'm a beginner here myself. 203 | 204 | 1. Create new project 205 | 2. Import a file (shortcut: `I`) 206 | 3. Choose the executable file. In case of Ambermoon there were 3. The Ambermoon - loader, AM2_CPU and AM2_BLIT, where AM2_CPU seems to contain all the interesting stuff. My guess is that AM2_BLIT is only used on certain hardware configurations. 207 | 4. Format should be "Amiga Executable Hunks loader" - if you can't choose this, the plugin is probably not installed or activated. 208 | 5. Open it and say __Yes__ when asked if it should be analyzed (use default values). 209 | 6. At this point you can partially (bug reported) turn off the chinese water torture feature in Edit -> Tool Options -> Options -> Listing Fields -> Cursor. 210 | 211 | Now we need to find the offset of our function in Ghidra's listing window. But: the offset we found was absolute for the running instance, while the one here relative to the programs address space. To bridge this, we need to find the difference. `dump-analyzer g` can help :) 212 | 213 | ``` 214 | ./dump-analyzer g egil_7_dmg 07178A60 20 215 | [........] [........] 216 | 302a 00da 217 | d06a 00dc 218 | 7200 219 | 322a 002a 220 | d26a 002e 221 | 82fc 0019 222 | d240 223 | 0c10 0001 224 | 6612 225 | 3039 0709 e354 226 | 670a 227 | 0640 0064 228 | c2c0 229 | 82fc 0064 230 | 3001 231 | 4eb9 0718 52ca 232 | Negative step not implemented 233 | ``` 234 | This will try to generate an instruction pattern, starting from 07178A60 including up to 20 instructions. I doesn't matter where we start - but we need a certain amount of output to be specific enough. The command can fail to produce something suitable if there are function calls or loops, but a few tries should produce something good. As an alternative, you could try the disassembly command in the FS-UAE debugger. 235 | 236 | In Ghidra, go to Search -> For Instruction Patterns, click the little icon with the pen (next to the house), select Hex mode and paste the part of the output of `./dump-analyzer g` from the first to the last hex value (302a .. 52ca) into that window and click "Apply". 237 | 238 | Some of these values (most likely those starting with 0x07) are translated addresses. To find anything, we have to mask them by clicking on them. This should look like this: 239 | 240 | ![](assets/instruction_search.png) 241 | 242 | Click on "Search All" and a window with (ideally) one search result should show. 243 | Select it, confirm that it matches the instructions. Then subtract its offset from the one found earlier. 244 | ``` 245 | 071789EA - 00238d6c = 6F3FC7E 246 | ``` 247 | With this value, you can easily convert between the two offset spaces. If qalc is installed, you can adapt `conv_offset.sh` for this. 248 | 249 | If you save this to a file `offset` in the dump directory, some commands in `dump-analyzer` will print the translated PC when called with an uppercase letter. For new dumps, use a symlink or copy it there. 250 | 251 | Now you're ready to enter the iterative circle of reverse engineering, meaning: 252 | * make notes in Ghidra 253 | * analyze dumps to find more functions 254 | * revise previous notes 255 | 256 | Every step will create more context, making Ghidra's output more clear. 257 | 258 | #### Find data chunks in memory #### 259 | To improve your understanding of data access, you can use the `./dump-analyzer M ` command. 260 | Wher `dir` is a directory, containing the memory dump. Both the text variant (filename=`mem`) as well as binary dumps (named as their starting address in hex, e.g. `07000000`) can be used. 261 | 262 | First you need to extract the data you want to search for into a directory structure. This should be something like `/filename_of_original_datafile/data_index`, e.g. `AMB/1Icon_gfx.amb/001` 263 | 264 | To get a full dump of all interesting memory, get into FS-UAEs debug mode and use 265 | `dm` to get the address space map. This will show something like 266 | ``` 267 | 00000000 2048K/1 = 2048K Chip memory 268 | 00200000 8192K/1 = 8192K Fast memory 269 | 00A00000 512K/0 = 512K 270 | 00A80000 1024K/2 = 512K Kickstart ROM (14E93BCC) 271 | [...] 272 | 07000000 16M/1 = 16M RAMSEY memory (low) 273 | 08000000 896M/0 = 896M 274 | 40000000 16M/1 = 16M Zorro III Fast RAM 275 | 41000000 3056M/0 = 3056M 276 | ``` 277 | 278 | Things labeled and ROM won't contain any interesting data, so just save what you need, like this: 279 | ``` 280 | S /tmp/00000000 00000000 00A00000 281 | S /tmp/07000000 07000000 01000000 282 | S /tmp/40000000 40000000 01000000 283 | ``` 284 | 285 | Then move the files to you ``. It is important that the file name is the starting address! 286 | 287 | With that we can call `./dump-analyzer M mem_battle AMB > dataMap.csv` which creates a nice TAB-separated file, we can open with a Spreadsheet application like libreoffice calc, or a text editor. 288 | ``` 289 | File Index Mem Translated Size 290 | 1Map_data.amb 193 0x40088484 0x40088484 10338 291 | 1Map_data.amb 036 0x40088484 0x40088484 10338 292 | [...] 293 | ``` 294 | You can use an offset file if you believe something is loaded into fixed locations, but usually the memory locations will be allocated by the OS at runtime. This makes it unsuited for searching in Ghidra, but can be helpful to make sense of the opcode.log / debugger output. 295 | 296 | ### A quick summary of things I found most useful in the FS-UAE debugger and Ghidra. ### 297 | 298 | #### FS-UAE debugger #### 299 | | Syntax | Description | Example | 300 | | :--- | :--- | :--- | 301 | | `?` | show command summary | | 302 | | `f
` | Add/remove breakpoint. | `f 0718A0B0` | 303 | | `fl` | List breakpoints | | 304 | | `t [instructions]` | Step one or more instructions. | | 305 | | `z` | Step through one instruction (subroutine) | | 306 | | `r ` | Modify CPU register | `r D0 00C4` | 307 | | `dm` | Dump current address space map. | | 308 | | `m
[]` | Memory dump starting at
| `m 0718A0B0 4` | 309 | | `S file
` | Write into Amiga memory. | `W 0718A0B2 A4B2` | 311 | | `g [
]` | Start execution at the current address or \. | `g` | 312 | 313 | #### Ghidra #### 314 | 315 | * **Comment** with `;`, if you have some thoughts on a part of code/data 316 | * **Label** a function or data location with `L` - if you know (or strongly suspect) what it does. This will make the label appear instead of an address everywhere it is called / accessed. 317 | * Define **data structures** via "Data Type Manager" -> \[program name\] -> right click -> New -> Structure, or from data segments with `[`. Then **set data type** with `T` (for data segments) or `Ctrl+L` (for variables). 318 | 319 | In time, what you see in Ghidra will look less like a bunch of wild numbers and more like this: 320 | 321 | ![](assets/ghidra_decompile.png) 322 | 323 | #### And what is that M68K manual good for? #### 324 | The answer is: you can't always rely on the decompiler and should check the opcode! 325 | 326 | I had one case, where it showed something like `DAT_0024ACE0 = '\0'`, when the disassembler listing clearly showed, that instead of setting the value to 0, it was set to the value of a neighbouring memory cell. As far as I understand it, that value was initially 0, but would be changed at runtime. Ghidra did not know that, and made a false assumption. 327 | 328 | Because of things like this, it is important to understand the M68K opcode and it might be a good idea to figure out a few functions using the summary from `dump-analyzer` and the M68K manual for practice, before moving to Ghidra. 329 | 330 | And if you're wondering where PUSH and POP are... in M68K, register states are saved and restored to/from stack with MOVEM. 331 | 332 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------