Rewrite the entire crate, add assembler
- 10x faster disassembly performance - Nearly feature-complete assembler - `no_std` compatible - Relicense to MIT/Apache-2.0 - Remove old crates (dol, flow-graph, etc) - Remove Python bindings (for now, at least)
This commit is contained in:
parent
f6e15052b1
commit
c4af15ddc2
|
@ -2,13 +2,19 @@
|
|||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.80"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1"
|
||||
|
||||
[[package]]
|
||||
name = "atty"
|
||||
version = "0.2.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"hermit-abi 0.1.19",
|
||||
"libc",
|
||||
"winapi",
|
||||
]
|
||||
|
@ -19,100 +25,72 @@ version = "1.1.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
|
||||
|
||||
[[package]]
|
||||
name = "bincode"
|
||||
version = "1.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "3.1.8"
|
||||
version = "3.2.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71c47df61d9e16dc010b55dba1952a57d8c215dbb533fd13cdd13369aac73b1c"
|
||||
checksum = "4ea181bf566f71cb9a5d17a59e1871af638180a18fb0035c92ae62b705207123"
|
||||
dependencies = [
|
||||
"atty",
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
"os_str_bytes",
|
||||
"clap_lex",
|
||||
"indexmap 1.9.3",
|
||||
"strsim",
|
||||
"termcolor",
|
||||
"textwrap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor"
|
||||
version = "0.1.22"
|
||||
name = "clap_lex"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f877be4f7c9f246b183111634f75baa039715e3f46ce860677d3b19a69fb229c"
|
||||
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn",
|
||||
"os_str_bytes",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dol"
|
||||
version = "0.1.0"
|
||||
name = "colored"
|
||||
version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8"
|
||||
dependencies = [
|
||||
"bincode",
|
||||
"serde",
|
||||
"thiserror",
|
||||
"lazy_static",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.6.1"
|
||||
name = "deranged"
|
||||
version = "0.3.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
|
||||
|
||||
[[package]]
|
||||
name = "fixedbitset"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "279fb028e20b3c4c320317955b77c5e0c9701f05a1d309905d6fc702cdc5053e"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"
|
||||
checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
"powerfmt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ghost"
|
||||
version = "0.1.2"
|
||||
name = "equivalent"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a5bcf1bbeab73aa4cf2fde60a846858dc036163c7c33bec309f8d17de785479"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.11.2"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
|
||||
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
|
@ -124,181 +102,153 @@ dependencies = [
|
|||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.8.1"
|
||||
name = "hermit-abi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee"
|
||||
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"hashbrown",
|
||||
"hashbrown 0.12.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indoc"
|
||||
version = "1.0.4"
|
||||
name = "indexmap"
|
||||
version = "2.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7906a9fababaeacb774f72410e497a1d18de916322e33797bb2cd29baa23c9e"
|
||||
checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4"
|
||||
dependencies = [
|
||||
"unindent",
|
||||
"equivalent",
|
||||
"hashbrown 0.14.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "instant"
|
||||
version = "0.1.12"
|
||||
name = "itoa"
|
||||
version = "1.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
|
||||
|
||||
[[package]]
|
||||
name = "inventory"
|
||||
version = "0.2.2"
|
||||
name = "lazy_static"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6b5d8c669bfbad811d95ddd7a1c6cf9cfdbf2777e59928b6f3fa8ff54f72a0"
|
||||
dependencies = [
|
||||
"ctor",
|
||||
"ghost",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.122"
|
||||
version = "0.2.153"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec647867e2bf0772e28c8bcde4f0d19a9216916e890543b5a03ed8ef27b8f259"
|
||||
checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
|
||||
|
||||
[[package]]
|
||||
name = "linked-hash-map"
|
||||
version = "0.5.4"
|
||||
name = "log"
|
||||
version = "0.4.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
|
||||
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.7"
|
||||
name = "num-conv"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"
|
||||
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.14"
|
||||
version = "0.2.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
|
||||
checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num_cpus"
|
||||
version = "1.13.1"
|
||||
version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1"
|
||||
checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"hermit-abi 0.3.9",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.10.0"
|
||||
name = "num_threads"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9"
|
||||
checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "os_str_bytes"
|
||||
version = "6.0.0"
|
||||
version = "6.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
checksum = "e2355d85b9a3786f481747ced0e0ff2ba35213a1f9bd406ed906554d7af805a1"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
name = "phf"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
|
||||
checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc"
|
||||
dependencies = [
|
||||
"instant",
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
"phf_shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.8.5"
|
||||
name = "phf_codegen"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216"
|
||||
checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"instant",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"winapi",
|
||||
"phf_generator",
|
||||
"phf_shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parse_int"
|
||||
version = "0.6.0"
|
||||
name = "phf_generator"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d695b79916a2c08bcff7be7647ab60d1402885265005a6658ffe6d763553c5a"
|
||||
checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
"phf_shared",
|
||||
"rand",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "petgraph"
|
||||
version = "0.6.0"
|
||||
name = "phf_shared"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a13a2fa9d0b63e5f22328828741e523766fff0ee9e779316902290dff3f824f"
|
||||
checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b"
|
||||
dependencies = [
|
||||
"fixedbitset",
|
||||
"indexmap",
|
||||
"siphasher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppc750cl"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
"serde",
|
||||
]
|
||||
version = "0.3.0"
|
||||
|
||||
[[package]]
|
||||
name = "ppc750cl-flow-graph"
|
||||
version = "0.2.0"
|
||||
name = "ppc750cl-asm"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"dol",
|
||||
"itertools",
|
||||
"parse_int",
|
||||
"petgraph",
|
||||
"ppc750cl",
|
||||
"phf",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppc750cl-fuzz"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"num_cpus",
|
||||
|
@ -307,113 +257,46 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "ppc750cl-genisa"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"itertools",
|
||||
"anyhow",
|
||||
"log",
|
||||
"num-traits",
|
||||
"phf",
|
||||
"phf_codegen",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"serde_yaml",
|
||||
"simple_logger",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppc750cl-py"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"ppc750cl",
|
||||
"pyo3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppc750cl-rand"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"ppc750cl",
|
||||
"rand_core",
|
||||
"sfmt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
name = "prettyplease"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"
|
||||
checksum = "a41cf62165e97c7f814d2221421dbb9afcbcdb0a88068e5ea206e19951c2cbb5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.37"
|
||||
version = "1.0.78"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1"
|
||||
checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
|
||||
dependencies = [
|
||||
"unicode-xid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3"
|
||||
version = "0.16.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b3e99c4c3e790e4fc365b42b70c1f7801f42eadc4ea648fa327e6f5ca29f215"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"indoc",
|
||||
"inventory",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
"pyo3-build-config",
|
||||
"pyo3-ffi",
|
||||
"pyo3-macros",
|
||||
"unindent",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3-build-config"
|
||||
version = "0.16.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2486b96281859ff0a3929ba6467b13751627b974f7137362db38e2bed14b2094"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"target-lexicon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3-ffi"
|
||||
version = "0.16.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd9de1d94557751599f8bd321f10e6c1ef2801067acb58c91138deef2ae83a17"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"pyo3-build-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3-macros"
|
||||
version = "0.16.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b9584049129b1cfb615243391a6345c726690271ae195ffd6aa3766177296aa"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"pyo3-macros-backend",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyo3-macros-backend"
|
||||
version = "0.16.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c4717e6a55c51a9958eda1f5481ff7f62cccd21f45309c10e4731cb7198dbc"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.17"
|
||||
version = "1.0.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58"
|
||||
checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
@ -424,65 +307,35 @@ version = "0.8.5"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.3"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.2.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.9"
|
||||
version = "1.0.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
|
||||
checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.136"
|
||||
version = "1.0.197"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789"
|
||||
checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.136"
|
||||
version = "1.0.197"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9"
|
||||
checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
@ -491,31 +344,34 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "serde_yaml"
|
||||
version = "0.8.23"
|
||||
version = "0.9.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4a521f2940385c165a24ee286aa8599633d162077a54bdcae2a6fd5a7bfa7a0"
|
||||
checksum = "8fd075d994154d4a774f95b51fb96bdc2832b0ea48425c92546073816cda1f2f"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"indexmap 2.2.5",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
"yaml-rust",
|
||||
"unsafe-libyaml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sfmt"
|
||||
version = "0.7.0"
|
||||
name = "simple_logger"
|
||||
version = "4.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e389a3c1536438f85612667cd992dfb7169f60784252342278458e90d37c7565"
|
||||
checksum = "8e7e46c8c90251d47d08b28b8a419ffb4aede0f87c2eea95e17d1d5bacbf3ef1"
|
||||
dependencies = [
|
||||
"rand",
|
||||
"rand_core",
|
||||
"colored",
|
||||
"log",
|
||||
"time",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.8.0"
|
||||
name = "siphasher"
|
||||
version = "0.3.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83"
|
||||
checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
|
@ -525,73 +381,74 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
|
|||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.91"
|
||||
version = "2.0.52"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d"
|
||||
checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-xid",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-lexicon"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7fa7e55043acb85fca6b3c01485a2eeb6b69c5d21002e273c79e465f43b7ac1"
|
||||
|
||||
[[package]]
|
||||
name = "termcolor"
|
||||
version = "1.1.3"
|
||||
version = "1.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
|
||||
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "textwrap"
|
||||
version = "0.15.0"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
|
||||
checksum = "23d434d3f8967a09480fb04132ebe0a3e088c173e6d0ee7897abbdf4eab0f8b9"
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.30"
|
||||
name = "time"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417"
|
||||
checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
"deranged",
|
||||
"itoa",
|
||||
"libc",
|
||||
"num-conv",
|
||||
"num_threads",
|
||||
"powerfmt",
|
||||
"serde",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "1.0.30"
|
||||
name = "time-core"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b"
|
||||
checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"num-conv",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.2"
|
||||
name = "unicode-ident"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
|
||||
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
|
||||
|
||||
[[package]]
|
||||
name = "unindent"
|
||||
version = "0.1.8"
|
||||
name = "unsafe-libyaml"
|
||||
version = "0.2.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "514672a55d7380da379785a4d70ca8386c8883ff7eaae877be4d2081cebe73d8"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.10.2+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
|
||||
checksum = "ab4c90930b95a82d00dc9e9ac071b4991924390d46cbd0dfe566148667605e4b"
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
|
@ -611,9 +468,9 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
|||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
|
||||
checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
|
||||
dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
@ -625,10 +482,67 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "yaml-rust"
|
||||
version = "0.4.5"
|
||||
name = "windows-sys"
|
||||
version = "0.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
|
||||
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
||||
dependencies = [
|
||||
"linked-hash-map",
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.48.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
||||
|
|
18
Cargo.toml
18
Cargo.toml
|
@ -1,11 +1,11 @@
|
|||
[workspace]
|
||||
members = ["asm", "disasm", "fuzz", "genisa"]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"disasm",
|
||||
"disasm-py",
|
||||
"dol",
|
||||
"fuzz",
|
||||
"genisa",
|
||||
"flow-graph",
|
||||
"rand",
|
||||
]
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
opt-level = "z"
|
||||
|
||||
[profile.release-lto]
|
||||
inherits = "release"
|
||||
lto = "thin"
|
||||
|
|
674
LICENSE
674
LICENSE
|
@ -1,674 +0,0 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2024 Luke Street.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright 2024 Luke Street.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
36
README.md
36
README.md
|
@ -5,35 +5,10 @@ Rust tools for working with the PowerPC 750CL family of processors.
|
|||
### Rust crates
|
||||
|
||||
```shell
|
||||
rustup components add rustfmt
|
||||
cargo run --package ppc750cl-genisa
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
### Python module
|
||||
|
||||
```shell
|
||||
python -m venv env
|
||||
source ./env/bin/activate
|
||||
pip install maturin
|
||||
maturin build -m ./disasm-py/Cargo.toml
|
||||
```
|
||||
|
||||
Install module in dev env
|
||||
|
||||
```
|
||||
maturin develop -m ./disasm-py/Cargo.toml
|
||||
python
|
||||
>>> import ppc750cl
|
||||
>>> ins = ppc750cl.Ins(addr=0x80006969, code=0x10400420)
|
||||
>>> str(ins)
|
||||
'ps_merge00 f2, f0, f0'
|
||||
>>> ins.fields()
|
||||
[('frD', 2), ('frA', 0), ('frB', 0)]
|
||||
>>> ins.frD
|
||||
2
|
||||
```
|
||||
|
||||
### Instruction Set
|
||||
|
||||
For those unfamiliar with PowerPC, here are some basics.
|
||||
|
@ -48,7 +23,7 @@ For those unfamiliar with PowerPC, here are some basics.
|
|||
|
||||
The file [isa.yaml](./isa.yaml) contains a full definition of the PowerPC 750CL instruction set.
|
||||
|
||||
It powers the disassembler, assembler, and Rust/Python bindings code analysis tools.
|
||||
It powers the disassembler and assembler.
|
||||
|
||||
Similarly to LLVM TableGen, the program `ppc750cl-genisa` generates a Rust file implementing an instruction decoder.
|
||||
|
||||
|
@ -57,10 +32,11 @@ Similarly to LLVM TableGen, the program `ppc750cl-genisa` generates a Rust file
|
|||
- This project does not use `unsafe` Rust code outside of testing utils.
|
||||
- The disassembler has been fuzzed over all ~4.29 billion possible instructions (via `ppc750cl-fuzz`).
|
||||
- It is safe to run the disassembler over untrusted byte arrays.
|
||||
- However no guarantees on correctness are made (yet). Expect bugs.
|
||||
- However, no guarantees on correctness are made (yet). Expect bugs.
|
||||
|
||||
### Performance
|
||||
|
||||
- Performance isn't great but acceptable.
|
||||
- Disassembling & printing: 600k insn/s (2.4 MB/s)
|
||||
- Disassembling only: 6M insn/s (24 MB/s)
|
||||
With a single thread on Ryzen 9 3900X:
|
||||
|
||||
- Disassembling & printing: ~5M insn/s (~20 MB/s)
|
||||
- Disassembling only: ~50M insn/s (~200 MB/s)
|
||||
|
|
174
analysis/cfa.md
174
analysis/cfa.md
|
@ -1,174 +0,0 @@
|
|||
---
|
||||
date: 2022-04-10
|
||||
status: draft
|
||||
---
|
||||
|
||||
# Control-flow analysis
|
||||
|
||||
CFA analyses the entire `.text` section with linear complexity.
|
||||
|
||||
It has the following goals:
|
||||
- Detect function boundaries
|
||||
- Create the control-flow graph of each function
|
||||
|
||||
## Pass 1: Find control-flow intrinsics
|
||||
|
||||
Input:
|
||||
- `.text` section
|
||||
|
||||
Output:
|
||||
- Locations of compiler intrinsics
|
||||
|
||||
Rules
|
||||
|
||||
*savegpr/restgpr detection* (CodeWarrior only)
|
||||
|
||||
Find the following instructions in `.text`
|
||||
|
||||
```asm
|
||||
_save_gpr:
|
||||
stw r14, -0x48(r11)
|
||||
stw r15, -0x44(r11)
|
||||
stw r16, -0x40(r11)
|
||||
stw r17, -0x3c(r11)
|
||||
stw r18, -0x38(r11)
|
||||
stw r19, -0x34(r11)
|
||||
stw r20, -0x30(r11)
|
||||
stw r21, -0x2c(r11)
|
||||
stw r22, -0x28(r11)
|
||||
stw r23, -0x24(r11)
|
||||
stw r24, -0x20(r11)
|
||||
stw r25, -0x1c(r11)
|
||||
stw r26, -0x18(r11)
|
||||
stw r27, -0x14(r11)
|
||||
stw r28, -0x10(r11)
|
||||
stw r29, -0xc(r11)
|
||||
stw r30, -0x8(r11)
|
||||
stw r31, -0x4(r11)
|
||||
blr
|
||||
|
||||
_load_gpr:
|
||||
lwz r14, -0x48(r11)
|
||||
lwz r15, -0x44(r11)
|
||||
lwz r16, -0x40(r11)
|
||||
lwz r17, -0x3c(r11)
|
||||
lwz r18, -0x38(r11)
|
||||
lwz r19, -0x34(r11)
|
||||
lwz r20, -0x30(r11)
|
||||
lwz r21, -0x2c(r11)
|
||||
lwz r22, -0x28(r11)
|
||||
lwz r23, -0x24(r11)
|
||||
lwz r24, -0x20(r11)
|
||||
lwz r25, -0x1c(r11)
|
||||
lwz r26, -0x18(r11)
|
||||
lwz r27, -0x14(r11)
|
||||
lwz r28, -0x10(r11)
|
||||
lwz r29, -0xc(r11)
|
||||
lwz r30, -0x8(r11)
|
||||
lwz r31, -0x4(r11)
|
||||
blr
|
||||
```
|
||||
|
||||
## Pass 2: Branch analysis
|
||||
|
||||
Input:
|
||||
- `.text` section
|
||||
|
||||
Output:
|
||||
- Slices (cuts) from which basic blocks can be derived
|
||||
- Forward edges between basic blocks
|
||||
- Initial set of function boundaries
|
||||
|
||||
#### Branch instruction hints
|
||||
|
||||
- Iterate over all branch opcodes (b, bc, bcctr, bclr)
|
||||
- Assume that branches with link register save …
|
||||
- point to the start of another function;
|
||||
- eventually return back to the call site.
|
||||
- Assume that branches without link register save are …
|
||||
- tail calls if their target precedes the function start of the call site;
|
||||
- probably jumps to basic blocks within the function otherwise (might be wrong)
|
||||
- Skip indirect local branches (bcctr, bclr) for now.
|
||||
|
||||
#### Stack frame detection (CodeWarrior only)
|
||||
|
||||
Detect patterns matching stack frames. They might be reordered due to instruction scheduling.
|
||||
|
||||
Since CodeWarrior will only emit one function epilogue and prologue per function,
|
||||
we can use this hint (if present) to reliably detect function bounds.
|
||||
|
||||
- On function entry point:
|
||||
- Execute instructions up to next branch
|
||||
- Derive stack frame from changes in machine state
|
||||
- If the stack changed, we found an epilog
|
||||
- When a `blr` (function return) is encountered:
|
||||
- Execute instructions in basic block of `blr`
|
||||
- If stack-related machine state got reverted, assume this BB to contain the prolog
|
||||
|
||||
Example 0x80045de0 from RMCP01 (savegpr/restgpr sled):
|
||||
|
||||
```asm
|
||||
# Stack
|
||||
# +0x04..+0x08: ret addr to caller
|
||||
# 0x00..+0x04: caller backchain <- caller r1
|
||||
# -0x30.. 0x00: callee saved gprs <- callee r11
|
||||
# -0x68..-0x30: callee stack
|
||||
# -0x6c..-0x68: ret addr to callee
|
||||
# -0x70..-0x6c: callee backchain <- callee r1
|
||||
|
||||
_alloc_stack_frame:
|
||||
stwu r1, -0x70(r1) # store callee backchain & alloc stack frame
|
||||
mflr r0
|
||||
…
|
||||
stw r0, 0x74(r1) # store ret addr to caller
|
||||
…
|
||||
la r11, 0x40(r1) # load ptr to callee saved gprs
|
||||
bl _savegpr_22 # save gprs
|
||||
mr r31, r1
|
||||
|
||||
…
|
||||
|
||||
_free_stack_frame:
|
||||
mr r10, r31
|
||||
la r11, 0x40(r10) # load ptr to callee saved gprs
|
||||
bl _restgpr_22 # restore gprs
|
||||
lwz r10, 0x0(r1) # load ptr to caller stack frame
|
||||
lwz r0, 0x4(r10) # load ret addr to caller
|
||||
mr r1, r10 # free stack frame
|
||||
mtlr r0
|
||||
blr # return to caller
|
||||
```
|
||||
|
||||
Example 0x80228490 from RMCP01 (stmw/lmw):
|
||||
|
||||
```asm
|
||||
# Stack
|
||||
# +0x04..+0x08: ret addr to caller
|
||||
# 0x00..+0x04: caller backchain <- caller r1
|
||||
# -0x30.. 0x00: callee saved gprs <- callee r11
|
||||
# -0x38..-0x30: callee stack
|
||||
# -0x3c..-0x38: ret addr to callee
|
||||
# -0x40..-0x3c: callee backchain <- callee r1
|
||||
|
||||
_alloc_stack_frame:
|
||||
stwu r1, -0x40(r1) # store callee backchain & alloc stack frame
|
||||
mflr r0
|
||||
stw r0, 0x44(r1) # store ret addr to caller
|
||||
stmw r20, -0x30(r1) # save gprs
|
||||
|
||||
…
|
||||
|
||||
_free_stack_frame:
|
||||
lmw r20, -0x30(r1) # restore gprs
|
||||
lwz r0, 0x44(r1) # load ret addr to caller
|
||||
mtlr r0
|
||||
la r1, 0x40(r1) # free stack frame
|
||||
blr # return to caller
|
||||
```
|
||||
|
||||
## TODO
|
||||
|
||||
Add the following rules:
|
||||
- follow indirect local branches
|
||||
- destructor detection
|
||||
- vtable detection
|
|
@ -0,0 +1,16 @@
|
|||
[package]
|
||||
name = "ppc750cl-asm"
|
||||
version = "0.3.0"
|
||||
edition = "2021"
|
||||
authors = ["Luke Street <luke@street.dev>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Assembler for PowerPC 750CL"
|
||||
keywords = ["powerpc", "wii", "gamecube"]
|
||||
repository = "https://github.com/encounter/ppc750cl"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = []
|
||||
|
||||
[dependencies]
|
||||
phf = "0.11"
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,6 @@
|
|||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
mod generated;
|
||||
mod types;
|
||||
|
||||
pub use generated::*;
|
||||
pub use types::{Argument, ArgumentError};
|
|
@ -0,0 +1,94 @@
|
|||
use crate::Arguments;
|
||||
use core::fmt::Formatter;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ArgumentError {
|
||||
ArgOutOfRangeUnsigned { index: usize, value: u32, start: u32, end: u32 },
|
||||
ArgOutOfRangeSigned { index: usize, value: i32, start: i32, end: i32 },
|
||||
ArgCount { value: usize, expected: usize },
|
||||
UnknownMnemonic,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for ArgumentError {
|
||||
fn fmt(&self, _f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl std::error::Error for ArgumentError {}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
|
||||
pub enum Argument {
|
||||
#[default]
|
||||
None,
|
||||
Unsigned(u32),
|
||||
Signed(i32),
|
||||
}
|
||||
|
||||
pub const fn parse_unsigned(
|
||||
args: &Arguments,
|
||||
index: usize,
|
||||
start: u32,
|
||||
end: u32,
|
||||
) -> Result<u32, ArgumentError> {
|
||||
match args[index] {
|
||||
Argument::Unsigned(value) => {
|
||||
if value >= start && value <= end {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(ArgumentError::ArgOutOfRangeUnsigned { index, value, start, end })
|
||||
}
|
||||
}
|
||||
Argument::Signed(value) => {
|
||||
if value >= start as i32 && value <= end as i32 {
|
||||
Ok(value as u32)
|
||||
} else {
|
||||
Err(ArgumentError::ArgOutOfRangeUnsigned { index, value: value as u32, start, end })
|
||||
}
|
||||
}
|
||||
Argument::None => Err(ArgumentError::ArgCount { value: index, expected: index + 1 }),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn parse_signed(
|
||||
args: &Arguments,
|
||||
index: usize,
|
||||
start: i32,
|
||||
end: i32,
|
||||
) -> Result<i32, ArgumentError> {
|
||||
match args[index] {
|
||||
Argument::Unsigned(value) => {
|
||||
if (start < 0 || value >= start as u32) && value <= end as u32 {
|
||||
Ok(value as i32)
|
||||
} else {
|
||||
Err(ArgumentError::ArgOutOfRangeSigned { index, value: value as i32, start, end })
|
||||
}
|
||||
}
|
||||
Argument::Signed(value) => {
|
||||
if value >= start && value <= end {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(ArgumentError::ArgOutOfRangeSigned { index, value, start, end })
|
||||
}
|
||||
}
|
||||
Argument::None => Err(ArgumentError::ArgCount { value: index, expected: index + 1 }),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn arg_count(args: &Arguments) -> usize {
|
||||
let mut i = 0;
|
||||
while i < args.len() && !matches!(args[i], Argument::None) {
|
||||
i += 1;
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
pub const fn check_arg_count(args: &Arguments, expected: usize) -> Result<(), ArgumentError> {
|
||||
let value = arg_count(args);
|
||||
if value == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ArgumentError::ArgCount { value, expected })
|
||||
}
|
||||
}
|
|
@ -0,0 +1,182 @@
|
|||
use ppc750cl_asm::*;
|
||||
use Argument::{None, Signed as S, Unsigned as U};
|
||||
|
||||
macro_rules! assert_asm {
|
||||
($mnemonic:literal, $arg1:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5: expr, $code:literal) => {{
|
||||
assert_eq!(assemble($mnemonic, &[$arg1, $arg2, $arg3, $arg4, $arg5]).unwrap(), $code)
|
||||
}};
|
||||
($mnemonic:literal, $arg1:expr, $arg2:expr, $arg3:expr, $arg4:expr, $code:literal) => {{
|
||||
assert_eq!(assemble($mnemonic, &[$arg1, $arg2, $arg3, $arg4, None]).unwrap(), $code)
|
||||
}};
|
||||
($mnemonic:literal, $arg1:expr, $arg2:expr, $arg3:expr, $code:literal) => {{
|
||||
assert_eq!(assemble($mnemonic, &[$arg1, $arg2, $arg3, None, None]).unwrap(), $code)
|
||||
}};
|
||||
($mnemonic:literal, $arg1:expr, $arg2:expr, $code:literal) => {{
|
||||
assert_eq!(assemble($mnemonic, &[$arg1, $arg2, None, None, None]).unwrap(), $code)
|
||||
}};
|
||||
($mnemonic:literal, $arg1:expr, $code:literal) => {{
|
||||
assert_eq!(assemble($mnemonic, &[$arg1, None, None, None, None]).unwrap(), $code)
|
||||
}};
|
||||
($mnemonic:literal, $code:literal) => {{
|
||||
assert_eq!(assemble($mnemonic, &[None, None, None, None, None]).unwrap(), $code)
|
||||
}};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_add() {
|
||||
assert_asm!("add", U(2), U(3), U(4), 0x7C432214); // add r2, r3, r4
|
||||
assert_asm!("add.", U(7), U(6), U(5), 0x7CE62A15); // add. r7, r6, r5
|
||||
assert_asm!("addo", U(31), U(31), U(31), 0x7FFFFE14); // addo r31, r31, r31
|
||||
assert_asm!("addo.", U(28), U(29), U(30), 0x7F9DF615); // addo. r28, r29, r30
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_addc() {
|
||||
assert_asm!("addc", U(2), U(3), U(4), 0x7C432014); // addc r2, r3, r4
|
||||
assert_asm!("addc.", U(7), U(6), U(5), 0x7CE62815); // addc. r7, r6, r5
|
||||
assert_asm!("addco", U(31), U(31), U(31), 0x7FFFFC14); // addco r31, r31, r31
|
||||
assert_asm!("addco.", U(28), U(29), U(30), 0x7F9DF415); // addco. r28, r29, r30
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_addi() {
|
||||
assert_asm!("addi", U(0), U(1), U(0x140), 0x38010140); // addi r0, r1, 0x140
|
||||
assert_asm!("addi", U(0), U(4), S(-0x7000), 0x38049000); // addi r0, r4, -0x7000
|
||||
assert_asm!("subi", U(0), U(4), S(0x7000), 0x38049000); // subi r0, r4, 0x7000
|
||||
assert_asm!("li", U(5), U(0), 0x38A00000); // li r5, 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_b() {
|
||||
assert_asm!("b", U(0), 0x48000000); // b 0x0
|
||||
assert_asm!("b", U(4), 0x48000004); // b 0x4
|
||||
assert_asm!("bl", U(0xA5C8), 0x4800A5C9); // bl 0xa5c8
|
||||
assert_asm!("bl", U(0x23B4D8), 0x4823B4D9); // bl 0x23b4d8
|
||||
assert_asm!("bl", S(-0x1FC368), 0x4BE03C99); // bl -0x1fc368
|
||||
assert_asm!("bl", S(-0x23E5A8), 0x4BDC1A59); // bl -0x23e5a8
|
||||
assert_asm!("bla", U(0x60), 0x48000063); // bla 0x60
|
||||
assert_asm!("ba", U(0), 0x48000002); // ba 0x0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_bc() {
|
||||
assert_asm!("bge", U(0x8), 0x40800008); // bge 0x8
|
||||
assert_asm!("bge", U(0x2350), 0x40802350); // bge 0x2350
|
||||
assert_asm!("bge", S(-0x384), 0x4080FC7C); // bge -0x384
|
||||
assert_asm!("ble", U(0xac), 0x408100AC); // ble 0xac
|
||||
assert_asm!("ble", S(-0x878), 0x4081F788); // ble -0x878
|
||||
assert_asm!("bne", U(0x1ba0), 0x40821BA0); // bne 0x1ba0
|
||||
assert_asm!("bne", S(-0x1c3c), 0x4082E3C4); // bne -0x1c3c
|
||||
assert_asm!("bne", U(1), U(0xd8), 0x408600D8); // bne cr1, 0xd8
|
||||
assert_asm!("bne", U(1), S(-0x134), 0x4086FECC); // bne cr1, -0x134
|
||||
assert_asm!("bge", U(7), U(0xc), 0x409C000C); // bge cr7, 0xc
|
||||
assert_asm!("blt", U(0xc), 0x4180000C); // blt 0xc
|
||||
assert_asm!("blt", S(-0x640), 0x4180F9C0); // blt -0x640
|
||||
assert_asm!("bgt", U(0x21c), 0x4181021C); // bgt 0x21c
|
||||
assert_asm!("bgt", S(-0x280), 0x4181FD80); // bgt -0x280
|
||||
assert_asm!("beq", U(0x2304), 0x41822304); // beq 0x2304
|
||||
assert_asm!("beq", S(-0x1c4), 0x4182FE3C); // beq -0x1c4
|
||||
assert_asm!("blt", U(1), U(0x1ac), 0x418401AC); // blt cr1, 0x1ac
|
||||
assert_asm!("blt", U(1), S(-0x31c), 0x4184FCE4); // blt cr1, -0x31c
|
||||
assert_asm!("bgt", U(1), U(0xc0), 0x418500C0); // bgt cr1, 0xc0
|
||||
assert_asm!("bgt", U(1), U(0x2e4), 0x418502E4); // bgt cr1, 0x2e4
|
||||
assert_asm!("beq", U(6), U(0x138), 0x419A0138); // beq cr6, 0x138
|
||||
assert_asm!("blt", U(7), U(0x8), 0x419C0008); // blt cr7, 0x8
|
||||
assert_asm!("bdz", S(-0x10), 0x4240FFF0); // bdz -0x10
|
||||
assert_asm!("bdnz", S(-0xaa0), 0x4200F560); // bdnz -0xaa0
|
||||
assert_asm!("bdnzf", U(1), U(0x14), 0x40010014); // bdnzf gt, 0x14
|
||||
assert_asm!("bdzfl", U(1), U(0x34), 0x40410035); // bdzfl gt, 0x34
|
||||
assert_asm!("bdztla", U(3), U(0x20), 0x41430023); // bdztla un, 0x20
|
||||
assert_asm!("bdnztla", U(8), S(-0x20), 0x4108FFE3); // bdnztla cr2lt, -0x20
|
||||
assert_asm!("bne+", U(0x8), 0x40A20008); // bne+ 0x8
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_bcctr() {
|
||||
assert_asm!("bctr", 0x4E800420); // bctr
|
||||
assert_asm!("bctrl", 0x4E800421); // bctrl
|
||||
assert_asm!("beqctr", 0x4D820420); // beqctr
|
||||
assert_asm!("bgtctrl", U(3), 0x4D8D0421); // bgtctrl cr3
|
||||
assert_asm!("beqctr+", 0x4DA20420); // beqctr+
|
||||
assert_asm!("bgtctrl+", U(6), 0x4DB90421); // bgtctrl+ cr6
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_bclr() {
|
||||
assert_asm!("bgelr", 0x4C800020); // bgelr
|
||||
assert_asm!("bgelr+", 0x4CA00020); // bgelr+
|
||||
assert_asm!("blelr", 0x4C810020); // blelr
|
||||
assert_asm!("bnelr", 0x4C820020); // bnelr
|
||||
assert_asm!("bnelr", U(7), 0x4C9E0020); // bnelr cr7
|
||||
assert_asm!("bltlr", 0x4D800020); // bltlr
|
||||
assert_asm!("bgtlr", 0x4D810020); // bgtlr
|
||||
assert_asm!("beqlr", 0x4D820020); // beqlr
|
||||
assert_asm!("beqlr", U(1), 0x4D860020); // beqlr cr1
|
||||
assert_asm!("blr", 0x4E800020); // blr
|
||||
assert_asm!("blrl", 0x4E800021); // blrl
|
||||
assert_asm!("bdnztlr", U(0), 0x4D000020); // bdnztlr lt
|
||||
assert_asm!("bdnzflrl", U(31), 0x4C1F0021); // bdnzflrl cr7un
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_cmpi() {
|
||||
assert_asm!("cmpi", U(6), U(0), U(31), U(0), 0x2F1F0000); // cmpi r6, 0, 31, 0
|
||||
assert_asm!("cmpwi", U(5), U(0xd00), 0x2C050D00); // cmpwi r5, 0xd00
|
||||
assert_asm!("cmpwi", U(6), U(31), U(0), 0x2F1F0000); // cmpwi r6, 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_mfspr() {
|
||||
assert_asm!("mfsrr0", U(16), 0x7E1A02A6); // mfsrr0 r16
|
||||
assert_asm!("mfspr", U(3), U(1008), 0x7C70FAA6); // mfspr r3, HID0
|
||||
assert_asm!("mfibatu", U(3), U(2), 0x7C7482A6); // mfibatu r3, 2
|
||||
assert_asm!("mfibatl", U(3), U(3), 0x7C7782A6); // mfibatl r3, 3
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_rlwimi() {
|
||||
assert_asm!("rlwimi", U(3), U(0), U(0), U(27), U(31), 0x500306FE); // rlwimi r3, r0, 0, 27, 31
|
||||
assert_asm!("rlwimi", U(3), U(0), U(5), U(21), U(26), 0x50032D74); // rlwimi r3, r0, 5, 21, 26
|
||||
assert_asm!("clrrwi.", U(0), U(0), U(0), 0x5400003F); // clrrwi. r0, r0, 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_rlwinm() {
|
||||
assert_asm!("rlwinm", U(0), U(0), U(0), U(16), U(25), 0x54000432); // rlwinm r0, r0, 0, 16, 25
|
||||
assert_asm!("rlwinm", U(9), U(0), U(12), U(8), U(19), 0x54096226); // rlwinm r9, r0, 12, 8, 19
|
||||
assert_asm!("rlwinm.", U(0), U(0), U(0), U(16), U(17), 0x54000423); // rlwinm. r0, r0, 0, 16, 17
|
||||
assert_asm!("slwi", U(5), U(31), U(2), 0x57E5103A); // slwi r5, r31, 2
|
||||
assert_asm!("extlwi", U(3), U(4), U(20), U(4), 0x54832026); // extlwi r3, r4, 20, 4
|
||||
assert_asm!("extrwi", U(3), U(4), U(20), U(1), 0x5483AB3E); // extrwi r3, r4, 20, 1
|
||||
assert_asm!("extrwi", U(0), U(0), U(2), U(2), 0x540027BE); // extrwi r0, r0, 2, 2
|
||||
assert_asm!("rlwinm", U(3), U(4), U(19), U(12), U(31), 0x54839B3E); // rlwinm r3, r4, 19, 12, 31
|
||||
assert_asm!("rotlwi", U(3), U(4), U(4), 0x5483203E); // rotlwi r3, r4, 4
|
||||
assert_asm!("rotrwi", U(3), U(4), U(4), 0x5483E03E); // rotrwi r3, r4, 4
|
||||
assert_asm!("clrlwi", U(4), U(3), U(16), 0x5464043E); // clrlwi r4, r3, 16
|
||||
assert_asm!("clrrwi", U(3), U(4), U(4), 0x54830036); // clrrwi r3, r4, 4
|
||||
assert_asm!("clrlslwi", U(4), U(3), U(31), U(1), 0x54640FBC); // clrlslwi r4, r3, 31, 1
|
||||
assert_asm!("clrlslwi", U(9), U(0), U(27), U(5), 0x54092DB4); // clrlslwi r9, r0, 27, 5
|
||||
assert_asm!("clrlslwi", U(9), U(0), U(20), U(12), 0x54096226); // clrlslwi r9, r0, 20, 12
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tw() {
|
||||
assert_asm!("tw", U(0), U(6), U(7), 0x7C063808); // tw 0, r6, r7
|
||||
assert_asm!("tweq", U(4), U(5), 0x7C842808); // tweq r4, r5
|
||||
assert_asm!("twlge", U(4), U(5), 0x7CA42808); // twlge r4, r5
|
||||
assert_asm!("trap", 0x7FE00008); // trap
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_twi() {
|
||||
assert_asm!("twi", U(0), U(0), U(0), 0x0C000000); // twi 0, r0, 0x0
|
||||
assert_asm!("twgti", U(7), S(-0x1), 0x0D07FFFF); // twgti r7, -0x1
|
||||
assert_asm!("twllei", U(4), S(-0xff), 0x0CC4FF01); // twllei r4, -0xff
|
||||
assert_asm!("twui", U(4), U(0x3), 0x0FE40003); // twui r4, 0x3
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ins_xor() {
|
||||
assert_asm!("xor", U(5), U(0), U(5), 0x7C052A78); // xor r5, r0, r5
|
||||
assert_asm!("xor.", U(7), U(9), U(10), 0x7D275279); // xor. r7, r9, r10
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
[package]
|
||||
name = "ppc750cl-py"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
authors = ["Richard Patel <me@terorie.dev>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
description = "Python bindings for PowerPC 750CL Disassembler"
|
||||
repository = "https://github.com/terorie/ppc750cl"
|
||||
|
||||
[lib]
|
||||
name = "ppc750cl"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[features]
|
||||
extension-module = ["pyo3/extension-module"]
|
||||
default = ["extension-module"]
|
||||
|
||||
[dependencies]
|
||||
pyo3 = { version = "0.16", features = ["multiple-pymethods"] }
|
||||
ppc750cl = { version = "0.2.0", path = "../disasm" }
|
|
@ -1,257 +0,0 @@
|
|||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
|
||||
use ppc750cl::formatter::FormattedIns;
|
||||
|
||||
#[pyclass]
|
||||
struct Ins(ppc750cl::Ins);
|
||||
|
||||
#[pymethods]
|
||||
impl Ins {
|
||||
#[new]
|
||||
fn new(code: u32, addr: u32) -> Self {
|
||||
Ins(ppc750cl::Ins::new(code, addr))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn code(&self) -> u32 {
|
||||
self.0.code
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn addr(&self) -> u32 {
|
||||
self.0.addr
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn opcode(&self) -> &'static str {
|
||||
self.0.op.mnemonic()
|
||||
}
|
||||
|
||||
fn __str__(&self) -> String {
|
||||
FormattedIns(self.0.clone()).to_string()
|
||||
}
|
||||
|
||||
fn fields(&self) -> Vec<(&'static str, i64)> {
|
||||
self.0
|
||||
.fields()
|
||||
.iter()
|
||||
.flat_map(|field| field.argument().map(|arg| (field.name(), arg.into())))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
#[pymethods]
|
||||
impl Ins {
|
||||
#[getter]
|
||||
fn simm(&self) -> i64 {
|
||||
self.0.field_simm() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn uimm(&self) -> i64 {
|
||||
self.0.field_uimm() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn offset(&self) -> i64 {
|
||||
self.0.field_offset() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn ps_offset(&self) -> i64 {
|
||||
self.0.field_ps_offset() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn BO(&self) -> i64 {
|
||||
self.0.field_BO() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn BI(&self) -> i64 {
|
||||
self.0.field_BI() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn BD(&self) -> i64 {
|
||||
self.0.field_BD() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn LI(&self) -> i64 {
|
||||
self.0.field_LI() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn SH(&self) -> i64 {
|
||||
self.0.field_SH() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn MB(&self) -> i64 {
|
||||
self.0.field_SH() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn ME(&self) -> i64 {
|
||||
self.0.field_SH() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn rS(&self) -> i64 {
|
||||
self.0.field_rS() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn rD(&self) -> i64 {
|
||||
self.0.field_rD() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn rA(&self) -> i64 {
|
||||
self.0.field_rA() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn rB(&self) -> i64 {
|
||||
self.0.field_rB() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn sr(&self) -> i64 {
|
||||
self.0.field_sr() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn spr(&self) -> i64 {
|
||||
self.0.field_spr() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn frS(&self) -> i64 {
|
||||
self.0.field_frS() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn frD(&self) -> i64 {
|
||||
self.0.field_frD() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn frA(&self) -> i64 {
|
||||
self.0.field_frA() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn frB(&self) -> i64 {
|
||||
self.0.field_frB() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn frC(&self) -> i64 {
|
||||
self.0.field_frC() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn crbD(&self) -> i64 {
|
||||
self.0.field_crbD() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn crbA(&self) -> i64 {
|
||||
self.0.field_crbA() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn crbB(&self) -> i64 {
|
||||
self.0.field_crbB() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn crfD(&self) -> i64 {
|
||||
self.0.field_crfD() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn crfS(&self) -> i64 {
|
||||
self.0.field_crfS() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn crm(&self) -> i64 {
|
||||
self.0.field_crm() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn ps_I(&self) -> i64 {
|
||||
self.0.field_ps_I() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn ps_IX(&self) -> i64 {
|
||||
self.0.field_ps_IX() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn ps_W(&self) -> i64 {
|
||||
self.0.field_ps_W() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn ps_WX(&self) -> i64 {
|
||||
self.0.field_ps_WX() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn ps_NB(&self) -> i64 {
|
||||
self.0.field_NB() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn tbr(&self) -> i64 {
|
||||
self.0.field_tbr() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn mtfsf_FM(&self) -> i64 {
|
||||
self.0.field_mtfsf_FM() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn mtfsf_IMM(&self) -> i64 {
|
||||
self.0.field_mtfsf_IMM() as i64
|
||||
}
|
||||
#[getter]
|
||||
fn TO(&self) -> i64 {
|
||||
self.0.field_TO() as i64
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ppc750cl::Ins> for Ins {
|
||||
fn from(ins: ppc750cl::Ins) -> Self {
|
||||
Self(ins)
|
||||
}
|
||||
}
|
||||
|
||||
#[pyclass]
|
||||
struct DisasmIterator {
|
||||
bytes: Py<PyBytes>,
|
||||
addr: u32,
|
||||
offset: u32,
|
||||
left: usize,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl DisasmIterator {
|
||||
fn __iter__(slf: PyRef<Self>) -> PyRef<DisasmIterator> {
|
||||
slf
|
||||
}
|
||||
fn __next__(mut slf: PyRefMut<Self>) -> PyResult<Option<Ins>> {
|
||||
if slf.left < 4 {
|
||||
return Ok(None);
|
||||
}
|
||||
let bytes = slf.bytes.as_ref(slf.py());
|
||||
let code = ((bytes[(slf.offset) as usize] as u32) << 24)
|
||||
| ((bytes[(slf.offset + 1) as usize] as u32) << 16)
|
||||
| ((bytes[(slf.offset + 2) as usize] as u32) << 8)
|
||||
| (bytes[(slf.offset + 3) as usize] as u32);
|
||||
slf.offset += 4;
|
||||
slf.left -= 4;
|
||||
let ins = Ins::new(code, slf.addr);
|
||||
slf.addr += 4;
|
||||
Ok(Some(ins))
|
||||
}
|
||||
}
|
||||
|
||||
#[pyfunction(code, addr, offset = "0", size = "None")]
|
||||
fn disasm_iter(
|
||||
code: &PyBytes,
|
||||
addr: u32,
|
||||
offset: u32,
|
||||
size: Option<u32>,
|
||||
) -> PyResult<DisasmIterator> {
|
||||
let left = match size {
|
||||
None => code.as_bytes().len().saturating_sub(offset as usize),
|
||||
Some(v) => v as usize,
|
||||
};
|
||||
Ok(DisasmIterator {
|
||||
bytes: code.into(),
|
||||
addr,
|
||||
offset,
|
||||
left,
|
||||
})
|
||||
}
|
||||
|
||||
#[pymodule]
|
||||
fn ppc750cl(_: Python, m: &PyModule) -> PyResult<()> {
|
||||
m.add_class::<Ins>()?;
|
||||
m.add_wrapped(wrap_pyfunction!(disasm_iter))?;
|
||||
Ok(())
|
||||
}
|
|
@ -1,13 +1,12 @@
|
|||
[package]
|
||||
name = "ppc750cl"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
edition = "2021"
|
||||
authors = ["Richard Patel <me@terorie.dev>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
authors = ["Luke Street <luke@street.dev>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Disassembler for PowerPC 750CL"
|
||||
keywords = ["powerpc", "wii", "gamecube"]
|
||||
repository = "https://github.com/terorie/ppc750cl"
|
||||
repository = "https://github.com/encounter/ppc750cl"
|
||||
|
||||
[dependencies]
|
||||
num-traits = "0.2"
|
||||
serde = "1.0"
|
||||
# Intentionally left blank.
|
||||
|
|
|
@ -0,0 +1,368 @@
|
|||
use core::{
|
||||
fmt,
|
||||
fmt::{Display, Formatter, LowerHex},
|
||||
};
|
||||
|
||||
use crate::generated::{
|
||||
Arguments, Opcode, BASE_MNEMONICS, DEFS_FUNCTIONS, SIMPLIFIED_MNEMONICS, USES_FUNCTIONS,
|
||||
};
|
||||
|
||||
/// A PowerPC 750CL instruction.
|
||||
#[derive(Default, Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Ins {
|
||||
pub code: u32,
|
||||
pub op: Opcode,
|
||||
}
|
||||
|
||||
impl Ins {
|
||||
/// Create a new instruction from its raw code.
|
||||
pub fn new(code: u32) -> Self {
|
||||
Self { code, op: Opcode::_detect(code) }
|
||||
}
|
||||
|
||||
/// Parse the instruction into a simplified mnemonic, if any match.
|
||||
pub fn simplified(self) -> SimplifiedIns {
|
||||
SimplifiedIns::new(self)
|
||||
}
|
||||
|
||||
/// Parse the instruction into its basic form.
|
||||
pub fn basic_form(self) -> SimplifiedIns {
|
||||
SimplifiedIns::basic_form(self)
|
||||
}
|
||||
|
||||
/// Returns all registers defined by the instruction.
|
||||
pub fn defs(&self) -> Arguments {
|
||||
DEFS_FUNCTIONS[self.op as usize](self)
|
||||
}
|
||||
|
||||
/// Returns all registers used by the instruction.
|
||||
pub fn uses(&self) -> Arguments {
|
||||
USES_FUNCTIONS[self.op as usize](self)
|
||||
}
|
||||
|
||||
/// Returns the relative branch offset of the instruction, if any.
|
||||
pub fn branch_offset(&self) -> Option<i32> {
|
||||
match self.op {
|
||||
Opcode::B => Some(self.field_li()),
|
||||
Opcode::Bc => Some(self.field_bd() as i32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the absolute branch destination of the instruction, if any.
|
||||
pub fn branch_dest(&self, addr: u32) -> Option<u32> {
|
||||
self.branch_offset().and_then(|offset| {
|
||||
if self.field_aa() {
|
||||
Some(offset as u32)
|
||||
} else {
|
||||
addr.checked_add_signed(offset)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the instruction is any kind of branch.
|
||||
pub fn is_branch(&self) -> bool {
|
||||
matches!(self.op, Opcode::B | Opcode::Bc | Opcode::Bcctr | Opcode::Bclr)
|
||||
}
|
||||
|
||||
/// Whether the instruction is a direct branch.
|
||||
pub fn is_direct_branch(&self) -> bool {
|
||||
matches!(self.op, Opcode::B | Opcode::Bc)
|
||||
}
|
||||
|
||||
/// Whether the instruction is an unconditional branch.
|
||||
pub fn is_unconditional_branch(&self) -> bool {
|
||||
match self.op {
|
||||
Opcode::B => true,
|
||||
Opcode::Bc | Opcode::Bcctr | Opcode::Bclr => {
|
||||
self.field_bo() == 20 && self.field_bi() == 0
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the instruction is a conditional branch.
|
||||
pub fn is_conditional_branch(&self) -> bool {
|
||||
self.is_branch() && !self.is_unconditional_branch()
|
||||
}
|
||||
|
||||
/// Whether the instruction is a branch with link. (blr)
|
||||
#[inline]
|
||||
pub fn is_blr(&self) -> bool {
|
||||
self.code == 0x4e800020
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! field_arg_no_display {
|
||||
($name:ident, $typ:ident) => {
|
||||
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
|
||||
pub struct $name(pub $typ);
|
||||
impl From<$name> for Argument {
|
||||
fn from(x: $name) -> Argument {
|
||||
Argument::$name(x)
|
||||
}
|
||||
}
|
||||
impl From<$typ> for $name {
|
||||
fn from(x: $typ) -> $name {
|
||||
$name(x)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! field_arg {
|
||||
($name:ident, $typ:ident) => {
|
||||
field_arg_no_display!($name, $typ);
|
||||
impl Display for $name {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
($name:ident, $typ:ident, $format:literal) => {
|
||||
field_arg_no_display!($name, $typ);
|
||||
impl Display for $name {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(f, $format, self.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
($name:ident, $typ:ident, $format:literal, $format_arg:expr) => {
|
||||
field_arg_no_display!($name, $typ);
|
||||
impl Display for $name {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(f, $format, $format_arg(self.0))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// General-purpose register.
|
||||
field_arg!(GPR, u8, "r{}");
|
||||
// Floating-point register (direct or paired-singles mode).
|
||||
field_arg!(FPR, u8, "f{}");
|
||||
// Segment register.
|
||||
field_arg!(SR, u8);
|
||||
// Special-purpose register.
|
||||
field_arg_no_display!(SPR, u16);
|
||||
impl Display for SPR {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self.0 {
|
||||
1 => "XER",
|
||||
8 => "LR",
|
||||
9 => "CTR",
|
||||
18 => "DSISR",
|
||||
19 => "DAR",
|
||||
22 => "DEC",
|
||||
25 => "SDR1",
|
||||
26 => "SRR0",
|
||||
27 => "SRR1",
|
||||
272 => "SPRG0",
|
||||
273 => "SPRG1",
|
||||
274 => "SPRG2",
|
||||
275 => "SPRG3",
|
||||
282 => "EAR",
|
||||
287 => "PVR",
|
||||
528 => "IBAT0U",
|
||||
529 => "IBAT0L",
|
||||
530 => "IBAT1U",
|
||||
531 => "IBAT1L",
|
||||
532 => "IBAT2U",
|
||||
533 => "IBAT2L",
|
||||
534 => "IBAT3U",
|
||||
535 => "IBAT3L",
|
||||
536 => "DBAT0U",
|
||||
537 => "DBAT0L",
|
||||
538 => "DBAT1U",
|
||||
539 => "DBAT1L",
|
||||
540 => "DBAT2U",
|
||||
541 => "DBAT2L",
|
||||
542 => "DBAT3U",
|
||||
543 => "DBAT3L",
|
||||
912 => "GQR0",
|
||||
913 => "GQR1",
|
||||
914 => "GQR2",
|
||||
915 => "GQR3",
|
||||
916 => "GQR4",
|
||||
917 => "GQR5",
|
||||
918 => "GQR6",
|
||||
919 => "GQR7",
|
||||
920 => "HID2",
|
||||
921 => "WPAR",
|
||||
922 => "DMA_U",
|
||||
923 => "DMA_L",
|
||||
936 => "UMMCR0",
|
||||
937 => "UPMC1",
|
||||
938 => "UPMC2",
|
||||
939 => "USIA",
|
||||
940 => "UMMCR1",
|
||||
941 => "UPMC3",
|
||||
942 => "UPMC4",
|
||||
943 => "USDA",
|
||||
952 => "MMCR0",
|
||||
953 => "PMC1",
|
||||
954 => "PMC2",
|
||||
955 => "SIA",
|
||||
956 => "MMCR1",
|
||||
957 => "PMC3",
|
||||
958 => "PMC4",
|
||||
959 => "SDA",
|
||||
1008 => "HID0",
|
||||
1009 => "HID1",
|
||||
1010 => "IABR",
|
||||
1013 => "DABR",
|
||||
1017 => "L2CR",
|
||||
1019 => "ICTC",
|
||||
1020 => "THRM1",
|
||||
1021 => "THRM2",
|
||||
1022 => "THRM3",
|
||||
_ => return write!(f, "{}", self.0),
|
||||
})
|
||||
}
|
||||
}
|
||||
// Condition register field.
|
||||
field_arg!(CRField, u8, "cr{}");
|
||||
// Condition register bit (index + condition case).
|
||||
field_arg_no_display!(CRBit, u8);
|
||||
impl Display for CRBit {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
let cr = self.0 >> 2;
|
||||
let cc = self.0 & 3;
|
||||
if cr != 0 {
|
||||
write!(f, "{}", CRField(cr))?;
|
||||
}
|
||||
const CR_NAMES: [&str; 4] = ["lt", "gt", "eq", "un"];
|
||||
f.write_str(CR_NAMES[cc as usize])
|
||||
}
|
||||
}
|
||||
// Paired-single graphics quantization register
|
||||
field_arg!(GQR, u8, "qr{}");
|
||||
// Unsigned immediate.
|
||||
field_arg!(Uimm, u16, "{:#x}");
|
||||
// Signed immediate.
|
||||
field_arg!(Simm, i16, "{:#x}", SignedHexLiteral);
|
||||
// Offset for indirect memory reference.
|
||||
field_arg!(Offset, i16, "{:#x}", SignedHexLiteral);
|
||||
// Branch destination.
|
||||
field_arg!(BranchDest, i32, "{:#x}", SignedHexLiteral);
|
||||
impl From<i16> for BranchDest {
|
||||
fn from(x: i16) -> BranchDest {
|
||||
BranchDest(x as i32)
|
||||
}
|
||||
}
|
||||
// Unsigned opaque argument.
|
||||
field_arg!(OpaqueU, u16);
|
||||
impl From<u8> for OpaqueU {
|
||||
fn from(x: u8) -> OpaqueU {
|
||||
OpaqueU(x as u16)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Eq, PartialEq)]
|
||||
pub enum Argument {
|
||||
#[default]
|
||||
None,
|
||||
GPR(GPR),
|
||||
FPR(FPR),
|
||||
SR(SR),
|
||||
SPR(SPR),
|
||||
CRField(CRField),
|
||||
CRBit(CRBit),
|
||||
GQR(GQR),
|
||||
Uimm(Uimm),
|
||||
Simm(Simm),
|
||||
Offset(Offset),
|
||||
BranchDest(BranchDest),
|
||||
OpaqueU(OpaqueU),
|
||||
}
|
||||
|
||||
impl Display for Argument {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Argument::None => Ok(()),
|
||||
Argument::GPR(x) => x.fmt(f),
|
||||
Argument::FPR(x) => x.fmt(f),
|
||||
Argument::SR(x) => x.fmt(f),
|
||||
Argument::SPR(x) => x.fmt(f),
|
||||
Argument::CRField(x) => x.fmt(f),
|
||||
Argument::CRBit(x) => x.fmt(f),
|
||||
Argument::GQR(x) => x.fmt(f),
|
||||
Argument::Uimm(x) => x.fmt(f),
|
||||
Argument::Simm(x) => x.fmt(f),
|
||||
Argument::Offset(x) => x.fmt(f),
|
||||
Argument::BranchDest(x) => x.fmt(f),
|
||||
Argument::OpaqueU(x) => x.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A simplified PowerPC 750CL instruction.
|
||||
pub struct SimplifiedIns {
|
||||
pub ins: Ins,
|
||||
pub mnemonic: &'static str,
|
||||
pub args: Arguments,
|
||||
}
|
||||
|
||||
impl SimplifiedIns {
|
||||
pub fn new(ins: Ins) -> Self {
|
||||
let (mnemonic, args) = SIMPLIFIED_MNEMONICS[ins.op as usize](&ins);
|
||||
Self { ins, mnemonic, args }
|
||||
}
|
||||
|
||||
pub fn basic_form(ins: Ins) -> Self {
|
||||
let (mnemonic, args) = BASE_MNEMONICS[ins.op as usize](&ins);
|
||||
Self { ins, mnemonic, args }
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for SimplifiedIns {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.mnemonic)?;
|
||||
let mut writing_offset = false;
|
||||
for (i, argument) in self.args.iter().enumerate() {
|
||||
if matches!(argument, Argument::None) {
|
||||
break;
|
||||
}
|
||||
if i == 0 {
|
||||
write!(f, " ")?;
|
||||
} else if !writing_offset {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
write!(f, "{}", argument)?;
|
||||
if let Argument::Offset(_) = argument {
|
||||
write!(f, "(")?;
|
||||
writing_offset = true;
|
||||
continue;
|
||||
}
|
||||
if writing_offset {
|
||||
write!(f, ")")?;
|
||||
writing_offset = false;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SignedHexLiteral<T>(pub T);
|
||||
|
||||
impl LowerHex for SignedHexLiteral<i16> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
if self.0 < 0 {
|
||||
write!(f, "-")?;
|
||||
LowerHex::fmt(&-(self.0 as i32), f)
|
||||
} else {
|
||||
LowerHex::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LowerHex for SignedHexLiteral<i32> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
if self.0 < 0 {
|
||||
write!(f, "-")?;
|
||||
LowerHex::fmt(&-(self.0 as i64), f)
|
||||
} else {
|
||||
LowerHex::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use crate::prelude::*;
|
||||
|
||||
pub struct FormattedIns(pub Ins);
|
||||
|
||||
impl Display for FormattedIns {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
let simple = self.0.clone().simplified();
|
||||
write!(f, "{}{}", simple.mnemonic, simple.suffix)?;
|
||||
let mut writing_offset = false;
|
||||
for (i, arg) in simple.args.iter().enumerate() {
|
||||
if i == 0 {
|
||||
write!(f, " ")?;
|
||||
}
|
||||
if i > 0 && !writing_offset {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
if let Argument::Offset(val) = arg {
|
||||
write!(f, "{}(", val)?;
|
||||
writing_offset = true;
|
||||
continue;
|
||||
} else {
|
||||
write!(f, "{}", arg)?;
|
||||
}
|
||||
if writing_offset {
|
||||
write!(f, ")")?;
|
||||
writing_offset = false;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
19292
disasm/src/generated.rs
19292
disasm/src/generated.rs
File diff suppressed because it is too large
Load Diff
|
@ -1,34 +0,0 @@
|
|||
use crate::Ins;
|
||||
|
||||
/// Returns an iterator of instructions in the given byte slice.
|
||||
pub fn disasm_iter(code: &[u8], addr: u32) -> DisasmIterator {
|
||||
DisasmIterator { code, addr }
|
||||
}
|
||||
|
||||
pub struct DisasmIterator<'a> {
|
||||
code: &'a [u8],
|
||||
addr: u32,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for DisasmIterator<'a> {
|
||||
type Item = Ins;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.code.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
let code = ((self.code[0] as u32) << 24)
|
||||
| ((self.code[1] as u32) << 16)
|
||||
| ((self.code[2] as u32) << 8)
|
||||
| (self.code[3] as u32);
|
||||
self.code = &self.code[4..];
|
||||
let addr = self.addr;
|
||||
self.addr += 4;
|
||||
Some(Ins::new(code, addr))
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let count = self.code.len() / 4;
|
||||
(count, Some(count))
|
||||
}
|
||||
}
|
|
@ -1,458 +1,9 @@
|
|||
use std::fmt::{Display, Formatter, LowerHex, UpperHex, Write};
|
||||
use std::ops::Range;
|
||||
|
||||
use num_traits::{AsPrimitive, PrimInt};
|
||||
|
||||
pub use crate::iter::{disasm_iter, DisasmIterator};
|
||||
|
||||
pub mod formatter;
|
||||
#![no_std]
|
||||
mod disasm;
|
||||
mod generated;
|
||||
mod iter;
|
||||
pub use generated::*;
|
||||
|
||||
pub mod prelude {
|
||||
pub use crate::formatter::FormattedIns;
|
||||
pub use crate::Argument;
|
||||
pub use crate::Field::*;
|
||||
pub use crate::Ins;
|
||||
pub use crate::Opcode::*;
|
||||
pub use crate::SimplifiedIns;
|
||||
pub use crate::{
|
||||
Bit, BranchDest, CRBit, CRField, Offset, OpaqueU, Simm, Uimm, FPR, GPR, GQR, SPR, SR,
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! field_arg_no_display {
|
||||
($name:ident, $typ:ident) => {
|
||||
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
|
||||
pub struct $name(pub $typ);
|
||||
impl std::convert::From<$name> for Argument {
|
||||
fn from(x: $name) -> Argument {
|
||||
Argument::$name(x)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! field_arg {
|
||||
($name:ident, $typ:ident) => {
|
||||
field_arg_no_display!($name, $typ);
|
||||
impl Display for $name {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
($name:ident, $typ:ident, $format:literal) => {
|
||||
field_arg_no_display!($name, $typ);
|
||||
impl Display for $name {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, $format, self.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
($name:ident, $typ:ident, $format:literal, $format_arg:expr) => {
|
||||
field_arg_no_display!($name, $typ);
|
||||
impl Display for $name {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, $format, $format_arg(self.0))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn bit(x: u32, idx: usize) -> bool {
|
||||
((x >> (32 - idx - 1)) & 1) == 1
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn bits<F>(x: u32, range: Range<usize>) -> F
|
||||
where
|
||||
F: 'static + std::marker::Copy,
|
||||
u32: AsPrimitive<F>,
|
||||
{
|
||||
let masked: u32 = (x >> (32 - range.end)) & ((1 << range.len()) - 1);
|
||||
masked.as_()
|
||||
}
|
||||
|
||||
// https://stackoverflow.com/questions/44711012/how-do-i-format-a-signed-integer-to-a-sign-aware-hexadecimal-representation
|
||||
struct ReallySigned<N: PrimInt>(N);
|
||||
|
||||
impl<N: PrimInt> LowerHex for ReallySigned<N> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
let num = self.0.to_i32().unwrap();
|
||||
let prefix = if f.alternate() { "0x" } else { "" };
|
||||
let bare_hex = format!("{:x}", num.abs());
|
||||
f.pad_integral(num >= 0, prefix, &bare_hex)
|
||||
}
|
||||
}
|
||||
|
||||
impl<N: PrimInt> UpperHex for ReallySigned<N> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
let num = self.0.to_i32().unwrap();
|
||||
let prefix = if f.alternate() { "0x" } else { "" };
|
||||
let bare_hex = format!("{:X}", num.abs());
|
||||
f.pad_integral(num >= 0, prefix, &bare_hex)
|
||||
}
|
||||
}
|
||||
|
||||
// General-purpose register.
|
||||
field_arg!(GPR, u8, "r{}");
|
||||
// Floating-point register (direct or paired-singles mode).
|
||||
field_arg!(FPR, u8, "f{}");
|
||||
// Segment register.
|
||||
field_arg!(SR, u8);
|
||||
// Special-purpose register.
|
||||
field_arg_no_display!(SPR, u16);
|
||||
impl Display for SPR {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self.0 {
|
||||
1 => "XER",
|
||||
8 => "LR",
|
||||
9 => "CTR",
|
||||
18 => "DSISR",
|
||||
19 => "DAR",
|
||||
22 => "DEC",
|
||||
25 => "SDR1",
|
||||
26 => "SRR0",
|
||||
27 => "SRR1",
|
||||
272 => "SPRG0",
|
||||
273 => "SPRG1",
|
||||
274 => "SPRG2",
|
||||
275 => "SPRG3",
|
||||
282 => "EAR",
|
||||
287 => "PVR",
|
||||
528 => "IBAT0U",
|
||||
529 => "IBAT0L",
|
||||
530 => "IBAT1U",
|
||||
531 => "IBAT1L",
|
||||
532 => "IBAT2U",
|
||||
533 => "IBAT2L",
|
||||
534 => "IBAT3U",
|
||||
535 => "IBAT3L",
|
||||
536 => "DBAT0U",
|
||||
537 => "DBAT0L",
|
||||
538 => "DBAT1U",
|
||||
539 => "DBAT1L",
|
||||
540 => "DBAT2U",
|
||||
541 => "DBAT2L",
|
||||
542 => "DBAT3U",
|
||||
543 => "DBAT3L",
|
||||
912 => "GQR0",
|
||||
913 => "GQR1",
|
||||
914 => "GQR2",
|
||||
915 => "GQR3",
|
||||
916 => "GQR4",
|
||||
917 => "GQR5",
|
||||
918 => "GQR6",
|
||||
919 => "GQR7",
|
||||
920 => "HID2",
|
||||
921 => "WPAR",
|
||||
922 => "DMA_U",
|
||||
923 => "DMA_L",
|
||||
936 => "UMMCR0",
|
||||
937 => "UPMC1",
|
||||
938 => "UPMC2",
|
||||
939 => "USIA",
|
||||
940 => "UMMCR1",
|
||||
941 => "UPMC3",
|
||||
942 => "UPMC4",
|
||||
943 => "USDA",
|
||||
952 => "MMCR0",
|
||||
953 => "PMC1",
|
||||
954 => "PMC2",
|
||||
955 => "SIA",
|
||||
956 => "MMCR1",
|
||||
957 => "PMC3",
|
||||
958 => "PMC4",
|
||||
959 => "SDA",
|
||||
1008 => "HID0",
|
||||
1009 => "HID1",
|
||||
1010 => "IABR",
|
||||
1013 => "DABR",
|
||||
1017 => "L2CR",
|
||||
1019 => "ICTC",
|
||||
1020 => "THRM1",
|
||||
1021 => "THRM2",
|
||||
1022 => "THRM3",
|
||||
_ => return write!(f, "{}", self.0),
|
||||
})
|
||||
}
|
||||
}
|
||||
// Condition register field.
|
||||
field_arg!(CRField, u8, "cr{}");
|
||||
// Condition register bit (index + condition case).
|
||||
field_arg_no_display!(CRBit, u8);
|
||||
impl Display for CRBit {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
let cr = self.0 >> 2;
|
||||
let cc = self.0 & 3;
|
||||
if cr != 0 {
|
||||
write!(f, "{}", CRField(cr))?;
|
||||
}
|
||||
const CR_NAMES: [&str; 4] = ["lt", "gt", "eq", "un"];
|
||||
f.write_str(CR_NAMES[cc as usize])
|
||||
}
|
||||
}
|
||||
// Paired-single graphics quantization register
|
||||
field_arg!(GQR, u8, "qr{}");
|
||||
// Unsigned immediate.
|
||||
field_arg!(Uimm, u16, "{:#x}");
|
||||
// Signed immediate.
|
||||
field_arg!(Simm, i16, "{:#x}", ReallySigned);
|
||||
// Offset for indirect memory reference.
|
||||
field_arg!(Offset, i16, "{:#x}", ReallySigned);
|
||||
// Branch destination.
|
||||
field_arg!(BranchDest, i32, "{:#x}", ReallySigned);
|
||||
// Opaque zero or one argument.
|
||||
field_arg_no_display!(Bit, bool);
|
||||
impl Display for Bit {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_char(if self.0 { '1' } else { '0' })
|
||||
}
|
||||
}
|
||||
// Unsigned opaque argument.
|
||||
field_arg!(OpaqueU, u32);
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub enum Argument {
|
||||
GPR(GPR),
|
||||
FPR(FPR),
|
||||
SR(SR),
|
||||
SPR(SPR),
|
||||
CRField(CRField),
|
||||
CRBit(CRBit),
|
||||
GQR(GQR),
|
||||
Uimm(Uimm),
|
||||
Simm(Simm),
|
||||
Offset(Offset),
|
||||
BranchDest(BranchDest),
|
||||
Bit(Bit),
|
||||
OpaqueU(OpaqueU),
|
||||
}
|
||||
|
||||
impl Display for Argument {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Argument::GPR(x) => x.fmt(f),
|
||||
Argument::FPR(x) => x.fmt(f),
|
||||
Argument::SR(x) => x.fmt(f),
|
||||
Argument::SPR(x) => x.fmt(f),
|
||||
Argument::CRField(x) => x.fmt(f),
|
||||
Argument::CRBit(x) => x.fmt(f),
|
||||
Argument::GQR(x) => x.fmt(f),
|
||||
Argument::Uimm(x) => x.fmt(f),
|
||||
Argument::Simm(x) => x.fmt(f),
|
||||
Argument::Offset(x) => x.fmt(f),
|
||||
Argument::BranchDest(x) => x.fmt(f),
|
||||
Argument::Bit(x) => x.fmt(f),
|
||||
Argument::OpaqueU(x) => x.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Argument> for i64 {
|
||||
fn from(arg: Argument) -> Self {
|
||||
match arg {
|
||||
Argument::GPR(x) => x.0 as i64,
|
||||
Argument::FPR(x) => x.0 as i64,
|
||||
Argument::SR(x) => x.0 as i64,
|
||||
Argument::SPR(x) => x.0 as i64,
|
||||
Argument::CRField(x) => x.0 as i64,
|
||||
Argument::CRBit(x) => x.0 as i64,
|
||||
Argument::GQR(x) => x.0 as i64,
|
||||
Argument::Uimm(x) => x.0 as i64,
|
||||
Argument::Simm(x) => x.0 as i64,
|
||||
Argument::Offset(x) => x.0 as i64,
|
||||
Argument::BranchDest(x) => x.0 as i64,
|
||||
Argument::Bit(x) => x.0 as i64,
|
||||
Argument::OpaqueU(x) => x.0 as i64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryInto<Argument> for &Field {
|
||||
type Error = ();
|
||||
fn try_into(self) -> Result<Argument, Self::Error> {
|
||||
self.argument().ok_or(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Opcode {
|
||||
/// Detects the opcode of a machine code instruction.
|
||||
pub fn detect(code: u32) -> Self {
|
||||
Self::_detect(code) // auto-generated
|
||||
}
|
||||
|
||||
/// Prints the basic mnemonic of an opcode.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
self._mnemonic() // auto-generated
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Opcode {
|
||||
fn default() -> Self {
|
||||
Opcode::Illegal
|
||||
}
|
||||
}
|
||||
|
||||
impl std::string::ToString for Opcode {
|
||||
fn to_string(&self) -> String {
|
||||
let mnemonic = self.mnemonic();
|
||||
mnemonic.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// A PowerPC 750CL instruction.
|
||||
#[derive(Default, Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Ins {
|
||||
pub code: u32,
|
||||
pub addr: u32,
|
||||
pub op: Opcode,
|
||||
}
|
||||
|
||||
impl Ins {
|
||||
const BLR: u32 = 0x4e800020;
|
||||
|
||||
/// Constructs an instruction from the given machine code and address.
|
||||
pub fn new(code: u32, addr: u32) -> Self {
|
||||
Self {
|
||||
code,
|
||||
addr,
|
||||
op: Opcode::detect(code),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the simplified representation of an instruction.
|
||||
pub fn simplified(self) -> SimplifiedIns {
|
||||
self._simplified() // auto-generated
|
||||
}
|
||||
|
||||
/// Gets the fields of an instruction.
|
||||
pub fn fields(&self) -> Vec<Field> {
|
||||
self._fields() // auto-generated
|
||||
}
|
||||
|
||||
/// Gets the suffix of an instruction mnemonic.
|
||||
pub fn suffix(&self) -> String {
|
||||
self._suffix() // auto-generated
|
||||
}
|
||||
|
||||
/// Gets the defs of an instruction.
|
||||
pub fn defs(&self) -> Vec<Field> {
|
||||
self._defs() // auto-generated
|
||||
}
|
||||
|
||||
/// Gets the uses of an instruction.
|
||||
pub fn uses(&self) -> Vec<Field> {
|
||||
self._uses() // auto-generated
|
||||
}
|
||||
|
||||
/// Gets the given bit from the machine code instruction.
|
||||
pub fn bit(&self, idx: usize) -> bool {
|
||||
bit(self.code, idx)
|
||||
}
|
||||
|
||||
/// Gets the given range of btis from the machine code instruction.
|
||||
pub fn bits(&self, range: Range<usize>) -> u32 {
|
||||
bits(self.code, range)
|
||||
}
|
||||
|
||||
pub fn branch_offset(&self) -> Option<i32> {
|
||||
match self.op {
|
||||
Opcode::B => Some(self.field_LI() as i32),
|
||||
Opcode::Bc => Some(self.field_BD() as i32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn branch_dest(&self) -> Option<u32> {
|
||||
self.branch_offset().and_then(|offset| {
|
||||
if self.field_AA() {
|
||||
Some(offset as u32)
|
||||
} else if offset < 0 {
|
||||
self.addr.checked_sub((-offset) as u32)
|
||||
} else {
|
||||
self.addr.checked_add(offset as u32)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_branch(&self) -> bool {
|
||||
matches!(
|
||||
self.op,
|
||||
Opcode::B | Opcode::Bc | Opcode::Bcctr | Opcode::Bclr
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_direct_branch(&self) -> bool {
|
||||
matches!(self.op, Opcode::B | Opcode::Bc)
|
||||
}
|
||||
|
||||
pub fn is_unconditional_branch(&self) -> bool {
|
||||
match self.op {
|
||||
Opcode::B => true,
|
||||
Opcode::Bc | Opcode::Bcctr | Opcode::Bclr => {
|
||||
self.field_BO() == 20 && self.field_BI() == 0
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_conditional_branch(&self) -> bool {
|
||||
self.is_branch() && !self.is_unconditional_branch()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_blr(&self) -> bool {
|
||||
// self.op == Opcode::Bclr && self.is_unconditional_branch() && !self.field_LK()
|
||||
self.code == Ins::BLR
|
||||
}
|
||||
}
|
||||
|
||||
/// A simplified PowerPC 750CL instruction.
|
||||
pub struct SimplifiedIns {
|
||||
pub ins: Ins,
|
||||
pub mnemonic: &'static str,
|
||||
pub suffix: String,
|
||||
pub args: Vec<Argument>,
|
||||
}
|
||||
|
||||
impl Display for SimplifiedIns {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}{} ", self.mnemonic, self.suffix)?;
|
||||
let mut writing_offset = false;
|
||||
for (i, argument) in self.args.iter().enumerate() {
|
||||
write!(f, "{}", argument)?;
|
||||
if let Argument::Offset(_) = argument {
|
||||
write!(f, "(")?;
|
||||
writing_offset = true;
|
||||
continue;
|
||||
}
|
||||
if writing_offset {
|
||||
write!(f, ")")?;
|
||||
writing_offset = false;
|
||||
}
|
||||
if i != self.args.len() - 1 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SimplifiedIns {
|
||||
pub fn basic_form(ins: Ins) -> Self {
|
||||
Self {
|
||||
mnemonic: ins.op.mnemonic(),
|
||||
suffix: ins.suffix(),
|
||||
args: ins
|
||||
.fields()
|
||||
.iter()
|
||||
.flat_map(|field| field.argument())
|
||||
.collect(),
|
||||
ins,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub use disasm::{
|
||||
Argument, BranchDest, CRBit, CRField, Ins, Offset, OpaqueU, Simm, SimplifiedIns, Uimm, FPR,
|
||||
GPR, GQR, SPR, SR,
|
||||
};
|
||||
pub use generated::{Arguments, Opcode};
|
||||
|
|
|
@ -1,12 +1,22 @@
|
|||
use ppc750cl::prelude::*;
|
||||
use ppc750cl::{Argument, Ins, Opcode, SimplifiedIns, FPR, GPR};
|
||||
|
||||
macro_rules! assert_asm {
|
||||
($ins:ident, $disasm:literal) => {{
|
||||
assert_eq!(format!("{}", FormattedIns($ins)), $disasm)
|
||||
assert_eq!(format!("{}", SimplifiedIns::new($ins)), $disasm)
|
||||
}};
|
||||
($code:literal, $disasm:literal) => {{
|
||||
let ins = Ins::new($code, 0x8000_0000);
|
||||
assert_eq!(format!("{}", FormattedIns(ins)), $disasm)
|
||||
let ins = Ins::new($code);
|
||||
assert_eq!(format!("{}", SimplifiedIns::new(ins)), $disasm)
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! assert_basic {
|
||||
($ins:ident, $disasm:literal) => {{
|
||||
assert_eq!(format!("{}", SimplifiedIns::basic_form($ins)), $disasm)
|
||||
}};
|
||||
($code:literal, $disasm:literal) => {{
|
||||
let ins = Ins::new($code);
|
||||
assert_eq!(format!("{}", SimplifiedIns::basic_form(ins)), $disasm)
|
||||
}};
|
||||
}
|
||||
|
||||
|
@ -20,9 +30,9 @@ fn test_ins_add() {
|
|||
|
||||
#[test]
|
||||
fn test_ins_addc() {
|
||||
let ins = Ins::new(0x7c002014, 0x8000_0000u32);
|
||||
assert_eq!(ins.op, Addc);
|
||||
assert_eq!(ins.fields(), vec![rD(GPR(0)), rA(GPR(0)), rB(GPR(4))]);
|
||||
let ins = Ins::new(0x7c002014);
|
||||
assert_eq!(ins.op, Opcode::Addc);
|
||||
// assert_eq!(ins.fields(), vec![rD(GPR(0)), rA(GPR(0)), rB(GPR(4))]);
|
||||
assert_asm!(ins, "addc r0, r0, r4");
|
||||
assert_asm!(0x7C432014, "addc r2, r3, r4");
|
||||
assert_asm!(0x7CE62815, "addc. r7, r6, r5");
|
||||
|
@ -32,14 +42,20 @@ fn test_ins_addc() {
|
|||
|
||||
#[test]
|
||||
fn test_ins_addi() {
|
||||
let ins = Ins::new(0x38010140, 0x8000_0000u32);
|
||||
assert_eq!(ins.op, Addi);
|
||||
let ins = Ins::new(0x38010140);
|
||||
assert_eq!(ins.op, Opcode::Addi);
|
||||
// assert_eq!(
|
||||
// ins.fields(),
|
||||
// vec![rD(GPR(0)), rA(GPR(1)), simm(Simm(0x140))]
|
||||
// );
|
||||
assert_eq!(
|
||||
ins.fields(),
|
||||
vec![rD(GPR(0)), rA(GPR(1)), simm(Simm(0x140))]
|
||||
ins.defs(),
|
||||
[Argument::GPR(GPR(0)), Argument::None, Argument::None, Argument::None, Argument::None]
|
||||
);
|
||||
assert_eq!(
|
||||
ins.uses(),
|
||||
[Argument::GPR(GPR(1)), Argument::None, Argument::None, Argument::None, Argument::None]
|
||||
);
|
||||
assert_eq!(ins.defs(), vec![rD(GPR(0))]);
|
||||
assert_eq!(ins.uses(), vec![rA(GPR(1))]);
|
||||
assert_asm!(ins, "addi r0, r1, 0x140");
|
||||
|
||||
assert_asm!(0x38010008, "addi r0, r1, 0x8");
|
||||
|
@ -48,6 +64,7 @@ fn test_ins_addi() {
|
|||
assert_asm!(0x38010140, "addi r0, r1, 0x140");
|
||||
assert_asm!(0x38049000, "subi r0, r4, 0x7000");
|
||||
assert_asm!(0x38a00000, "li r5, 0x0");
|
||||
assert_basic!(0x38a00000, "addi r5, r0, 0x0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -710,20 +727,26 @@ fn test_ins_psq_lu() {
|
|||
|
||||
#[test]
|
||||
fn test_ins_psq_lx() {
|
||||
let ins = Ins::new(0x1000000C, 0x8000_0000u32);
|
||||
assert_eq!(ins.op, PsqLx);
|
||||
let ins = Ins::new(0x1000000C);
|
||||
assert_eq!(ins.op, Opcode::PsqLx);
|
||||
// assert_eq!(
|
||||
// ins.fields(),
|
||||
// vec![
|
||||
// frD(FPR(0)),
|
||||
// rA(GPR(0)),
|
||||
// rB(GPR(0)),
|
||||
// ps_WX(OpaqueU(0)),
|
||||
// ps_IX(GQR(0)),
|
||||
// ]
|
||||
// );
|
||||
assert_eq!(
|
||||
ins.fields(),
|
||||
vec![
|
||||
frD(FPR(0)),
|
||||
rA(GPR(0)),
|
||||
rB(GPR(0)),
|
||||
ps_WX(OpaqueU(0)),
|
||||
ps_IX(GQR(0)),
|
||||
]
|
||||
ins.defs(),
|
||||
[Argument::FPR(FPR(0)), Argument::None, Argument::None, Argument::None, Argument::None]
|
||||
);
|
||||
assert_eq!(
|
||||
ins.uses(),
|
||||
[Argument::None, Argument::GPR(GPR(0)), Argument::None, Argument::None, Argument::None]
|
||||
);
|
||||
assert_eq!(ins.defs(), vec![frD(FPR(0))]);
|
||||
assert_eq!(ins.uses(), vec![rB(GPR(0))]);
|
||||
|
||||
assert_asm!(0x1000000C, "psq_lx f0, r0, r0, 0, qr0");
|
||||
}
|
||||
|
@ -885,6 +908,7 @@ fn test_ins_rlwimi() {
|
|||
fn test_ins_rlwinm() {
|
||||
assert_asm!(0x54000423, "rlwinm. r0, r0, 0, 16, 17");
|
||||
assert_asm!(0x54000432, "rlwinm r0, r0, 0, 16, 25");
|
||||
assert_basic!(0x54096226, "rlwinm r9, r0, 12, 8, 19");
|
||||
|
||||
// mnemonics
|
||||
assert_asm!(0x57E5103A, "slwi r5, r31, 2");
|
||||
|
|
|
@ -1,13 +0,0 @@
|
|||
[package]
|
||||
name = "dol"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
authors = ["Richard Patel <me@terorie.dev>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
description = "Deserializer for the DOL executable format"
|
||||
repository = "https://github.com/terorie/ppc750cl"
|
||||
|
||||
[dependencies]
|
||||
bincode = "1.3"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
thiserror = "1.0"
|
237
dol/src/lib.rs
237
dol/src/lib.rs
|
@ -1,237 +0,0 @@
|
|||
use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
use bincode::Options;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
/// A loaded DOL executable.
|
||||
pub struct Dol {
|
||||
pub header: DolHeader,
|
||||
pub memory: Vec<u8>,
|
||||
pub memory_offset: u32,
|
||||
}
|
||||
|
||||
/// An error that can be raised during DOL parsing.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("{0}")]
|
||||
BincodeError(bincode::Error),
|
||||
#[error("{0}")]
|
||||
IOError(std::io::Error),
|
||||
#[error("No sections in DOL")]
|
||||
NoSections,
|
||||
#[error("Overlapping sections: {0:8>X} {1:8>X}")]
|
||||
OverlappingSections(u32, u32),
|
||||
#[error("Section sizes too large")]
|
||||
SectionsTooLarge,
|
||||
#[error("Attempted to access {0:08X} past DOL bounds")]
|
||||
OutOfBounds(u32),
|
||||
}
|
||||
|
||||
impl From<bincode::Error> for Error {
|
||||
fn from(e: bincode::Error) -> Self {
|
||||
Self::BincodeError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
Self::IOError(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of a DOL parsing.
|
||||
pub type Result<V> = std::result::Result<V, Error>;
|
||||
|
||||
impl Dol {
|
||||
/// Reads a DOL executable from a `Reader`.
|
||||
pub fn read_from<R>(mut r: R) -> Result<Self>
|
||||
where
|
||||
R: Read + Seek,
|
||||
{
|
||||
// Read header.
|
||||
let header_data = DolHeaderData::read_from(&mut r)?;
|
||||
let header: DolHeader = (&header_data).into();
|
||||
Dol::read_with_header(r, header)
|
||||
}
|
||||
|
||||
/// Reads a DOL body from a `Reader` given a header.
|
||||
pub fn read_with_header<R>(mut r: R, header: DolHeader) -> Result<Self>
|
||||
where
|
||||
R: Read + Seek,
|
||||
{
|
||||
let dol_start = r.stream_position()? - DolHeaderData::SERIALIZED_SIZE;
|
||||
if header.sections.is_empty() {
|
||||
return Err(Error::NoSections);
|
||||
}
|
||||
/*
|
||||
// Verify that sections are not overlapping.
|
||||
let mut end_target_addr = 0u32;
|
||||
for section in &header.sections {
|
||||
if section.target < end_target_addr {
|
||||
return Err(Error::OverlappingSections(end_target_addr, section.target));
|
||||
}
|
||||
end_target_addr = section.target + section.size
|
||||
}
|
||||
*/
|
||||
// Remember the memory offset of the first section.
|
||||
// Then shift all sections to the beginning of memory.
|
||||
let memory_offset = header.sections[0].target;
|
||||
// Get the size of all sections combined.
|
||||
let mut total_size = 0usize;
|
||||
for section in &header.sections {
|
||||
if let Some(sum) = total_size.checked_add(section.size as usize) {
|
||||
total_size = sum;
|
||||
} else {
|
||||
return Err(Error::SectionsTooLarge);
|
||||
}
|
||||
}
|
||||
// Cannot be larger than 24 MiB.
|
||||
if total_size > 0x180_0000 {
|
||||
return Err(Error::SectionsTooLarge);
|
||||
}
|
||||
// Create memory.
|
||||
let mut memory = vec![0u8; total_size];
|
||||
// Read sections into memory.
|
||||
for section in &header.sections {
|
||||
if section.kind == DolSectionType::Bss {
|
||||
continue;
|
||||
}
|
||||
r.seek(SeekFrom::Start(dol_start + section.offset as u64))?;
|
||||
let mem_start = (section.target - memory_offset) as usize;
|
||||
let mem_end = mem_start + section.size as usize;
|
||||
r.read_exact(&mut memory[mem_start..mem_end])?;
|
||||
}
|
||||
Ok(Self {
|
||||
header,
|
||||
memory,
|
||||
memory_offset,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn section_data(&self, section: &DolSection) -> &[u8] {
|
||||
self.virtual_data_at(section.target, section.size).unwrap()
|
||||
}
|
||||
|
||||
/// Returns a slice of DOL data. Does not support bss.
|
||||
pub fn virtual_data_at(&self, virtual_addr: u32, read_len: u32) -> Result<&[u8]> {
|
||||
if virtual_addr < self.memory_offset {
|
||||
return Err(Error::OutOfBounds(virtual_addr));
|
||||
}
|
||||
|
||||
let offset = (virtual_addr - self.memory_offset) as usize;
|
||||
if offset + (read_len as usize) < self.memory.len() {
|
||||
Ok(&self.memory[offset..offset + (read_len as usize)])
|
||||
} else {
|
||||
Err(Error::OutOfBounds(virtual_addr + read_len))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads bytes into a destination buffer given a virtual address.
|
||||
pub fn virtual_read(&self, data: &mut [u8], virtual_addr: u32) -> Result<()> {
|
||||
if virtual_addr < self.memory_offset {
|
||||
return Err(Error::OutOfBounds(virtual_addr));
|
||||
}
|
||||
|
||||
let offset = (virtual_addr - self.memory_offset) as usize;
|
||||
let read_len = data.len();
|
||||
if offset + read_len < self.memory.len() {
|
||||
data.copy_from_slice(&self.memory[offset..offset + data.len()]);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::OutOfBounds(virtual_addr + (read_len as u32)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
pub enum DolSectionType {
|
||||
Text,
|
||||
Data,
|
||||
Bss,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DolSection {
|
||||
pub kind: DolSectionType,
|
||||
pub index: usize,
|
||||
pub offset: u32,
|
||||
pub target: u32,
|
||||
pub size: u32,
|
||||
}
|
||||
|
||||
pub struct DolHeader {
|
||||
pub sections: Vec<DolSection>,
|
||||
pub entry_point: u32,
|
||||
}
|
||||
|
||||
impl From<&DolHeaderData> for DolHeader {
|
||||
fn from(header: &DolHeaderData) -> Self {
|
||||
let mut sections = Vec::with_capacity(DolHeaderData::SECTION_COUNT);
|
||||
for i in 0..DolHeaderData::SECTION_COUNT {
|
||||
let kind = if i < 7 {
|
||||
DolSectionType::Text
|
||||
} else {
|
||||
DolSectionType::Data
|
||||
};
|
||||
|
||||
if header.section_sizes[i] > 0 {
|
||||
sections.push(DolSection {
|
||||
kind,
|
||||
index: i,
|
||||
offset: header.section_offsets[i],
|
||||
target: header.section_targets[i],
|
||||
size: header.section_sizes[i],
|
||||
});
|
||||
}
|
||||
}
|
||||
if header.bss_target > 0 {
|
||||
sections.push(DolSection {
|
||||
kind: DolSectionType::Bss,
|
||||
index: 0,
|
||||
offset: 0,
|
||||
target: header.bss_target,
|
||||
size: header.bss_size,
|
||||
})
|
||||
}
|
||||
// Sort sections by target address to prepare them for mapping.
|
||||
sections.sort_by_key(|s| s.target);
|
||||
Self {
|
||||
sections,
|
||||
entry_point: header.entry_point,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DolHeader {
|
||||
pub fn section_at(&self, addr: u32) -> Option<&DolSection> {
|
||||
self.sections
|
||||
.iter()
|
||||
.find(|§ion| (section.target..(section.target + section.size)).contains(&addr))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct DolHeaderData {
|
||||
pub section_offsets: [u32; Self::SECTION_COUNT],
|
||||
pub section_targets: [u32; Self::SECTION_COUNT],
|
||||
pub section_sizes: [u32; Self::SECTION_COUNT],
|
||||
pub bss_target: u32,
|
||||
pub bss_size: u32,
|
||||
pub entry_point: u32,
|
||||
pub padding: [u8; 0x1c],
|
||||
}
|
||||
|
||||
impl DolHeaderData {
|
||||
const SECTION_COUNT: usize = 18;
|
||||
const SERIALIZED_SIZE: u64 = 0x100;
|
||||
|
||||
/// Reads the DOL header from a `Reader`.
|
||||
pub fn read_from<R: Read + Seek>(mut r: R) -> bincode::Result<Self> {
|
||||
bincode::DefaultOptions::new()
|
||||
.with_big_endian()
|
||||
.allow_trailing_bytes()
|
||||
.with_fixint_encoding()
|
||||
.deserialize_from(&mut r)
|
||||
}
|
||||
}
|
|
@ -1,16 +0,0 @@
|
|||
[package]
|
||||
name = "ppc750cl-flow-graph"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
authors = ["riidefi <riidefi@rii.dev>", "Richard Patel <me@terorie.dev>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
description = "Control flow graph analysis for PowerPC 750CL"
|
||||
repository = "https://github.com/terorie/ppc750cl"
|
||||
|
||||
[dependencies]
|
||||
clap = "3"
|
||||
dol = { version = "0.1.0", path = "../dol" }
|
||||
itertools = "0.10"
|
||||
parse_int = "0.6"
|
||||
petgraph = "0.6"
|
||||
ppc750cl = { version = "0.2.0", path = "../disasm" }
|
|
@ -1,178 +0,0 @@
|
|||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::ops::{Index, Range};
|
||||
|
||||
use itertools::Itertools;
|
||||
use petgraph::algo::dominators::Dominators;
|
||||
use petgraph::graph::{DefaultIx, NodeIndex};
|
||||
use petgraph::Graph;
|
||||
|
||||
use ppc750cl::formatter::FormattedIns;
|
||||
use ppc750cl::{Ins, Opcode};
|
||||
|
||||
use crate::slices::{BasicSlices, CodeIdx};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct BasicBlock<'a> {
|
||||
pub range: Range<CodeIdx>,
|
||||
pub code: &'a [Ins],
|
||||
pub data_refs: HashMap<CodeIdx, u32>,
|
||||
}
|
||||
|
||||
impl<'a> PartialEq for BasicBlock<'a> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.range == other.range
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Eq for BasicBlock<'a> {}
|
||||
|
||||
impl<'a> Hash for BasicBlock<'a> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.range.hash(state)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> BasicBlock<'a> {
|
||||
pub fn from_code_slice(range: Range<CodeIdx>, complete_code: &'a [Ins]) -> BasicBlock {
|
||||
let start_idx = complete_code.first().unwrap().addr / 4;
|
||||
assert!(start_idx <= range.start);
|
||||
let offset = (range.start - start_idx) as usize;
|
||||
let code = &complete_code[offset..(offset + (range.len() as usize))];
|
||||
BasicBlock {
|
||||
range,
|
||||
code,
|
||||
data_refs: Self::detect_data_refs(code),
|
||||
}
|
||||
}
|
||||
|
||||
/// Very simple algorithm to detect data references.
|
||||
fn detect_data_refs(code: &[Ins]) -> HashMap<CodeIdx, u32> {
|
||||
let mut defs = HashMap::<u8, u16>::new();
|
||||
let mut data_refs = HashMap::<CodeIdx, u32>::new();
|
||||
for ins in code {
|
||||
match ins.op {
|
||||
Opcode::Addis => {
|
||||
if ins.field_rA() == 0 {
|
||||
// lis
|
||||
defs.insert(ins.field_rD() as u8, ins.field_uimm() as u16);
|
||||
} else {
|
||||
defs.remove(&(ins.field_rD() as u8));
|
||||
}
|
||||
}
|
||||
Opcode::Addi => {
|
||||
if let Some(hi) = defs.get(&(ins.field_rA() as u8)) {
|
||||
data_refs.insert(
|
||||
ins.addr / 4,
|
||||
((*hi as u32) << 16) + (ins.field_uimm() as u32),
|
||||
);
|
||||
}
|
||||
defs.remove(&(ins.field_rD() as u8));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
data_refs
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Display for BasicBlock<'a> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:0>#8x}", self.range.start * 4)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Debug for BasicBlock<'a> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
writeln!(
|
||||
f,
|
||||
"// {:0>#8x}..{:0>#8x}",
|
||||
self.range.start * 4,
|
||||
self.range.end * 4
|
||||
)?;
|
||||
for ins in self.code {
|
||||
writeln!(f, "{}", FormattedIns(ins.clone()))?;
|
||||
if let Some(addr) = self.data_refs.get(&(ins.addr / 4)) {
|
||||
writeln!(f, " ref: {:0>#8x}", addr)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A control-flow graph of a function.
|
||||
pub struct FlowGraph<'a> {
|
||||
pub graph: Graph<BasicBlock<'a>, ()>,
|
||||
pub root_idx: NodeIndex,
|
||||
}
|
||||
|
||||
impl<'a> FlowGraph<'a> {
|
||||
/// Creates a control-flow graph from basic slices.
|
||||
pub fn from_basic_slices(slices: &BasicSlices, code: &'a [Ins]) -> Self {
|
||||
assert!(!code.is_empty(), "Attempt to create empty flow graph");
|
||||
// Walk set cuts and create basic blocks.
|
||||
let mut graph = Graph::new();
|
||||
let mut node_by_addr = BTreeMap::<u32, NodeIndex<DefaultIx>>::new();
|
||||
let mut block_start: CodeIdx = code[0].addr / 4;
|
||||
for cut in &slices.cuts {
|
||||
if *cut > block_start {
|
||||
node_by_addr.insert(
|
||||
block_start,
|
||||
graph.add_node(BasicBlock::from_code_slice(block_start..*cut, code)),
|
||||
);
|
||||
}
|
||||
block_start = *cut;
|
||||
}
|
||||
// Last block.
|
||||
let func_end: CodeIdx = (code.last().unwrap().addr / 4) + 1;
|
||||
if func_end > block_start {
|
||||
node_by_addr.insert(
|
||||
block_start,
|
||||
graph.add_node(BasicBlock::from_code_slice(block_start..func_end, code)),
|
||||
);
|
||||
}
|
||||
// Walk set of branches and connect graph.
|
||||
for branch in &slices.branches {
|
||||
let src_node_idx = match node_by_addr.range(..branch.0 + 1).last() {
|
||||
None => continue,
|
||||
Some(idx) => *idx.1,
|
||||
};
|
||||
debug_assert!(graph[src_node_idx].range.contains(&branch.0));
|
||||
let dst_node_idx = match node_by_addr.range(..branch.1 + 1).last() {
|
||||
None => continue,
|
||||
Some(idx) => *idx.1,
|
||||
};
|
||||
debug_assert!(graph[dst_node_idx].range.contains(&branch.1));
|
||||
graph.add_edge(src_node_idx, dst_node_idx, ());
|
||||
}
|
||||
// Walk blocks and re-connect nodes that were split off.
|
||||
for (src_node_idx, dst_node_idx) in node_by_addr.values().tuple_windows::<(_, _)>() {
|
||||
// Get pairs of two blocks as a sliding window.
|
||||
let src_block: &BasicBlock = &graph[*src_node_idx];
|
||||
let dst_block: &BasicBlock = &graph[*dst_node_idx];
|
||||
assert_eq!(src_block.range.end, dst_block.range.start);
|
||||
// Get last instruction of left block.
|
||||
// Unless it's an unconditional branch, we can connect the blocks.
|
||||
let last_ins = &src_block.code.last().unwrap();
|
||||
if last_ins.code == 0x4E800020
|
||||
|| (last_ins.op == Opcode::B && last_ins.field_BO() == 0b10100)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Execution can continue past the last instruction of a block,
|
||||
// so re-connect two blocks that were split off.
|
||||
if !graph.contains_edge(*src_node_idx, *dst_node_idx) {
|
||||
graph.add_edge(*src_node_idx, *dst_node_idx, ());
|
||||
}
|
||||
}
|
||||
Self {
|
||||
graph,
|
||||
root_idx: *node_by_addr.index(node_by_addr.keys().next().unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dominators(&self) -> Dominators<NodeIndex> {
|
||||
petgraph::algo::dominators::simple_fast(&self.graph, self.root_idx)
|
||||
}
|
||||
}
|
|
@ -1,69 +0,0 @@
|
|||
use petgraph::dot::{Config as DotConfig, Dot};
|
||||
|
||||
use ppc750cl::{disasm_iter, Ins};
|
||||
|
||||
pub mod flow;
|
||||
pub mod slices;
|
||||
|
||||
use crate::flow::FlowGraph;
|
||||
use crate::slices::BasicSlices;
|
||||
use dol::Dol;
|
||||
|
||||
fn main() {
|
||||
let matches = clap::Command::new("ppc750cl-flow-graph")
|
||||
.version("0.2.0")
|
||||
.about("Control flow graph analysis for PowerPC 750CL")
|
||||
.arg(
|
||||
clap::Arg::new("START")
|
||||
.long("--start")
|
||||
.required(true)
|
||||
.takes_value(true)
|
||||
.help("Start address"),
|
||||
)
|
||||
.arg(
|
||||
clap::Arg::new("STOP")
|
||||
.long("--stop")
|
||||
.required(true)
|
||||
.takes_value(true)
|
||||
.help("Stop address"),
|
||||
)
|
||||
.arg(
|
||||
clap::Arg::new("INPUT")
|
||||
.required(true)
|
||||
.help("Binary input file"),
|
||||
)
|
||||
.get_matches();
|
||||
|
||||
let start_addr = matches.value_of("START").unwrap();
|
||||
let start_addr: u32 = ::parse_int::parse(start_addr).expect("Invalid address flag");
|
||||
let stop_addr = matches.value_of("STOP").unwrap();
|
||||
let stop_addr: u32 = ::parse_int::parse(stop_addr).expect("Invalid address flag");
|
||||
|
||||
let file_path = matches.value_of("INPUT").unwrap();
|
||||
let dol_file = std::fs::File::open(file_path).expect("Failed to read file");
|
||||
let dol = Dol::read_from(&dol_file).expect("Invalid DOL file");
|
||||
drop(dol_file);
|
||||
let mut bytes = vec![0u8; (stop_addr - start_addr) as usize];
|
||||
dol.virtual_read(&mut bytes, start_addr)
|
||||
.expect("Invalid address range");
|
||||
|
||||
// Create control flow graph.
|
||||
let ins_list: Vec<Ins> = disasm_iter(&bytes, start_addr).collect();
|
||||
let basic_slices = BasicSlices::from_code(&ins_list);
|
||||
let graph = FlowGraph::from_basic_slices(&basic_slices, &ins_list);
|
||||
|
||||
// Output graphviz.
|
||||
let graphviz = Dot::with_config(
|
||||
&graph.graph,
|
||||
&[DotConfig::EdgeNoLabel, DotConfig::GraphContentOnly],
|
||||
);
|
||||
println!(
|
||||
concat!(
|
||||
"digraph func {{\n",
|
||||
"node [shape=record fontname=Arial];\n",
|
||||
"{:?}\n",
|
||||
"}}"
|
||||
),
|
||||
graphviz
|
||||
);
|
||||
}
|
|
@ -1,62 +0,0 @@
|
|||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use ppc750cl::{Ins, Opcode};
|
||||
|
||||
/// The instruction address divided by four.
|
||||
pub type CodeIdx = u32;
|
||||
|
||||
pub struct BasicSlices {
|
||||
/// The indexes separating instructions into basic blocks.
|
||||
/// Used to create a list of consecutive basic blocks.
|
||||
pub cuts: BTreeSet<CodeIdx>,
|
||||
/// The possible branches from one instruction to another.
|
||||
/// Used to link together basic blocks into a directed graph.
|
||||
pub branches: HashSet<(CodeIdx, CodeIdx)>,
|
||||
}
|
||||
|
||||
impl BasicSlices {
|
||||
/// Computes basic slices from instructions.
|
||||
pub fn from_code(code: &[Ins]) -> Self {
|
||||
let mut cuts = BTreeSet::<CodeIdx>::new();
|
||||
let mut branches = HashSet::<(CodeIdx, CodeIdx)>::new();
|
||||
for ins in code {
|
||||
let cur_index = ins.addr / 4;
|
||||
let is_control_flow_ins = match ins.op {
|
||||
// Direct branches are control flow instructions if they don't save the link register.
|
||||
// If they do, we encountered a function call.
|
||||
Opcode::B | Opcode::Bc => !ins.field_LK(),
|
||||
// Switch table
|
||||
Opcode::Bcctr => panic!("jump tables not supported yet"),
|
||||
_ => false,
|
||||
};
|
||||
if !is_control_flow_ins {
|
||||
continue;
|
||||
}
|
||||
// We encountered some kind of control flow instruction.
|
||||
if ins.field_BO() == 20 && ins.field_BI() == 0 {
|
||||
// There's a possibility that branch can be taken.
|
||||
// Branch destinations are always the first instruction of a block.
|
||||
// Thus, we also found the end of another block.
|
||||
let new_index = ins.branch_dest().unwrap() / 4;
|
||||
cuts.insert(new_index);
|
||||
branches.insert((cur_index, new_index));
|
||||
}
|
||||
if is_conditional_branch(ins) {
|
||||
// There's a possibility that branch is not taken.
|
||||
// End block anyways.
|
||||
cuts.insert(cur_index + 1);
|
||||
branches.insert((cur_index, cur_index + 1));
|
||||
}
|
||||
}
|
||||
Self { cuts, branches }
|
||||
}
|
||||
}
|
||||
|
||||
fn is_conditional_branch(ins: &Ins) -> bool {
|
||||
match ins.op {
|
||||
Opcode::Bc | Opcode::Bcctr | Opcode::Bclr => (),
|
||||
_ => return false,
|
||||
};
|
||||
// Check whether bits "branch always".
|
||||
ins.field_BO() & 0b10100 != 0b10100
|
||||
}
|
|
@ -1,13 +1,14 @@
|
|||
[package]
|
||||
name = "ppc750cl-fuzz"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
edition = "2021"
|
||||
authors = ["Richard Patel <me@terorie.dev>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
description = "Complete fuzzer for ppc750cl"
|
||||
repository = "https://github.com/terorie/ppc750cl"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
clap = "3"
|
||||
num_cpus = "1.13"
|
||||
ppc750cl = { path = "../disasm", version = "0.2.0" }
|
||||
ppc750cl = { path = "../disasm" }
|
||||
|
|
|
@ -5,7 +5,6 @@ use std::sync::atomic::{AtomicU32, Ordering};
|
|||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use ppc750cl::formatter::FormattedIns;
|
||||
use ppc750cl::Ins;
|
||||
|
||||
fn main() {
|
||||
|
@ -91,10 +90,7 @@ struct Fuzzer {
|
|||
|
||||
impl Fuzzer {
|
||||
fn new(range: Range<u32>) -> Self {
|
||||
Self {
|
||||
range,
|
||||
counter: Arc::new(AtomicU32::new(0)),
|
||||
}
|
||||
Self { range, counter: Arc::new(AtomicU32::new(0)) }
|
||||
}
|
||||
|
||||
fn dispatch(&self) -> std::thread::JoinHandle<()> {
|
||||
|
@ -104,8 +100,8 @@ impl Fuzzer {
|
|||
let range = self.range.clone();
|
||||
std::thread::spawn(move || {
|
||||
for x in range.clone() {
|
||||
let ins = Ins::new(x, 0x8000_0000);
|
||||
writeln!(&mut devnull, "{}", FormattedIns(ins)).unwrap();
|
||||
let ins = Ins::new(x);
|
||||
writeln!(&mut devnull, "{}", ins.simplified()).unwrap();
|
||||
if x % (1 << 19) == 0 {
|
||||
counter.store(x, Ordering::Relaxed);
|
||||
}
|
||||
|
|
|
@ -1,17 +1,23 @@
|
|||
[package]
|
||||
name = "ppc750cl-genisa"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
edition = "2021"
|
||||
authors = ["Richard Patel <me@terorie.dev>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
authors = ["Luke Street <luke@street.dev>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Rust code generator for ppc750cl"
|
||||
repository = "https://github.com/terorie/ppc750cl"
|
||||
|
||||
repository = "https://github.com/encounter/ppc750cl"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
itertools = "0.10"
|
||||
anyhow = "1.0"
|
||||
log = "0.4"
|
||||
num-traits = "0.2"
|
||||
prettyplease = "0.2"
|
||||
proc-macro2 = "1.0"
|
||||
quote = "1.0"
|
||||
syn = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_yaml = "0.8"
|
||||
serde_yaml = "0.9"
|
||||
simple_logger = "4.3"
|
||||
syn = { version = "2", default-features = false, features = ["full", "parsing"] }
|
||||
phf = "0.11"
|
||||
phf_codegen = "0.11"
|
||||
|
|
|
@ -0,0 +1,306 @@
|
|||
use crate::condition::{parse_conditions, replace_fields, ConditionOp, ConditionValue};
|
||||
use crate::isa::{
|
||||
modifiers_iter, modifiers_valid, to_ident, Field, HexLiteral, Isa, Mnemonic, Opcode,
|
||||
SignedHexLiteral,
|
||||
};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use proc_macro2::{Literal, TokenStream};
|
||||
use quote::{format_ident, quote};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub fn gen_asm(isa: &Isa, max_args: usize) -> Result<TokenStream> {
|
||||
let mut functions = TokenStream::new();
|
||||
|
||||
let mut func_map = phf_codegen::Map::new();
|
||||
for opcode in &isa.opcodes {
|
||||
let name = format_ident!("gen_{}", opcode.ident());
|
||||
let inner = gen_opcode(opcode, isa)?;
|
||||
functions.extend(quote! {
|
||||
fn #name(args: &Arguments, modifiers: u32) -> Result<u32, ArgumentError> { #inner }
|
||||
});
|
||||
}
|
||||
|
||||
let mut mnemonic_map = HashMap::<String, Vec<Mnemonic>>::new();
|
||||
for mnemonic in &isa.mnemonics {
|
||||
mnemonic_map.entry(mnemonic.name.clone()).or_default().push(mnemonic.clone());
|
||||
}
|
||||
for (name, mnemonics) in &mnemonic_map {
|
||||
let fn_name = format!("gen_{}", to_ident(name));
|
||||
let fn_ident = format_ident!("{}", fn_name);
|
||||
let mut inner;
|
||||
if mnemonics.len() > 1 {
|
||||
inner = TokenStream::new();
|
||||
let mut max_args = 0;
|
||||
for mnemonic in mnemonics {
|
||||
let gen = gen_mnemonic(mnemonic, isa, false)?;
|
||||
let arg_n = Literal::usize_unsuffixed(mnemonic.args.len());
|
||||
inner.extend(quote! {
|
||||
#arg_n => { #gen }
|
||||
});
|
||||
max_args = max_args.max(mnemonic.args.len());
|
||||
}
|
||||
let max_args = Literal::usize_unsuffixed(max_args);
|
||||
inner.extend(quote! {
|
||||
value => Err(ArgumentError::ArgCount { value, expected: #max_args })
|
||||
});
|
||||
inner = quote! { match arg_count(args) { #inner } };
|
||||
} else {
|
||||
inner = gen_mnemonic(mnemonics.first().unwrap(), isa, true)?;
|
||||
}
|
||||
functions.extend(quote! {
|
||||
fn #fn_ident(args: &Arguments, modifiers: u32) -> Result<u32, ArgumentError> { #inner }
|
||||
});
|
||||
}
|
||||
|
||||
for (opcode, modifiers) in isa.opcodes.iter().flat_map(|o| {
|
||||
modifiers_iter(&o.modifiers, isa).filter(|m| modifiers_valid(m)).map(move |m| (o, m))
|
||||
}) {
|
||||
let suffix = modifiers.iter().map(|m| m.suffix).collect::<String>();
|
||||
let mut pattern = 0;
|
||||
for modifier in &modifiers {
|
||||
pattern |= modifier.mask();
|
||||
}
|
||||
func_map.entry(
|
||||
format!("{}{}", opcode.name, suffix),
|
||||
&format!("(gen_{}, {:#x})", opcode.ident(), pattern),
|
||||
);
|
||||
}
|
||||
|
||||
for (mnemonic, modifiers) in mnemonic_map.iter().flat_map(|(_, mnemonics)| {
|
||||
let mnemonic = mnemonics.first().unwrap();
|
||||
let opcode = isa.find_opcode(&mnemonic.opcode).unwrap();
|
||||
let modifiers = mnemonic.modifiers.as_deref().unwrap_or(&opcode.modifiers);
|
||||
modifiers_iter(modifiers, isa).filter(|m| modifiers_valid(m)).map(move |m| (mnemonic, m))
|
||||
}) {
|
||||
let suffix = modifiers.iter().map(|m| m.suffix).collect::<String>();
|
||||
let mut pattern = 0;
|
||||
for modifier in &modifiers {
|
||||
pattern |= modifier.mask();
|
||||
}
|
||||
func_map.entry(
|
||||
format!("{}{}", mnemonic.name, suffix),
|
||||
&format!("(gen_{}, {:#x})", to_ident(&mnemonic.name), pattern),
|
||||
);
|
||||
}
|
||||
|
||||
let func_map = syn::parse_str::<TokenStream>(&func_map.build().to_string())?;
|
||||
let max_args = Literal::usize_unsuffixed(max_args);
|
||||
Ok(quote! {
|
||||
#![allow(unused)]
|
||||
#![cfg_attr(rustfmt, rustfmt_skip)]
|
||||
use crate::types::*;
|
||||
pub type Arguments = [Argument; #max_args];
|
||||
#functions
|
||||
type MnemonicFn = fn(&Arguments, u32) -> Result<u32, ArgumentError>;
|
||||
const MNEMONIC_MAP: phf::Map<&'static str, (MnemonicFn, u32)> = #func_map;
|
||||
pub fn assemble(mnemonic: &str, args: &Arguments) -> Result<u32, ArgumentError> {
|
||||
if let Some(&(fn_ptr, modifiers)) = MNEMONIC_MAP.get(mnemonic) {
|
||||
fn_ptr(args, modifiers)
|
||||
} else {
|
||||
Err(ArgumentError::UnknownMnemonic)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn gen_parse_field(field: &Field, i: usize) -> Result<(TokenStream, bool)> {
|
||||
let Some(bits) = field.bits else { bail!("Field {} has no bits", field.name) };
|
||||
let i = Literal::usize_unsuffixed(i);
|
||||
Ok(if field.signed {
|
||||
let max_value = 1 << (bits.len() - 1 + field.shift_left);
|
||||
let min_value = SignedHexLiteral(-max_value);
|
||||
let max_value = SignedHexLiteral(max_value);
|
||||
(quote! { parse_signed(args, #i, #min_value, #max_value)? }, true)
|
||||
} else {
|
||||
let min_value = HexLiteral(0);
|
||||
let max_value = HexLiteral(bits.max_value() << field.shift_left);
|
||||
(quote! { parse_unsigned(args, #i, #min_value, #max_value)? }, false)
|
||||
})
|
||||
}
|
||||
|
||||
fn gen_field(
|
||||
field: &Field,
|
||||
mut accessor: TokenStream,
|
||||
finalize: fn(TokenStream) -> TokenStream,
|
||||
signed: bool,
|
||||
) -> Result<TokenStream> {
|
||||
let Some(bits) = field.bits else { bail!("Field {} has no bits", field.name) };
|
||||
let mut shift_right = bits.shift();
|
||||
let mut shift_left = field.shift_left;
|
||||
if shift_right == shift_left {
|
||||
// Optimization: these cancel each other out
|
||||
// Adjust subsequent operations to operate on the full value
|
||||
shift_right = 0;
|
||||
shift_left = 0;
|
||||
}
|
||||
|
||||
// Handle the operations (in reverse order from disassembly)
|
||||
let mut operations = TokenStream::new();
|
||||
let mut inner;
|
||||
|
||||
if signed {
|
||||
accessor = quote! { #accessor as u32 };
|
||||
}
|
||||
|
||||
// Swap 5-bit halves (SPR, TBR)
|
||||
if field.split {
|
||||
operations.extend(quote! {
|
||||
value = ((value & 0b11111_00000) >> 5) | ((value & 0b00000_11111) << 5);
|
||||
});
|
||||
inner = quote! { value };
|
||||
} else {
|
||||
inner = accessor.clone();
|
||||
}
|
||||
|
||||
// Handle left shift
|
||||
if shift_left > 0 {
|
||||
let shift_left = Literal::u8_unsuffixed(shift_left);
|
||||
inner = quote! { (#inner >> #shift_left) };
|
||||
}
|
||||
|
||||
// Mask
|
||||
let mask = HexLiteral(bits.mask() >> shift_right);
|
||||
inner = quote! { #inner & #mask };
|
||||
|
||||
// Shift right
|
||||
if shift_right > 0 {
|
||||
let shift = Literal::u8_unsuffixed(shift_right);
|
||||
inner = quote! { (#inner) << #shift };
|
||||
}
|
||||
|
||||
if operations.is_empty() {
|
||||
Ok(finalize(inner))
|
||||
} else {
|
||||
inner = finalize(inner);
|
||||
Ok(quote! {{
|
||||
let mut value = #accessor;
|
||||
#operations
|
||||
#inner
|
||||
}})
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_opcode(opcode: &Opcode, isa: &Isa) -> Result<TokenStream> {
|
||||
let mut args = TokenStream::new();
|
||||
for (i, arg) in opcode.args.iter().enumerate() {
|
||||
let field = isa.find_field(arg).unwrap();
|
||||
let comment = format!(" {}", field.name);
|
||||
let (accessor, signed) = gen_parse_field(field, i)?;
|
||||
let value = gen_field(field, accessor, |s| s, signed)?;
|
||||
args.extend(quote! {
|
||||
#[comment = #comment]
|
||||
code |= #value;
|
||||
});
|
||||
}
|
||||
|
||||
let arg_count = Literal::usize_unsuffixed(opcode.args.len());
|
||||
let pattern = HexLiteral(opcode.pattern);
|
||||
Ok(quote! {
|
||||
check_arg_count(args, #arg_count)?;
|
||||
let mut code = #pattern | modifiers;
|
||||
#args
|
||||
Ok(code)
|
||||
})
|
||||
}
|
||||
|
||||
fn gen_mnemonic(mnemonic: &Mnemonic, isa: &Isa, check_arg_count: bool) -> Result<TokenStream> {
|
||||
let Some(opcode) = isa.find_opcode(&mnemonic.opcode) else {
|
||||
bail!("Unknown opcode {}", mnemonic.opcode)
|
||||
};
|
||||
let mut args = TokenStream::new();
|
||||
for (i, arg) in mnemonic.args.iter().enumerate() {
|
||||
let comment = format!(" {}", arg);
|
||||
let arg = gen_argument(&mnemonic.args, i, isa, mnemonic.replace_assemble.get(arg))?;
|
||||
args.extend(quote! {
|
||||
#[comment = #comment]
|
||||
code |= #arg;
|
||||
});
|
||||
}
|
||||
|
||||
let mut pattern = opcode.pattern;
|
||||
for condition in parse_conditions(&mnemonic.condition, isa)? {
|
||||
if condition.op == ConditionOp::Eq {
|
||||
match condition.value {
|
||||
ConditionValue::ConstantUnsigned(value) => {
|
||||
pattern |= condition.field.shift_value(value);
|
||||
}
|
||||
ConditionValue::ConstantSigned(value) => {
|
||||
pattern |= condition.field.shift_value(value as u32);
|
||||
}
|
||||
ConditionValue::Field(in_field) => {
|
||||
let comment = format!(" {}", condition.field.name);
|
||||
let arg_n = mnemonic
|
||||
.args
|
||||
.iter()
|
||||
.position(|a| a == &in_field.name)
|
||||
.with_context(|| {
|
||||
format!("Mnemonic {}: unknown field {}", mnemonic.name, in_field.name)
|
||||
})?;
|
||||
let (accessor, signed) = gen_parse_field(in_field, arg_n)?;
|
||||
let arg = gen_field(condition.field, accessor, |s| s, signed)?;
|
||||
args.extend(quote! {
|
||||
#[comment = #comment]
|
||||
code |= #arg;
|
||||
});
|
||||
}
|
||||
ConditionValue::Complex(c) => {
|
||||
let comment = format!(" {}", condition.field.name);
|
||||
let mut any_signed = false;
|
||||
let arg = replace_fields(c, isa, |f| {
|
||||
let arg_n =
|
||||
mnemonic.args.iter().position(|a| a == &f.name).with_context(|| {
|
||||
format!("Mnemonic {}: unknown field {}", mnemonic.name, f.name)
|
||||
})?;
|
||||
let (s, signed) = gen_parse_field(f, arg_n)?;
|
||||
any_signed |= signed;
|
||||
Ok(s)
|
||||
})?;
|
||||
let arg = gen_field(condition.field, quote! { (#arg) }, |s| s, any_signed)?;
|
||||
args.extend(quote! {
|
||||
#[comment = #comment]
|
||||
code |= #arg;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let arg_count = Literal::usize_unsuffixed(mnemonic.args.len());
|
||||
let mut result = TokenStream::new();
|
||||
if check_arg_count {
|
||||
result.extend(quote! { check_arg_count(args, #arg_count)?; });
|
||||
}
|
||||
|
||||
let pattern = HexLiteral(pattern);
|
||||
result.extend(quote! {
|
||||
let mut code = #pattern | modifiers;
|
||||
#args
|
||||
Ok(code)
|
||||
});
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn gen_argument(
|
||||
args: &[String],
|
||||
arg_n: usize,
|
||||
isa: &Isa,
|
||||
replace: Option<&String>,
|
||||
) -> Result<TokenStream> {
|
||||
let field = &args[arg_n];
|
||||
let Some(field) = isa.find_field(field) else { bail!("Unknown field {}", field) };
|
||||
if let Some(replace) = replace {
|
||||
let mut any_signed = false;
|
||||
let stream = replace_fields(replace, isa, |f| {
|
||||
let arg_n = args.iter().position(|a| a == &f.name).with_context(|| {
|
||||
format!("Field {} references unknown argument {}", field.name, f.name)
|
||||
})?;
|
||||
let (parse, signed) = gen_parse_field(field, arg_n)?;
|
||||
any_signed |= signed;
|
||||
Ok(parse)
|
||||
})?;
|
||||
gen_field(field, quote! { (#stream) }, |s| s, any_signed)
|
||||
} else {
|
||||
let (accessor, signed) = gen_parse_field(field, arg_n)?;
|
||||
gen_field(field, accessor, |s| s, signed)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,166 @@
|
|||
use std::str::FromStr;
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use proc_macro2::{Group, Ident, TokenStream, TokenTree};
|
||||
use quote::quote;
|
||||
|
||||
use crate::isa::{parse_signed, parse_unsigned, Field, HexLiteral, Isa, SignedHexLiteral};
|
||||
|
||||
/// A condition that must be met for a modifier to be applied
|
||||
/// or for a simplified mnemonic to be matched.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Condition<'a> {
|
||||
pub field: &'a Field,
|
||||
pub field_mask: u32,
|
||||
pub op: ConditionOp,
|
||||
pub value: ConditionValue<'a>,
|
||||
}
|
||||
|
||||
/// The operation of a complex condition.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ConditionOp {
|
||||
/// Equal to. (e.g. `MB == 0`)
|
||||
Eq,
|
||||
/// Not equal to. (e.g. `simm != -0x8000`)
|
||||
Ne,
|
||||
/// Less than. (e.g. `simm < 0`)
|
||||
Lt,
|
||||
/// Greater than. (e.g. `SH > 16`)
|
||||
Gt,
|
||||
/// Less than or equal to. (e.g. `SH <= 16`)
|
||||
Lte,
|
||||
/// Greater than or equal to. (e.g. `SH >= 32 - MB`)
|
||||
Gte,
|
||||
}
|
||||
|
||||
/// The value of a condition.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ConditionValue<'a> {
|
||||
/// A constant unsigned value. (e.g. `MB == 0`)
|
||||
ConstantUnsigned(u32),
|
||||
/// A constant signed value. (e.g. `simm != -0x8000`)
|
||||
ConstantSigned(i32),
|
||||
/// A field value. (e.g. `rB == rS`)
|
||||
Field(&'a Field),
|
||||
/// A complex condition. (e.g. `SH >= 32 - MB`)
|
||||
Complex(&'a str),
|
||||
}
|
||||
|
||||
/// Parse a condition string into a list of conditions. (e.g. `SH >= 32 - MB && MB == 0`)
|
||||
/// Maybe turn this into a real lexer/parser if it gets more complex.
|
||||
pub fn parse_conditions<'a>(condition: &'a str, isa: &'a Isa) -> Result<Vec<Condition<'a>>> {
|
||||
let mut conditions = Vec::new();
|
||||
for tok in condition.split(" && ") {
|
||||
let (mut field, value, op) = if let Some((field, value)) = tok.split_once(" == ") {
|
||||
(field, value, ConditionOp::Eq)
|
||||
} else if let Some((field, value)) = tok.split_once(" != ") {
|
||||
(field, value, ConditionOp::Ne)
|
||||
} else if let Some((field, value)) = tok.split_once(" < ") {
|
||||
(field, value, ConditionOp::Lt)
|
||||
} else if let Some((field, value)) = tok.split_once(" > ") {
|
||||
(field, value, ConditionOp::Gt)
|
||||
} else if let Some((field, value)) = tok.split_once(" <= ") {
|
||||
(field, value, ConditionOp::Lte)
|
||||
} else if let Some((field, value)) = tok.split_once(" >= ") {
|
||||
(field, value, ConditionOp::Gte)
|
||||
} else {
|
||||
log::error!("Invalid condition: {}", tok);
|
||||
continue;
|
||||
};
|
||||
let mut field_mask = u32::MAX;
|
||||
if let Some((n, mask)) = field.split_once(" & ") {
|
||||
field = n;
|
||||
field_mask = parse_unsigned(mask)?;
|
||||
};
|
||||
let field = isa
|
||||
.find_field(field)
|
||||
.with_context(|| format!("Condition references unknown field {}", field))?;
|
||||
let value = if let Ok(value) = parse_unsigned(value) {
|
||||
ConditionValue::ConstantUnsigned(value)
|
||||
} else if let Ok(value) = parse_signed(value) {
|
||||
ConditionValue::ConstantSigned(value)
|
||||
} else if let Some(field) = isa.find_field(value) {
|
||||
ConditionValue::Field(field)
|
||||
} else {
|
||||
ConditionValue::Complex(value)
|
||||
};
|
||||
conditions.push(Condition { field, field_mask, op, value });
|
||||
}
|
||||
Ok(conditions)
|
||||
}
|
||||
|
||||
impl Condition<'_> {
|
||||
pub fn to_token_stream(&self, isa: &Isa, self_ident: Ident) -> Result<TokenStream> {
|
||||
// Accessor
|
||||
let field = self.field;
|
||||
let mut accessor = quote!(#self_ident.#field());
|
||||
if self.field_mask != u32::MAX {
|
||||
let mask = HexLiteral(self.field_mask);
|
||||
accessor = quote! { (#accessor & #mask) };
|
||||
}
|
||||
|
||||
// Operator
|
||||
let op = match self.op {
|
||||
ConditionOp::Eq => quote! { == },
|
||||
ConditionOp::Ne => quote! { != },
|
||||
ConditionOp::Lt => quote! { < },
|
||||
ConditionOp::Gt => quote! { > },
|
||||
ConditionOp::Lte => quote! { <= },
|
||||
ConditionOp::Gte => quote! { >= },
|
||||
};
|
||||
|
||||
// Value
|
||||
let value = match self.value {
|
||||
ConditionValue::ConstantUnsigned(v) => {
|
||||
let v = HexLiteral(v);
|
||||
quote! { #v }
|
||||
}
|
||||
ConditionValue::ConstantSigned(v) => {
|
||||
let v = SignedHexLiteral(v);
|
||||
quote! { #v }
|
||||
}
|
||||
ConditionValue::Field(f) => {
|
||||
quote! { #self_ident.#f() }
|
||||
}
|
||||
ConditionValue::Complex(c) => {
|
||||
replace_fields(c, isa, |f| Ok(quote! { #self_ident.#f() }))?
|
||||
}
|
||||
};
|
||||
|
||||
Ok(quote! { #accessor #op #value })
|
||||
}
|
||||
}
|
||||
|
||||
pub fn replace_fields(
|
||||
s: &str,
|
||||
isa: &Isa,
|
||||
mut accessor: impl FnMut(&Field) -> Result<TokenStream>,
|
||||
) -> Result<TokenStream> {
|
||||
fn replace_inner(
|
||||
s: TokenStream,
|
||||
isa: &Isa,
|
||||
accessor: &mut impl FnMut(&Field) -> Result<TokenStream>,
|
||||
) -> Result<TokenStream> {
|
||||
s.into_iter()
|
||||
.map(|t| -> Result<TokenStream> {
|
||||
match &t {
|
||||
TokenTree::Ident(ident) => {
|
||||
if let Some(field) = isa.find_field(&ident.to_string()) {
|
||||
return accessor(field);
|
||||
}
|
||||
}
|
||||
TokenTree::Group(g) => {
|
||||
return Ok(TokenStream::from(TokenTree::Group(Group::new(
|
||||
g.delimiter(),
|
||||
replace_inner(g.stream(), isa, accessor)?,
|
||||
))));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(TokenStream::from(t))
|
||||
})
|
||||
.collect::<Result<TokenStream>>()
|
||||
}
|
||||
let stream = TokenStream::from_str(s).map_err(|e| anyhow!("{}", e))?;
|
||||
replace_inner(stream, isa, &mut accessor)
|
||||
}
|
|
@ -0,0 +1,416 @@
|
|||
use crate::condition::{parse_conditions, replace_fields};
|
||||
use crate::ident;
|
||||
use crate::isa::{modifiers_iter, modifiers_valid, HexLiteral, Isa, Opcode};
|
||||
use anyhow::{bail, ensure, Result};
|
||||
use proc_macro2::{Literal, TokenStream};
|
||||
use quote::{format_ident, quote};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub fn gen_disasm(isa: &Isa, max_args: usize) -> Result<TokenStream> {
|
||||
// The entry table allows us to quickly find the range of possible opcodes
|
||||
// for a given 6-bit prefix. 2*64 bytes should fit in a cache line (or two).
|
||||
struct OpcodeEntry {
|
||||
start: u8,
|
||||
count: u8,
|
||||
}
|
||||
let mut sorted_ops = Vec::<Opcode>::new();
|
||||
let mut entries = Vec::<OpcodeEntry>::new();
|
||||
for i in 0..64 {
|
||||
let mut entry = OpcodeEntry { start: 0, count: 0 };
|
||||
for opcode in &isa.opcodes {
|
||||
if (opcode.pattern >> 26) as u8 == i {
|
||||
if entry.count == 0 {
|
||||
entry.start = sorted_ops.len() as u8;
|
||||
}
|
||||
// Sanity check for duplicate opcodes
|
||||
if sorted_ops.iter().any(|op| op.name == opcode.name) {
|
||||
bail!("Duplicate opcode: {}", opcode.name);
|
||||
}
|
||||
sorted_ops.push(opcode.clone());
|
||||
entry.count += 1;
|
||||
}
|
||||
}
|
||||
if entry.count > 1 {
|
||||
log::info!("{:#X}: {} opcodes", i, entry.count);
|
||||
} else if let Some(op) = (entry.count == 1).then(|| &sorted_ops[entry.start as usize]) {
|
||||
log::info!("{:#X}: {}", i, op.name);
|
||||
} else {
|
||||
log::info!("{:#X}: <invalid>", i);
|
||||
}
|
||||
entries.push(entry);
|
||||
}
|
||||
ensure!(sorted_ops.len() == isa.opcodes.len());
|
||||
|
||||
// Generate the opcode entries table
|
||||
let mut opcode_entries = TokenStream::new();
|
||||
for entry in &entries {
|
||||
let start = Literal::u8_unsuffixed(entry.start);
|
||||
let end = Literal::u8_unsuffixed(entry.start + entry.count);
|
||||
opcode_entries.extend(quote! { (#start, #end), });
|
||||
}
|
||||
|
||||
// Generate the opcode tables
|
||||
let mut opcode_patterns = TokenStream::new();
|
||||
let mut opcode_enum = TokenStream::new();
|
||||
let mut opcode_names = TokenStream::new();
|
||||
for (idx, opcode) in sorted_ops.iter().enumerate() {
|
||||
let bitmask = HexLiteral(opcode.mask(isa));
|
||||
let pattern = HexLiteral(opcode.pattern);
|
||||
let enum_idx = Literal::u8_unsuffixed(idx as u8);
|
||||
let name = &opcode.name;
|
||||
opcode_patterns.extend(quote! { (#bitmask, #pattern), });
|
||||
opcode_names.extend(quote! { #name, });
|
||||
let doc = opcode.doc();
|
||||
let variant = opcode.variant();
|
||||
opcode_enum.extend(quote! {
|
||||
#[doc = #doc]
|
||||
#variant = #enum_idx,
|
||||
});
|
||||
}
|
||||
|
||||
// Generate field and modifier accessors
|
||||
let mut ins_fields = TokenStream::new();
|
||||
for field in &isa.fields {
|
||||
let Some(bits) = field.bits else {
|
||||
continue;
|
||||
};
|
||||
// TODO get rid of .nz hack
|
||||
if field.name.ends_with(".nz") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut sign_bit = bits.len() - 1;
|
||||
let mut shift_right = bits.shift();
|
||||
let mut shift_left = field.shift_left;
|
||||
if shift_right == shift_left {
|
||||
// Optimization: these cancel each other out
|
||||
// Adjust subsequent operations to operate on the full value
|
||||
sign_bit += shift_left;
|
||||
shift_right = 0;
|
||||
shift_left = 0;
|
||||
}
|
||||
|
||||
// Shift right and mask
|
||||
let mut inner = quote! { self.code };
|
||||
if shift_right > 0 {
|
||||
let shift = Literal::u8_unsuffixed(shift_right);
|
||||
inner = quote! { (#inner >> #shift) };
|
||||
}
|
||||
let mask = HexLiteral(bits.mask() >> shift_right);
|
||||
inner = quote! { #inner & #mask };
|
||||
|
||||
// Determine the smallest integer type that can hold the value
|
||||
let num_bits = bits.len() + field.shift_left;
|
||||
let (out_type, cast) = match (num_bits, field.signed) {
|
||||
(1..=8, false) => (ident!(u8), true),
|
||||
(9..=16, false) => (ident!(u16), true),
|
||||
(17..=32, false) => (ident!(u32), false),
|
||||
(1..=8, true) => (ident!(i8), true),
|
||||
(9..=16, true) => (ident!(i16), true),
|
||||
(17..=32, true) => (ident!(i32), true),
|
||||
(v, _) => bail!("Unsupported field size {v}"),
|
||||
};
|
||||
|
||||
// Handle sign extension
|
||||
if field.signed {
|
||||
let sign_value = HexLiteral(1 << sign_bit);
|
||||
inner = quote! { ((#inner) ^ #sign_value).wrapping_sub(#sign_value) as #out_type };
|
||||
} else if cast {
|
||||
inner = quote! { (#inner) as #out_type };
|
||||
}
|
||||
|
||||
// Handle left shift
|
||||
if shift_left > 0 {
|
||||
let shift_left = Literal::u8_unsuffixed(shift_left);
|
||||
inner = quote! { (#inner) << #shift_left };
|
||||
}
|
||||
|
||||
// Swap 5-bit halves (SPR, TBR)
|
||||
if field.split {
|
||||
inner = quote! {
|
||||
let value = #inner;
|
||||
((value & 0b11111_00000) >> 5) | ((value & 0b00000_11111) << 5)
|
||||
};
|
||||
}
|
||||
|
||||
// Write the accessor
|
||||
let doc = field.doc();
|
||||
ins_fields.extend(quote! {
|
||||
#[doc = #doc]
|
||||
#[inline(always)]
|
||||
pub const fn #field(&self) -> #out_type { #inner }
|
||||
});
|
||||
}
|
||||
for modifier in &isa.modifiers {
|
||||
let mask = HexLiteral(modifier.mask());
|
||||
let mut inner = quote! { (self.code & #mask) == #mask };
|
||||
if let Some(condition) = &modifier.condition {
|
||||
for condition in parse_conditions(condition, isa)? {
|
||||
let stream = condition.to_token_stream(isa, ident!(self))?;
|
||||
inner.extend(quote! { && #stream });
|
||||
}
|
||||
};
|
||||
|
||||
// Write the accessor
|
||||
let doc = modifier.doc();
|
||||
ins_fields.extend(quote! {
|
||||
#[doc = #doc]
|
||||
#[inline(always)]
|
||||
pub const fn #modifier(&self) -> bool { #inner }
|
||||
});
|
||||
}
|
||||
|
||||
// Generate simplified mnemonics
|
||||
let mut mnemonic_functions = TokenStream::new();
|
||||
let mut base_functions_ref = TokenStream::new();
|
||||
let mut simplified_functions_ref = TokenStream::new();
|
||||
for opcode in &sorted_ops {
|
||||
let mnemonics =
|
||||
isa.mnemonics.iter().filter(|m| m.opcode == opcode.name).collect::<Vec<_>>();
|
||||
let mut mnemonic_conditions = TokenStream::new();
|
||||
|
||||
// Generate conditions for each simplified mnemonic
|
||||
for mnemonic in &mnemonics {
|
||||
let conditions = parse_conditions(&mnemonic.condition, isa)?
|
||||
.iter()
|
||||
.map(|c| c.to_token_stream(isa, ident!(ins)))
|
||||
.collect::<Result<Vec<TokenStream>>>()?;
|
||||
let modifiers = mnemonic.modifiers.as_deref().unwrap_or(&opcode.modifiers);
|
||||
let inner = gen_mnemonic(
|
||||
&mnemonic.name,
|
||||
&mnemonic.args,
|
||||
modifiers,
|
||||
isa,
|
||||
max_args,
|
||||
Some(&mnemonic.replace),
|
||||
)?;
|
||||
mnemonic_conditions.extend(quote! {
|
||||
if #(#conditions)&&* {
|
||||
return #inner;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Fallback to the base opcode name if no mnemonic matches
|
||||
let inner =
|
||||
gen_mnemonic(&opcode.name, &opcode.args, &opcode.modifiers, isa, max_args, None)?;
|
||||
let base_name = format_ident!("base_{}", opcode.ident());
|
||||
if mnemonics.is_empty() {
|
||||
mnemonic_functions.extend(quote! {
|
||||
const fn #base_name(ins: &Ins) -> (&'static str, Arguments) {
|
||||
#inner
|
||||
}
|
||||
});
|
||||
base_functions_ref.extend(quote! { #base_name, });
|
||||
simplified_functions_ref.extend(quote! { #base_name, });
|
||||
} else {
|
||||
let simplified_name = format_ident!("simplified_{}", opcode.ident());
|
||||
mnemonic_functions.extend(quote! {
|
||||
#[inline(always)]
|
||||
const fn #base_name(ins: &Ins) -> (&'static str, Arguments) {
|
||||
#inner
|
||||
}
|
||||
const fn #simplified_name(ins: &Ins) -> (&'static str, Arguments) {
|
||||
#mnemonic_conditions
|
||||
#base_name(ins)
|
||||
}
|
||||
});
|
||||
base_functions_ref.extend(quote! { #base_name, });
|
||||
simplified_functions_ref.extend(quote! { #simplified_name, });
|
||||
}
|
||||
}
|
||||
let mut none_args = TokenStream::new();
|
||||
for _ in 0..max_args {
|
||||
none_args.extend(quote! { Argument::None, });
|
||||
}
|
||||
mnemonic_functions.extend(quote! {
|
||||
const fn mnemonic_illegal(_ins: &Ins) -> (&'static str, Arguments) {
|
||||
("<illegal>", [#none_args])
|
||||
}
|
||||
});
|
||||
|
||||
// TODO rework defs/uses to account for modifiers and special registers (CTR, LR, etc)
|
||||
let mut defs_uses_functions = TokenStream::new();
|
||||
let mut defs_refs = TokenStream::new();
|
||||
let mut uses_refs = TokenStream::new();
|
||||
for opcode in &sorted_ops {
|
||||
let mut defs = TokenStream::new();
|
||||
let mut uses = TokenStream::new();
|
||||
let mut defs_count = 0;
|
||||
for def in &opcode.defs {
|
||||
if isa.find_field(def).is_some_and(|f| f.arg.is_none()) {
|
||||
continue;
|
||||
}
|
||||
let arg = gen_argument(def, isa, None)?;
|
||||
defs.extend(quote! { #arg, });
|
||||
defs_count += 1;
|
||||
}
|
||||
for _ in defs_count..max_args {
|
||||
defs.extend(quote! { Argument::None, });
|
||||
}
|
||||
let mut use_count = 0;
|
||||
for use_ in &opcode.uses {
|
||||
if let Some(use_) = use_.strip_suffix(".nz") {
|
||||
let Some(field) = isa.find_field(use_) else { bail!("Unknown field {}", use_) };
|
||||
let ident = field.ident();
|
||||
let arg = gen_argument(use_, isa, None)?;
|
||||
uses.extend(quote! { if ins.#ident() != 0 { #arg } else { Argument::None }, });
|
||||
use_count += 1;
|
||||
continue;
|
||||
} else if isa.find_field(use_).is_some_and(|f| f.arg.is_none()) {
|
||||
continue;
|
||||
}
|
||||
let arg = gen_argument(use_, isa, None)?;
|
||||
uses.extend(quote! { #arg, });
|
||||
use_count += 1;
|
||||
}
|
||||
for _ in use_count..max_args {
|
||||
uses.extend(quote! { Argument::None, });
|
||||
}
|
||||
let defs_name = format_ident!("defs_{}", opcode.ident());
|
||||
let uses_name = format_ident!("uses_{}", opcode.ident());
|
||||
defs_uses_functions.extend(quote! {
|
||||
const fn #defs_name(ins: &Ins) -> Arguments { [#defs] }
|
||||
const fn #uses_name(ins: &Ins) -> Arguments { [#uses] }
|
||||
});
|
||||
defs_refs.extend(quote! { #defs_name, });
|
||||
uses_refs.extend(quote! { #uses_name, });
|
||||
}
|
||||
defs_uses_functions.extend(quote! {
|
||||
const fn defs_uses_illegal(_ins: &Ins) -> Arguments { [#none_args] }
|
||||
});
|
||||
|
||||
// Filling the tables to 256 entries to avoid bounds checks
|
||||
for _ in sorted_ops.len()..256 {
|
||||
opcode_patterns.extend(quote! { (0, 0), });
|
||||
opcode_names.extend(quote! { "<illegal>", });
|
||||
base_functions_ref.extend(quote! { mnemonic_illegal, });
|
||||
simplified_functions_ref.extend(quote! { mnemonic_illegal, });
|
||||
defs_refs.extend(quote! { defs_uses_illegal, });
|
||||
uses_refs.extend(quote! { defs_uses_illegal, });
|
||||
}
|
||||
|
||||
let max_args = Literal::usize_unsuffixed(max_args);
|
||||
Ok(quote! {
|
||||
#![allow(unused)]
|
||||
#![cfg_attr(rustfmt, rustfmt_skip)]
|
||||
use crate::disasm::*;
|
||||
#[doc = " The entry table allows us to quickly find the range of possible opcodes for a"]
|
||||
#[doc = " given 6-bit prefix. 2*64 bytes should fit in a cache line (or two)."]
|
||||
const OPCODE_ENTRIES: [(u8, u8); 64] = [#opcode_entries];
|
||||
#[doc = " The bitmask and pattern for each opcode."]
|
||||
const OPCODE_PATTERNS: [(u32, u32); 256] = [#opcode_patterns];
|
||||
#[doc = " The name of each opcode."]
|
||||
const OPCODE_NAMES: [&str; 256] = [#opcode_names];
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
#[non_exhaustive]
|
||||
pub enum Opcode {
|
||||
#[doc = " An illegal or unknown opcode"]
|
||||
#[default]
|
||||
Illegal = u8::MAX,
|
||||
#opcode_enum
|
||||
}
|
||||
impl Opcode {
|
||||
#[inline]
|
||||
pub const fn _mnemonic(self) -> &'static str {
|
||||
OPCODE_NAMES[self as usize]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub const fn _detect(code: u32) -> Self {
|
||||
let entry = OPCODE_ENTRIES[(code >> 26) as usize];
|
||||
let mut i = entry.0;
|
||||
while i < entry.1 {
|
||||
let pattern = OPCODE_PATTERNS[i as usize];
|
||||
if (code & pattern.0) == pattern.1 {
|
||||
#[comment = " Safety: The enum is repr(u8) and marked non_exhaustive"]
|
||||
return unsafe { core::mem::transmute(i) };
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
Self::Illegal
|
||||
}
|
||||
}
|
||||
|
||||
impl Ins {
|
||||
#ins_fields
|
||||
}
|
||||
|
||||
pub type Arguments = [Argument; #max_args];
|
||||
pub type MnemonicFunction = fn(&Ins) -> (&'static str, Arguments);
|
||||
#mnemonic_functions
|
||||
pub const BASE_MNEMONICS: [MnemonicFunction; 256] = [#base_functions_ref];
|
||||
pub const SIMPLIFIED_MNEMONICS: [MnemonicFunction; 256] = [#simplified_functions_ref];
|
||||
#defs_uses_functions
|
||||
pub type DefsUsesFunction = fn(&Ins) -> Arguments;
|
||||
pub const DEFS_FUNCTIONS: [DefsUsesFunction; 256] = [#defs_refs];
|
||||
pub const USES_FUNCTIONS: [DefsUsesFunction; 256] = [#uses_refs];
|
||||
})
|
||||
}
|
||||
|
||||
fn modifier_names(name: &str, modifiers: &[String], isa: &Isa) -> Vec<String> {
|
||||
// For every combination of modifiers, generate a name
|
||||
let mut names = Vec::with_capacity(1 << modifiers.len());
|
||||
for v in modifiers_iter(modifiers, isa) {
|
||||
if modifiers_valid(&v) {
|
||||
let mut name = name.to_string();
|
||||
for modifier in &v {
|
||||
name.push(modifier.suffix);
|
||||
}
|
||||
names.push(name);
|
||||
} else {
|
||||
names.push("<illegal>".to_string());
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
fn gen_argument(field: &str, isa: &Isa, replace: Option<&String>) -> Result<TokenStream> {
|
||||
let Some(field) = isa.find_field(field) else { bail!("Unknown field {}", field) };
|
||||
let Some(arg) = &field.arg else { bail!("Field {} has no argument", field.name) };
|
||||
let value = if let Some(replace) = replace {
|
||||
let stream = replace_fields(replace, isa, |f| Ok(quote! { ins.#f() }))?;
|
||||
quote! { (#stream) }
|
||||
} else {
|
||||
quote! { ins.#field() }
|
||||
};
|
||||
let arg = format_ident!("{}", arg);
|
||||
Ok(quote! { Argument::#arg(#arg(#value as _)) })
|
||||
}
|
||||
|
||||
fn gen_mnemonic(
|
||||
name: &str,
|
||||
args: &[String],
|
||||
modifiers: &[String],
|
||||
isa: &Isa,
|
||||
max_args: usize,
|
||||
replace: Option<&HashMap<String, String>>,
|
||||
) -> Result<TokenStream> {
|
||||
let mut arguments = TokenStream::new();
|
||||
for field in args {
|
||||
let arg = gen_argument(field, isa, replace.and_then(|m| m.get(field)))?;
|
||||
arguments.extend(quote! { #arg, });
|
||||
}
|
||||
for _ in args.len()..max_args {
|
||||
arguments.extend(quote! { Argument::None, });
|
||||
}
|
||||
|
||||
if modifiers.is_empty() {
|
||||
Ok(quote! { (#name, [#arguments]) })
|
||||
} else {
|
||||
let names = modifier_names(name, modifiers, isa);
|
||||
let mut bitset = quote! { 0 };
|
||||
for (i, modifier) in modifiers.iter().enumerate() {
|
||||
let modifier = isa.find_modifier(modifier).unwrap();
|
||||
if i == 0 {
|
||||
bitset = quote! { ins.#modifier() as usize };
|
||||
} else {
|
||||
let i = Literal::u8_unsuffixed(i as u8);
|
||||
bitset.extend(quote! { | (ins.#modifier() as usize) << #i });
|
||||
}
|
||||
}
|
||||
Ok(quote! { ([#(#names),*][#bitset], [#arguments]) })
|
||||
}
|
||||
}
|
|
@ -0,0 +1,416 @@
|
|||
use std::collections::HashMap;
|
||||
use std::{fs::File, path::Path, str::FromStr};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use num_traits::PrimInt;
|
||||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
use quote::{format_ident, ToTokens};
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
|
||||
pub fn load_isa(path: &Path) -> Result<Isa> {
|
||||
let yaml_file =
|
||||
File::open(path).with_context(|| format!("Failed to open file {}", path.display()))?;
|
||||
let isa: Isa = serde_yaml::from_reader(yaml_file)
|
||||
.with_context(|| format!("While parsing file {}", path.display()))?;
|
||||
Ok(isa)
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Isa {
|
||||
pub fields: Vec<Field>,
|
||||
pub modifiers: Vec<Modifier>,
|
||||
pub opcodes: Vec<Opcode>,
|
||||
pub mnemonics: Vec<Mnemonic>,
|
||||
}
|
||||
|
||||
impl Isa {
|
||||
pub fn find_field(&self, name: &str) -> Option<&Field> {
|
||||
self.fields.iter().find(|f| f.name == name)
|
||||
}
|
||||
|
||||
pub fn find_modifier(&self, name: &str) -> Option<&Modifier> {
|
||||
self.modifiers.iter().find(|m| m.name == name)
|
||||
}
|
||||
|
||||
pub fn find_opcode(&self, name: &str) -> Option<&Opcode> {
|
||||
self.opcodes.iter().find(|o| o.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Field {
|
||||
pub name: String,
|
||||
pub desc: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bits: Option<BitRange>,
|
||||
pub signed: bool,
|
||||
pub split: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub arg: Option<String>,
|
||||
pub shift_left: u8,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
/// Calculate the field mask from its bit range
|
||||
pub fn mask(&self) -> u32 {
|
||||
self.bits.map(|b| b.mask()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Shift and mask a value according to the field
|
||||
pub fn shift_value(&self, mut value: u32) -> u32 {
|
||||
if self.split {
|
||||
// Swap 5-bit halves (SPR, TBR)
|
||||
value = ((value & 0b11111_00000u32) >> 5) | ((value & 0b00000_11111u32) << 5);
|
||||
}
|
||||
self.bits.map(|b| b.shift_value(value >> self.shift_left)).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn ident(&self) -> Ident {
|
||||
format_ident!("field_{}", to_ident(&self.name))
|
||||
}
|
||||
|
||||
pub fn doc(&self) -> String {
|
||||
if self.desc.is_empty() {
|
||||
format!(" {}", self.name)
|
||||
} else {
|
||||
format!(" {}: {}", self.name, self.desc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for Field {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
self.ident().to_tokens(tokens)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Opcode {
|
||||
pub name: String,
|
||||
pub desc: String,
|
||||
pub bitmask: u32,
|
||||
pub pattern: u32,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub modifiers: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub defs: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub uses: Vec<String>,
|
||||
}
|
||||
|
||||
impl Opcode {
|
||||
/// Calculate the opcode mask from its fields and modifiers
|
||||
pub fn mask(&self, isa: &Isa) -> u32 {
|
||||
let mut calc_bitmask = 0u32;
|
||||
for arg_n in &self.args {
|
||||
let Some(field) = isa.find_field(arg_n) else {
|
||||
continue;
|
||||
};
|
||||
calc_bitmask |= field.mask();
|
||||
}
|
||||
for modifier_n in &self.modifiers {
|
||||
let Some(modifier) = isa.find_modifier(modifier_n) else {
|
||||
continue;
|
||||
};
|
||||
calc_bitmask |= modifier.mask();
|
||||
}
|
||||
!calc_bitmask
|
||||
}
|
||||
|
||||
pub fn ident(&self) -> Ident {
|
||||
Ident::new(&to_ident(&self.name), Span::call_site())
|
||||
}
|
||||
|
||||
pub fn variant(&self) -> Ident {
|
||||
Ident::new(&to_variant(&self.name), Span::call_site())
|
||||
}
|
||||
|
||||
pub fn doc(&self) -> String {
|
||||
if self.desc.is_empty() {
|
||||
format!(" {}", self.name)
|
||||
} else {
|
||||
format!(" {}: {}", self.name, self.desc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for Opcode {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
self.ident().to_tokens(tokens)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Mnemonic {
|
||||
pub name: String,
|
||||
pub desc: String,
|
||||
pub opcode: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
// Overrides modifier list from opcode
|
||||
pub modifiers: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
pub condition: String,
|
||||
#[serde(skip_serializing_if = "HashMap::is_empty")]
|
||||
pub replace: HashMap<String, String>,
|
||||
#[serde(skip_serializing_if = "HashMap::is_empty")]
|
||||
pub replace_assemble: HashMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Modifier {
|
||||
pub name: String,
|
||||
pub desc: String,
|
||||
pub suffix: char,
|
||||
pub bit: u8,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub defs: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub condition: Option<String>,
|
||||
}
|
||||
|
||||
impl Modifier {
|
||||
/// Calculate the modifier mask from its bit
|
||||
pub fn mask(&self) -> u32 {
|
||||
1 << (31 - self.bit)
|
||||
}
|
||||
|
||||
pub fn ident(&self) -> Ident {
|
||||
format_ident!("field_{}", to_ident(&self.name))
|
||||
}
|
||||
|
||||
pub fn doc(&self) -> String {
|
||||
if self.desc.is_empty() {
|
||||
format!(" {}", self.name)
|
||||
} else {
|
||||
format!(" {}: {}", self.name, self.desc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for Modifier {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
self.ident().to_tokens(tokens)
|
||||
}
|
||||
}
|
||||
|
||||
/// A collection of modifiers
|
||||
type Modifiers<'a> = Vec<&'a Modifier>;
|
||||
|
||||
/// Whether a collection of modifiers is valid (all bits are unique)
|
||||
pub fn modifiers_valid(modifiers: &Modifiers) -> bool {
|
||||
let bits = modifiers.iter().map(|m| m.bit).collect::<Vec<_>>();
|
||||
bits.iter().all(|&b| bits.iter().filter(|&&x| x == b).count() == 1)
|
||||
}
|
||||
|
||||
/// Iterate over all possible combinations of modifiers
|
||||
pub fn modifiers_iter<'a>(
|
||||
modifiers: &'a [String],
|
||||
isa: &'a Isa,
|
||||
) -> impl Iterator<Item = Modifiers<'a>> {
|
||||
(0..=(1 << modifiers.len()) - 1).map(move |b| {
|
||||
modifiers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| b & (1 << i) != 0)
|
||||
.map(|(_, m)| isa.find_modifier(m).unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default)]
|
||||
pub struct BitRange(pub (u8, u8));
|
||||
|
||||
impl BitRange {
|
||||
#[inline]
|
||||
pub fn new(start: u8, end: u8) -> Self {
|
||||
Self((start, end))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn start(&self) -> u8 {
|
||||
self.0 .0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn end(&self) -> u8 {
|
||||
self.0 .1
|
||||
}
|
||||
|
||||
/// Calculate the mask from the range
|
||||
#[inline]
|
||||
pub fn mask(&self) -> u32 {
|
||||
self.max_value() << self.shift()
|
||||
}
|
||||
|
||||
/// Number of bits to shift
|
||||
#[inline]
|
||||
pub fn shift(&self) -> u8 {
|
||||
32 - self.end()
|
||||
}
|
||||
|
||||
/// Number of bits in the range
|
||||
#[inline]
|
||||
pub fn len(&self) -> u8 {
|
||||
self.end() - self.start()
|
||||
}
|
||||
|
||||
/// Shift and mask a value according to the range
|
||||
#[inline]
|
||||
pub fn shift_value(&self, value: u32) -> u32 {
|
||||
(value & self.max_value()) << self.shift()
|
||||
}
|
||||
|
||||
/// Calculate the maximum value that can be represented by the range
|
||||
#[inline]
|
||||
pub fn max_value(&self) -> u32 {
|
||||
(1 << self.len()) - 1
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for BitRange {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let range_str: String = Deserialize::deserialize(deserializer)?;
|
||||
if let Some((start_str, end_str)) = range_str.split_once("..") {
|
||||
let start = start_str.parse::<u8>().map_err(serde::de::Error::custom)?;
|
||||
let end = end_str.parse::<u8>().map_err(serde::de::Error::custom)?;
|
||||
Ok(Self::new(start, end))
|
||||
} else {
|
||||
let bit_idx = range_str.parse::<u8>().map_err(serde::de::Error::custom)?;
|
||||
Ok(Self::new(bit_idx, bit_idx))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for BitRange {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
if self.start() == self.end() {
|
||||
self.start().serialize(serializer)
|
||||
} else {
|
||||
format!("{}..{}", self.start(), self.end()).serialize(serializer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_ident(key: &str) -> String {
|
||||
key.to_ascii_lowercase().replace('.', "_").replace('+', "p").replace('-', "m")
|
||||
}
|
||||
|
||||
pub fn to_variant(key: &str) -> String {
|
||||
let mut s = String::new();
|
||||
let mut chars = key.chars();
|
||||
loop {
|
||||
// Make first char uppercase.
|
||||
let c = match chars.next() {
|
||||
None => return s,
|
||||
Some(c) => c,
|
||||
};
|
||||
s.push(match c {
|
||||
'a'..='z' => c.to_ascii_uppercase(),
|
||||
'A'..='Z' => c,
|
||||
_ => panic!("invalid identifier: {}", key),
|
||||
});
|
||||
loop {
|
||||
let c = match chars.next() {
|
||||
None => return s,
|
||||
Some(c) => c,
|
||||
};
|
||||
match c.to_ascii_lowercase() {
|
||||
'0'..='9' | 'a'..='z' => s.push(c),
|
||||
'_' => break,
|
||||
'.' => {
|
||||
s.push('_');
|
||||
break;
|
||||
}
|
||||
_ => panic!("invalid character in variant: {}", key),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an unsigned number in decimal, binary, or hexadecimal format.
|
||||
pub fn parse_unsigned(mask: &str) -> Result<u32, std::num::ParseIntError> {
|
||||
if let Some(mask) = mask.strip_prefix("0b") {
|
||||
u32::from_str_radix(mask, 2)
|
||||
} else if let Some(mask) = mask.strip_prefix("0x") {
|
||||
u32::from_str_radix(mask, 16)
|
||||
} else {
|
||||
mask.parse::<u32>()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a signed number in decimal, binary, or hexadecimal format.
|
||||
pub fn parse_signed(mask: &str) -> Result<i32, std::num::ParseIntError> {
|
||||
if let Some(mask) = mask.strip_prefix('-') {
|
||||
if let Some(mask) = mask.strip_prefix("0b") {
|
||||
i32::from_str_radix(mask, 2).map(|n| -n)
|
||||
} else if let Some(mask) = mask.strip_prefix("0x") {
|
||||
i32::from_str_radix(mask, 16).map(|n| -n)
|
||||
} else {
|
||||
mask.parse::<i32>().map(|n| -n)
|
||||
}
|
||||
} else {
|
||||
parse_unsigned(mask).map(|n| n as i32)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HexLiteral<T>(pub T);
|
||||
|
||||
impl<T> std::fmt::LowerHex for HexLiteral<T>
|
||||
where
|
||||
T: std::fmt::LowerHex,
|
||||
{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
std::fmt::LowerHex::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ToTokens for HexLiteral<T>
|
||||
where
|
||||
T: std::fmt::LowerHex,
|
||||
{
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
let s = format!("{:#x}", self);
|
||||
tokens.extend(TokenStream::from_str(&s).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SignedHexLiteral<T>(pub T);
|
||||
|
||||
impl<T> std::fmt::LowerHex for SignedHexLiteral<T>
|
||||
where
|
||||
T: PrimInt + std::fmt::LowerHex,
|
||||
{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if self.0 < T::zero() {
|
||||
write!(f, "-")?;
|
||||
let int = self.0.to_i64().unwrap_or_default();
|
||||
std::fmt::LowerHex::fmt(&-int, f)
|
||||
} else {
|
||||
std::fmt::LowerHex::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ToTokens for SignedHexLiteral<T>
|
||||
where
|
||||
T: PrimInt + std::fmt::LowerHex,
|
||||
{
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
let s = format!("{:#x}", self);
|
||||
tokens.extend(TokenStream::from_str(&s).unwrap());
|
||||
}
|
||||
}
|
|
@ -1,771 +1,162 @@
|
|||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::ops::Range;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::str::FromStr;
|
||||
mod asm;
|
||||
mod condition;
|
||||
mod disasm;
|
||||
mod isa;
|
||||
|
||||
use itertools::Itertools;
|
||||
use proc_macro2::{Group, Ident, Literal, Span, TokenStream, TokenTree};
|
||||
use quote::quote;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use syn::{LitChar, LitInt, LitStr};
|
||||
use crate::asm::gen_asm;
|
||||
use crate::disasm::gen_disasm;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use condition::{parse_conditions, ConditionOp, ConditionValue};
|
||||
use isa::load_isa;
|
||||
use std::path::Path;
|
||||
|
||||
macro_rules! token_stream {
|
||||
($stream:ident) => {
|
||||
TokenStream::from_iter($stream.into_iter())
|
||||
/// Identifier literal.
|
||||
#[macro_export]
|
||||
macro_rules! ident {
|
||||
($name:ident) => {
|
||||
proc_macro2::Ident::new(stringify!($name), proc_macro2::Span::call_site())
|
||||
};
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(err) = _main() {
|
||||
eprintln!("{}", err);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
simple_logger::SimpleLogger::new().env().init().unwrap();
|
||||
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
let isa = load_isa(Path::new("isa.yaml"))?;
|
||||
// Make sure we can fit the opcodes into a u8
|
||||
ensure!(isa.opcodes.len() <= 255);
|
||||
|
||||
fn _main() -> Result<()> {
|
||||
let isa = load_isa()?;
|
||||
|
||||
let mut unformatted_code = Vec::<u8>::new();
|
||||
writeln!(
|
||||
&mut unformatted_code,
|
||||
"{}",
|
||||
quote! {
|
||||
use crate::prelude::*;
|
||||
// Sanity check the opcodes and mnemonics
|
||||
// Calculate the bitmask for each opcode and compare it to the stored bitmask
|
||||
let mut max_args = 0;
|
||||
for opcode in &isa.opcodes {
|
||||
let mut calc_bitmask = opcode.mask(&isa);
|
||||
if opcode.bitmask != calc_bitmask {
|
||||
log::warn!(
|
||||
"Opcode {}: Calculated bitmask mismatch: {:#010X} != {:#010X} ({:032b} != {:032b})",
|
||||
opcode.name,
|
||||
opcode.bitmask,
|
||||
calc_bitmask,
|
||||
opcode.bitmask,
|
||||
calc_bitmask
|
||||
);
|
||||
}
|
||||
if opcode.pattern & !opcode.bitmask != 0 {
|
||||
log::warn!(
|
||||
"Opcode {}: Pattern has bits set outside of bitmask: {:#010X} & !{:#010X} != 0 ({:032b} & !{:032b} != 0)",
|
||||
opcode.name,
|
||||
opcode.pattern,
|
||||
opcode.bitmask,
|
||||
opcode.pattern,
|
||||
opcode.bitmask
|
||||
);
|
||||
}
|
||||
)?;
|
||||
writeln!(&mut unformatted_code, "{}", isa.gen_opcode_enum()?)?;
|
||||
writeln!(&mut unformatted_code, "{}", isa.gen_field_enum()?)?;
|
||||
writeln!(&mut unformatted_code, "{}", isa.gen_field_impl()?)?;
|
||||
writeln!(&mut unformatted_code, "{}", isa.gen_ins_impl()?)?;
|
||||
|
||||
let formatted_code = rustfmt(unformatted_code);
|
||||
File::create("./disasm/src/generated.rs")?.write_all(&formatted_code)?;
|
||||
// Make sure we can account for every bit with fields and modifiers
|
||||
for arg in &opcode.args {
|
||||
let field = isa
|
||||
.find_field(arg)
|
||||
.with_context(|| format!("Opcode {}: unknown field {}", opcode.name, arg))?;
|
||||
calc_bitmask |= field.mask();
|
||||
}
|
||||
for modifier_name in &opcode.modifiers {
|
||||
let modifier = isa.find_modifier(modifier_name).with_context(|| {
|
||||
format!("Opcode {}: unknown modifier {}", opcode.name, modifier_name)
|
||||
})?;
|
||||
if let Some(condition) = &modifier.condition {
|
||||
for condition in parse_conditions(condition, &isa)? {
|
||||
// Only check constant conditions
|
||||
if condition.op == ConditionOp::Eq
|
||||
&& matches!(
|
||||
condition.value,
|
||||
ConditionValue::ConstantUnsigned(_) | ConditionValue::ConstantSigned(_)
|
||||
)
|
||||
{
|
||||
calc_bitmask |= condition.field.shift_value(condition.field_mask);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
calc_bitmask |= modifier.mask();
|
||||
}
|
||||
}
|
||||
if calc_bitmask != u32::MAX {
|
||||
log::warn!(
|
||||
"Opcode {}: Calculated bitmask is non-exhaustive: {:#010X}, {:032b}",
|
||||
opcode.name,
|
||||
calc_bitmask,
|
||||
calc_bitmask
|
||||
);
|
||||
}
|
||||
|
||||
max_args = max_args.max(opcode.args.len());
|
||||
}
|
||||
|
||||
// Check each mnemonic, make sure we can account for every bit
|
||||
// with fields, modifiers, and conditions
|
||||
for mnemonic in &isa.mnemonics {
|
||||
let opcode = isa.find_opcode(&mnemonic.opcode).with_context(|| {
|
||||
format!("Mnemonic {}: unknown opcode {}", mnemonic.name, mnemonic.opcode)
|
||||
})?;
|
||||
let mut calc_bitmask = opcode.mask(&isa);
|
||||
for arg in &mnemonic.args {
|
||||
let field = isa
|
||||
.find_field(arg)
|
||||
.with_context(|| format!("Mnemonic {}: unknown field {}", mnemonic.name, arg))?;
|
||||
calc_bitmask |= field.mask();
|
||||
}
|
||||
for modifier_name in mnemonic.modifiers.as_deref().unwrap_or(&opcode.modifiers) {
|
||||
let modifier = isa.find_modifier(modifier_name).with_context(|| {
|
||||
format!("Mnemonic {}: unknown modifier {}", mnemonic.name, modifier_name)
|
||||
})?;
|
||||
if let Some(condition) = &modifier.condition {
|
||||
for condition in parse_conditions(condition, &isa)? {
|
||||
// Only check constant conditions
|
||||
if condition.op == ConditionOp::Eq
|
||||
&& matches!(
|
||||
condition.value,
|
||||
ConditionValue::ConstantUnsigned(_) | ConditionValue::ConstantSigned(_)
|
||||
)
|
||||
{
|
||||
calc_bitmask |= condition.field.shift_value(condition.field_mask);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
calc_bitmask |= modifier.mask();
|
||||
}
|
||||
}
|
||||
for condition in parse_conditions(&mnemonic.condition, &isa)? {
|
||||
if condition.op != ConditionOp::Eq {
|
||||
continue;
|
||||
}
|
||||
let field_bitmask = condition.field.shift_value(condition.field_mask);
|
||||
if calc_bitmask & field_bitmask != 0 {
|
||||
log::warn!(
|
||||
"Mnmemonic {}: {:#010X} & {:#010X} != 0",
|
||||
mnemonic.name,
|
||||
calc_bitmask,
|
||||
field_bitmask,
|
||||
);
|
||||
}
|
||||
calc_bitmask |= field_bitmask;
|
||||
}
|
||||
if calc_bitmask != u32::MAX {
|
||||
log::warn!(
|
||||
"Mnemonic {}: Calculated bitmask is non-exhaustive: {:#010X}, {:032b}",
|
||||
mnemonic.name,
|
||||
calc_bitmask,
|
||||
calc_bitmask
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let tokens = gen_disasm(&isa, max_args)?;
|
||||
let file = syn::parse2(tokens)?;
|
||||
let formatted = prettyplease::unparse(&file);
|
||||
std::fs::write("disasm/src/generated.rs", formatted)?;
|
||||
|
||||
let tokens = gen_asm(&isa, max_args)?;
|
||||
let file = syn::parse2(tokens)?;
|
||||
let formatted = prettyplease::unparse(&file);
|
||||
std::fs::write("asm/src/generated.rs", formatted)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rustfmt(code: Vec<u8>) -> Vec<u8> {
|
||||
let mut rustfmt = Command::new("rustfmt")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("failed to spawn rustfmt");
|
||||
|
||||
let mut stdin = rustfmt.stdin.take().unwrap();
|
||||
std::thread::spawn(move || {
|
||||
let _ = stdin.write_all(&code);
|
||||
});
|
||||
|
||||
let rustfmt_res = rustfmt.wait_with_output().expect("failed to run rustfmt");
|
||||
if !rustfmt_res.status.success() {
|
||||
panic!("rustfmt failed");
|
||||
}
|
||||
|
||||
rustfmt_res.stdout
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct BitRange(Range<u8>);
|
||||
|
||||
impl<'de> Deserialize<'de> for BitRange {
|
||||
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let range_str: String = Deserialize::deserialize(deserializer)?;
|
||||
if let Some((start_str, stop_str)) = range_str.split_once("..") {
|
||||
let start = start_str.parse::<u8>().map_err(serde::de::Error::custom)?;
|
||||
let stop = stop_str.parse::<u8>().map_err(serde::de::Error::custom)?;
|
||||
Ok(Self(start..stop))
|
||||
} else {
|
||||
let bit_idx = range_str.parse::<u8>().map_err(serde::de::Error::custom)?;
|
||||
Ok(Self(bit_idx..bit_idx))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub(crate) struct Field {
|
||||
name: String,
|
||||
desc: String,
|
||||
bits: BitRange,
|
||||
signed: bool,
|
||||
split: bool,
|
||||
arg: Option<String>,
|
||||
shift_left: u8,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
fn variant_identifier(&self) -> Option<TokenTree> {
|
||||
self.identifier("")
|
||||
}
|
||||
|
||||
fn identifier(&self, prefix: &str) -> Option<TokenTree> {
|
||||
if self.name.strip_suffix(".nz").is_none() {
|
||||
Some(to_rust_ident(prefix, &self.name))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn express_value(&self, code: TokenStream) -> TokenStream {
|
||||
let mut val = quote!(#code);
|
||||
|
||||
let shift = 32 - self.bits.0.end;
|
||||
if shift > 0 {
|
||||
val = quote!((#val >> #shift));
|
||||
}
|
||||
|
||||
let mask = (1u32 << self.bits.0.len()) - 1;
|
||||
if mask != 0xFFFF_FFFF {
|
||||
let mask = LitInt::new(&format!("0x{:x}", mask), Span::call_site());
|
||||
val = quote!((#val & #mask));
|
||||
}
|
||||
|
||||
if self.split {
|
||||
val = quote!((((#val & 0b11111_00000u32) >> 5u32) | ((#val & 0b00000_11111u32) << 5u32)) as u32);
|
||||
}
|
||||
|
||||
// https://graphics.stanford.edu/~seander/bithacks.html#VariableSignExtend
|
||||
if self.signed {
|
||||
let mask2 = 1u32 << (self.bits.0.len() - 1);
|
||||
let mask2 = LitInt::new(&format!("0x{:x}", mask2), Span::call_site());
|
||||
val = quote!((((#val ^ #mask2).wrapping_sub(#mask2)) as i32))
|
||||
}
|
||||
|
||||
let val_shift = self.shift_left;
|
||||
if val_shift > 0 {
|
||||
val = quote!((#val << #val_shift));
|
||||
}
|
||||
|
||||
val
|
||||
}
|
||||
|
||||
fn express_value_self(&self) -> TokenStream {
|
||||
self.express_value(quote!(self.code))
|
||||
}
|
||||
|
||||
fn enum_variant_definition(&self) -> Option<TokenStream> {
|
||||
let ident = self.variant_identifier()?;
|
||||
Some(if let Some(arg) = &self.arg {
|
||||
let arg = TokenTree::Ident(Ident::new(arg, Span::call_site()));
|
||||
quote! {
|
||||
#ident(#arg),
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
#ident,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn construct_variant(&self, code: TokenStream) -> TokenStream {
|
||||
let field_variant = self.variant_identifier();
|
||||
if let Some(arg) = &self.arg {
|
||||
let field_arg = TokenTree::Ident(Ident::new(arg, Span::call_site()));
|
||||
let value = self.express_value(code);
|
||||
quote! {
|
||||
Field::#field_variant(#field_arg(#value as _))
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
Field::#field_variant
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn construct_variant_self(&self) -> TokenStream {
|
||||
self.construct_variant(quote!(self.code))
|
||||
}
|
||||
|
||||
fn construct_accessor(&self) -> TokenStream {
|
||||
let field_variant = match self.identifier("field_") {
|
||||
Some(v) => v,
|
||||
None => return TokenStream::new(),
|
||||
};
|
||||
if self.arg.is_none() {
|
||||
return TokenStream::new();
|
||||
}
|
||||
let value = self.express_value_self();
|
||||
let ret_type = if self.signed {
|
||||
quote!(isize)
|
||||
} else {
|
||||
quote!(usize)
|
||||
};
|
||||
quote! {
|
||||
#[inline(always)]
|
||||
pub fn #field_variant(&self) -> #ret_type {
|
||||
#value as _
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub(crate) struct Opcode {
|
||||
name: String,
|
||||
desc: String,
|
||||
bitmask: u32,
|
||||
pattern: u32,
|
||||
modifiers: Vec<String>,
|
||||
side_effects: Vec<String>,
|
||||
args: Vec<String>,
|
||||
defs: Vec<String>,
|
||||
uses: Vec<String>,
|
||||
}
|
||||
|
||||
impl Opcode {
|
||||
fn variant_identifier(&self) -> Result<TokenTree> {
|
||||
to_rust_variant(&self.name)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub(crate) struct Mnemonic {
|
||||
name: String,
|
||||
opcode: String,
|
||||
// Overrides modifier list from opcode
|
||||
modifiers: Option<Vec<String>>,
|
||||
args: Vec<String>,
|
||||
condition: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub(crate) struct Modifier {
|
||||
name: String,
|
||||
suffix: char,
|
||||
bit: u8,
|
||||
condition: String,
|
||||
}
|
||||
|
||||
impl Modifier {
|
||||
fn express_value_self(&self, field_by_name: &HashMap<String, &Field>) -> Result<TokenStream> {
|
||||
if self.condition.is_empty() {
|
||||
let modifier_bit = self.bit as usize;
|
||||
Ok(quote!(self.bit(#modifier_bit)))
|
||||
} else {
|
||||
compile_mnemonic_condition(field_by_name, &self.condition)
|
||||
}
|
||||
}
|
||||
|
||||
fn construct_accessor(&self, field_by_name: &HashMap<String, &Field>) -> Result<TokenStream> {
|
||||
let field_variant = to_rust_ident("field_", &self.name);
|
||||
let value = self.express_value_self(field_by_name)?;
|
||||
Ok(quote! {
|
||||
#[inline(always)]
|
||||
pub fn #field_variant(&self) -> bool {
|
||||
#value
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub(crate) struct Isa {
|
||||
fields: Vec<Field>,
|
||||
modifiers: Vec<Modifier>,
|
||||
opcodes: Vec<Opcode>,
|
||||
mnemonics: Vec<Mnemonic>,
|
||||
}
|
||||
|
||||
fn load_isa() -> Result<Isa> {
|
||||
let yaml_file = File::open("isa.yaml")?;
|
||||
let isa: Isa = serde_yaml::from_reader(yaml_file)?;
|
||||
Ok(isa)
|
||||
}
|
||||
|
||||
impl Isa {
|
||||
fn gen_opcode_enum(&self) -> Result<TokenStream> {
|
||||
// Create enum variants.
|
||||
let enum_variants = self
|
||||
.opcodes
|
||||
.iter()
|
||||
.map(|opcode| -> Result<TokenStream> {
|
||||
let ident = opcode.variant_identifier()?;
|
||||
Ok(quote! {
|
||||
#ident,
|
||||
})
|
||||
})
|
||||
.try_collect::<TokenStream, Vec<TokenStream>, Error>()?;
|
||||
let enum_variants = token_stream!(enum_variants);
|
||||
|
||||
// Create functions.
|
||||
let mnemonic_fn = self.gen_mnemonic_fn()?;
|
||||
let detect_fn = self.gen_opcode_detect()?;
|
||||
|
||||
// Create final enum.
|
||||
let opcode_enum = quote! {
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
pub enum Opcode {
|
||||
Illegal = -1,
|
||||
#enum_variants
|
||||
}
|
||||
#[allow(clippy::all)]
|
||||
impl Opcode {
|
||||
#mnemonic_fn
|
||||
#detect_fn
|
||||
}
|
||||
};
|
||||
Ok(opcode_enum)
|
||||
}
|
||||
|
||||
fn gen_mnemonic_fn(&self) -> Result<TokenStream> {
|
||||
// Create match arms.
|
||||
let match_arms = self
|
||||
.opcodes
|
||||
.iter()
|
||||
.map(|opcode| {
|
||||
let variant = opcode.variant_identifier()?;
|
||||
let literal = Literal::string(&opcode.name);
|
||||
Ok(quote! {
|
||||
Opcode::#variant => #literal,
|
||||
})
|
||||
})
|
||||
.try_collect::<TokenStream, Vec<TokenStream>, Error>()?;
|
||||
let match_arms = token_stream!(match_arms);
|
||||
// Create final function.
|
||||
let mnemonic_fn = quote! {
|
||||
pub(crate) fn _mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Opcode::Illegal => "<illegal>",
|
||||
#match_arms
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(mnemonic_fn)
|
||||
}
|
||||
|
||||
fn gen_opcode_detect(&self) -> Result<TokenStream> {
|
||||
// Generate if chain.
|
||||
let if_chain = self
|
||||
.opcodes
|
||||
.iter()
|
||||
.map(|opcode| {
|
||||
let bitmask_str = format!("{:>#8x}", opcode.bitmask);
|
||||
let bitmask = LitInt::new(&bitmask_str, Span::call_site());
|
||||
let pattern_str = format!("{:>#8x}", opcode.pattern);
|
||||
let pattern = LitInt::new(&pattern_str, Span::call_site());
|
||||
let identifier = opcode.variant_identifier()?;
|
||||
Ok(quote! {
|
||||
if code & #bitmask == #pattern {
|
||||
return Opcode::#identifier;
|
||||
}
|
||||
})
|
||||
})
|
||||
.try_collect::<TokenStream, Vec<TokenStream>, Error>()?;
|
||||
let if_chain = token_stream!(if_chain);
|
||||
// Generate function.
|
||||
let func = quote! {
|
||||
pub(crate) fn _detect(code: u32) -> Self {
|
||||
#if_chain
|
||||
Opcode::Illegal
|
||||
}
|
||||
};
|
||||
Ok(func)
|
||||
}
|
||||
|
||||
fn gen_field_enum(&self) -> Result<TokenStream> {
|
||||
// Create enum variants.
|
||||
let mut enum_variants = Vec::new();
|
||||
for field in &self.fields {
|
||||
if let Some(field) = field.enum_variant_definition() {
|
||||
enum_variants.push(field);
|
||||
}
|
||||
}
|
||||
let enum_variants = token_stream!(enum_variants);
|
||||
|
||||
// Create final enum.
|
||||
let field_enum = quote! {
|
||||
#[allow(non_camel_case_types)]
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
pub enum Field {
|
||||
#enum_variants
|
||||
}
|
||||
};
|
||||
Ok(field_enum)
|
||||
}
|
||||
|
||||
fn gen_field_argument(&self) -> Result<TokenStream> {
|
||||
let mut match_arms = Vec::new();
|
||||
for field in &self.fields {
|
||||
if let Some(variant) = field.variant_identifier() {
|
||||
if let Some(arg_str) = field.arg.as_ref() {
|
||||
let arg = Ident::new(arg_str, Span::call_site());
|
||||
match_arms.push(quote! { Field::#variant(x) => Some(Argument::#arg(*x)), });
|
||||
}
|
||||
}
|
||||
}
|
||||
let match_arms = token_stream!(match_arms);
|
||||
Ok(quote! {
|
||||
pub fn argument(&self) -> Option<Argument> {
|
||||
match self {
|
||||
#match_arms
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn gen_field_name(&self) -> Result<TokenStream> {
|
||||
let mut match_arms = Vec::new();
|
||||
for field in &self.fields {
|
||||
if let Some(variant) = field.variant_identifier() {
|
||||
let name = LitStr::new(&variant.to_string(), Span::call_site());
|
||||
let arg = field.arg.as_ref().map(|_| quote!((_)));
|
||||
match_arms.push(quote! { Field::#variant #arg => #name, });
|
||||
}
|
||||
}
|
||||
let match_arms = token_stream!(match_arms);
|
||||
Ok(quote! {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
#match_arms
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn gen_field_impl(&self) -> Result<TokenStream> {
|
||||
let field_argument = self.gen_field_argument()?;
|
||||
let field_name = self.gen_field_name()?;
|
||||
Ok(quote! {
|
||||
impl Field {
|
||||
#field_argument
|
||||
#field_name
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn gen_ins_impl(&self) -> Result<TokenStream> {
|
||||
// Map fields by name.
|
||||
let mut field_by_name = HashMap::<String, &Field>::new();
|
||||
for field in &self.fields {
|
||||
field_by_name.insert(field.name.clone(), field);
|
||||
}
|
||||
let mut modifier_by_name = HashMap::<String, &Modifier>::new();
|
||||
for modifier in &self.modifiers {
|
||||
modifier_by_name.insert(modifier.name.clone(), modifier);
|
||||
}
|
||||
// Map mnemonics by opcode.
|
||||
let mut mnemonics_by_opcode = HashMap::<&String, Vec<&Mnemonic>>::new();
|
||||
for simple in &self.mnemonics {
|
||||
mnemonics_by_opcode
|
||||
.entry(&simple.opcode)
|
||||
.or_insert_with(Vec::new)
|
||||
.push(simple)
|
||||
}
|
||||
// Generate match arms for each opcode.
|
||||
let mut field_match_arms = Vec::new();
|
||||
let mut def_match_arms = Vec::new();
|
||||
let mut use_match_arms = Vec::new();
|
||||
let mut suffix_match_arms = Vec::new();
|
||||
let mut simplified_ins_match_arms = Vec::new();
|
||||
for opcode in &self.opcodes {
|
||||
// Generate fields of opcode.
|
||||
let mut fields = Vec::new();
|
||||
for arg in &opcode.args {
|
||||
let field: &Field = field_by_name
|
||||
.get(arg)
|
||||
.ok_or_else(|| Error::from(format!("undefined field {}", arg)))?;
|
||||
let variant = field.construct_variant_self();
|
||||
fields.extend(quote! { #variant, })
|
||||
}
|
||||
let fields = token_stream!(fields);
|
||||
// Emit match arm.
|
||||
let ident = opcode.variant_identifier()?;
|
||||
field_match_arms.push(quote! {
|
||||
Opcode::#ident => vec![#fields],
|
||||
});
|
||||
|
||||
// Generate modifiers.
|
||||
let suffix = express_suffix(&modifier_by_name, &field_by_name, &opcode.modifiers)?;
|
||||
suffix_match_arms.push(quote! {
|
||||
Opcode::#ident => #suffix,
|
||||
});
|
||||
|
||||
// Generate defs.
|
||||
let mut defs = Vec::new();
|
||||
for arg in &opcode.defs {
|
||||
let field: &Field = field_by_name.get(arg).ok_or_else(|| {
|
||||
syn::Error::new(Span::call_site(), format!("undefined field {}", arg))
|
||||
})?;
|
||||
let variant = field.construct_variant_self();
|
||||
defs.extend(quote! { #variant, })
|
||||
}
|
||||
let defs = token_stream!(defs);
|
||||
let ident = opcode.variant_identifier()?;
|
||||
def_match_arms.push(quote! {
|
||||
Opcode::#ident => vec![#defs],
|
||||
});
|
||||
|
||||
// Generate uses.
|
||||
let mut uses = Vec::new();
|
||||
let mut special_uses = Vec::new();
|
||||
for arg in &opcode.uses {
|
||||
// Detect non-zero modifier.
|
||||
let mut arg = arg.as_str();
|
||||
let mut non_zero = false;
|
||||
if let Some(substr) = arg.strip_suffix(".nz") {
|
||||
non_zero = true;
|
||||
arg = substr;
|
||||
}
|
||||
// Get underlying field.
|
||||
let field: &Field = field_by_name.get(arg).ok_or_else(|| {
|
||||
syn::Error::new(Span::call_site(), format!("undefined field {}", arg))
|
||||
})?;
|
||||
let variant = field.construct_variant_self();
|
||||
if non_zero {
|
||||
let value = field.express_value_self();
|
||||
special_uses.extend(quote! {
|
||||
if (#value) != 0 {
|
||||
uses.push(#variant);
|
||||
}
|
||||
})
|
||||
} else {
|
||||
uses.extend(quote! {
|
||||
#variant,
|
||||
})
|
||||
}
|
||||
}
|
||||
let uses = token_stream!(uses);
|
||||
let ident = opcode.variant_identifier()?;
|
||||
let special_uses = token_stream!(special_uses);
|
||||
use_match_arms.push(quote! {
|
||||
Opcode::#ident => {
|
||||
let mut uses = vec![#uses];
|
||||
#special_uses
|
||||
uses
|
||||
},
|
||||
});
|
||||
|
||||
// Generate instruction simplification.
|
||||
if let Some(mnemonics) = mnemonics_by_opcode.get(&opcode.name) {
|
||||
let mut simplified_conditions = Vec::new();
|
||||
for mnemonic in mnemonics {
|
||||
if mnemonic.condition.is_empty() {
|
||||
continue; // TODO else branch
|
||||
}
|
||||
simplified_conditions.push(quote!(if));
|
||||
simplified_conditions.push(compile_mnemonic_condition(
|
||||
&field_by_name,
|
||||
&mnemonic.condition,
|
||||
)?);
|
||||
// Emit branch.
|
||||
let mnemonic_lit = LitStr::new(&mnemonic.name, Span::call_site());
|
||||
// Emit suffix.
|
||||
let modifiers = mnemonic.modifiers.as_ref().unwrap_or(&opcode.modifiers);
|
||||
let suffix = express_suffix(&modifier_by_name, &field_by_name, modifiers)?;
|
||||
// Extract arguments.
|
||||
let mut args = Vec::new();
|
||||
for arg in &mnemonic.args {
|
||||
let (field_name, expression) = arg.split_once('=').unwrap_or((arg, arg));
|
||||
let field = field_by_name
|
||||
.get(field_name)
|
||||
.unwrap_or_else(|| panic!("field not found: {}", arg));
|
||||
let variant = Ident::new(field.arg.as_ref().unwrap(), Span::call_site());
|
||||
let value = compile_mnemonic_condition(&field_by_name, expression)?;
|
||||
args.push(quote!(Argument::#variant(#variant((#value) as _)),));
|
||||
}
|
||||
let args = token_stream!(args);
|
||||
simplified_conditions.push(quote! {
|
||||
{
|
||||
return SimplifiedIns {
|
||||
mnemonic: #mnemonic_lit,
|
||||
suffix: #suffix,
|
||||
args: vec![#args],
|
||||
ins: self,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
let simplified_conditions = token_stream!(simplified_conditions);
|
||||
simplified_ins_match_arms.push(quote! {
|
||||
Opcode::#ident => {
|
||||
#simplified_conditions
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
let field_match_arms = token_stream!(field_match_arms);
|
||||
let def_match_arms = token_stream!(def_match_arms);
|
||||
let use_match_arms = token_stream!(use_match_arms);
|
||||
let suffix_match_arms = token_stream!(suffix_match_arms);
|
||||
let simplified_ins_match_arms = token_stream!(simplified_ins_match_arms);
|
||||
let field_accessors =
|
||||
TokenStream::from_iter(self.fields.iter().map(|field| field.construct_accessor()));
|
||||
let modifiers: Vec<TokenStream> = self
|
||||
.modifiers
|
||||
.iter()
|
||||
.map(|modifier| modifier.construct_accessor(&field_by_name))
|
||||
.try_collect()?;
|
||||
let modifier_accessors = TokenStream::from_iter(modifiers);
|
||||
// Generate final fields function.
|
||||
let ins_impl = quote! {
|
||||
#[allow(clippy::all, unused_mut)]
|
||||
impl Ins {
|
||||
pub(crate) fn _fields(&self) -> Vec<Field> {
|
||||
match self.op {
|
||||
Opcode::Illegal => vec![],
|
||||
#field_match_arms
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn _defs(&self) -> Vec<Field> {
|
||||
match self.op {
|
||||
Opcode::Illegal => vec![],
|
||||
#def_match_arms
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn _uses(&self) -> Vec<Field> {
|
||||
match self.op {
|
||||
Opcode::Illegal => vec![],
|
||||
#use_match_arms
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn _suffix(&self) -> String {
|
||||
match self.op {
|
||||
Opcode::Illegal => String::new(),
|
||||
#suffix_match_arms
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn _simplified(self) -> SimplifiedIns {
|
||||
match self.op {
|
||||
#simplified_ins_match_arms
|
||||
_ => {}
|
||||
}
|
||||
SimplifiedIns::basic_form(self)
|
||||
}
|
||||
}
|
||||
#[allow(clippy::all, non_snake_case)]
|
||||
impl Ins {
|
||||
#field_accessors
|
||||
#modifier_accessors
|
||||
}
|
||||
};
|
||||
Ok(ins_impl)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the given key into an identifier.
|
||||
fn to_rust_ident(prefix: &str, key: &str) -> TokenTree {
|
||||
TokenTree::Ident(Ident::new(
|
||||
&(prefix.to_owned() + &key.replace('.', "_")),
|
||||
Span::call_site(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Converts the given key into an enum variant key.
|
||||
fn to_rust_variant(key: &str) -> Result<TokenTree> {
|
||||
Ok(TokenTree::Ident(Ident::new(
|
||||
&to_rust_variant_str(key)?,
|
||||
Span::call_site(),
|
||||
)))
|
||||
}
|
||||
|
||||
fn to_rust_variant_str(key: &str) -> Result<String> {
|
||||
let mut s = String::new();
|
||||
let mut chars = key.chars();
|
||||
loop {
|
||||
// Make first char uppercase.
|
||||
let c = match chars.next() {
|
||||
None => return Ok(s),
|
||||
Some(c) => c,
|
||||
};
|
||||
s.push(match c {
|
||||
'a'..='z' => c.to_ascii_uppercase(),
|
||||
'A'..='Z' => c,
|
||||
_ => return Err(format!("invalid identifier: {}", key).into()),
|
||||
});
|
||||
loop {
|
||||
let c = match chars.next() {
|
||||
None => return Ok(s),
|
||||
Some(c) => c,
|
||||
};
|
||||
match c.to_ascii_lowercase() {
|
||||
'0'..='9' | 'a'..='z' => s.push(c),
|
||||
'_' => break,
|
||||
'.' => {
|
||||
s.push('_');
|
||||
break;
|
||||
}
|
||||
_ => return Err(format!("invalid character in opcode name: {}", key).into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compiles conditions such as `S == B` into valid Rust expressions on a PowerPC instruction.
|
||||
fn compile_mnemonic_condition(
|
||||
field_by_name: &HashMap<String, &Field>,
|
||||
code: &str,
|
||||
) -> Result<TokenStream> {
|
||||
let src_stream = TokenStream::from_str(code)?;
|
||||
fn map_ident(field_by_name: &HashMap<String, &Field>, token: TokenTree) -> TokenStream {
|
||||
match token {
|
||||
TokenTree::Ident(ref ident) => {
|
||||
if let Some(field) = field_by_name.get(&ident.to_string()) {
|
||||
return field.express_value_self();
|
||||
}
|
||||
}
|
||||
TokenTree::Group(ref group) => {
|
||||
let iter = group
|
||||
.stream()
|
||||
.into_iter()
|
||||
.flat_map(|token| map_ident(field_by_name, token));
|
||||
let stream = TokenStream::from_iter(iter);
|
||||
return TokenStream::from(TokenTree::Group(Group::new(group.delimiter(), stream)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
token.into()
|
||||
}
|
||||
let token_iter = src_stream
|
||||
.into_iter()
|
||||
.flat_map(|token| map_ident(field_by_name, token));
|
||||
Ok(TokenStream::from_iter(token_iter))
|
||||
}
|
||||
|
||||
fn express_suffix(
|
||||
modifier_by_name: &HashMap<String, &Modifier>,
|
||||
field_by_name: &HashMap<String, &Field>,
|
||||
modifiers: &[String],
|
||||
) -> Result<TokenStream> {
|
||||
Ok(if modifiers.is_empty() {
|
||||
quote!(String::new())
|
||||
} else {
|
||||
let mut chars = Vec::new();
|
||||
for mod_name in modifiers {
|
||||
let modifier: &Modifier = modifier_by_name
|
||||
.get(mod_name)
|
||||
.ok_or_else(|| Error::from(format!("undefined modifier {}", mod_name)))?;
|
||||
let lit_char = LitChar::new(modifier.suffix, Span::call_site());
|
||||
let modifier_bit = modifier.express_value_self(field_by_name)?;
|
||||
chars.push(quote! {
|
||||
if #modifier_bit {
|
||||
s.push(#lit_char);
|
||||
}
|
||||
});
|
||||
}
|
||||
let chars = token_stream!(chars);
|
||||
quote!({
|
||||
{
|
||||
let mut s = String::with_capacity(4);
|
||||
#chars
|
||||
s
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
|
111
isa.yaml
111
isa.yaml
|
@ -2,108 +2,134 @@ fields:
|
|||
# Immediates
|
||||
- name: simm
|
||||
arg: Simm
|
||||
desc: Signed Immediate
|
||||
bits: 16..32
|
||||
signed: true
|
||||
- name: uimm
|
||||
arg: Uimm
|
||||
desc: Unsigned Immediate
|
||||
bits: 16..32
|
||||
- name: offset
|
||||
arg: Offset
|
||||
desc: Branch Offset
|
||||
bits: 16..32
|
||||
signed: true
|
||||
- name: ps_offset
|
||||
arg: Offset
|
||||
desc: Paired Single Offset
|
||||
bits: 20..32
|
||||
signed: true
|
||||
# Branch fields
|
||||
- name: BO
|
||||
arg: OpaqueU
|
||||
desc: Branch Options
|
||||
bits: 6..11
|
||||
- name: BI
|
||||
arg: CRBit
|
||||
desc: Branch Condition Register Bit
|
||||
bits: 11..16
|
||||
- name: BD
|
||||
arg: BranchDest
|
||||
desc: Branch Destination (14-bit)
|
||||
bits: 16..30
|
||||
shift_left: 2
|
||||
signed: true
|
||||
- name: LI
|
||||
arg: BranchDest
|
||||
desc: Branch Destination (24-bit)
|
||||
bits: 6..30
|
||||
signed: true
|
||||
shift_left: 2
|
||||
# Shift/rotate type fields
|
||||
- name: SH
|
||||
arg: OpaqueU
|
||||
desc: Shift
|
||||
desc: Shift Amount
|
||||
bits: 16..21
|
||||
- name: MB
|
||||
arg: OpaqueU
|
||||
desc: Mask start
|
||||
desc: Mask Begin
|
||||
bits: 21..26
|
||||
- name: ME
|
||||
arg: OpaqueU
|
||||
desc: Mask stop
|
||||
desc: Mask End
|
||||
bits: 26..31
|
||||
# Registers
|
||||
- name: rS
|
||||
arg: GPR
|
||||
desc: Source Register
|
||||
bits: 6..11
|
||||
- name: rD
|
||||
arg: GPR
|
||||
desc: Destination Register
|
||||
bits: 6..11
|
||||
- name: rA
|
||||
arg: GPR
|
||||
desc: Register A
|
||||
bits: 11..16
|
||||
- name: rA.nz
|
||||
arg: GPR
|
||||
desc: Register A (non-zero)
|
||||
bits: 11..16
|
||||
- name: rB
|
||||
arg: GPR
|
||||
desc: Register B
|
||||
bits: 16..21
|
||||
- name: sr
|
||||
arg: SR
|
||||
desc: Segment Register
|
||||
bits: 12..16
|
||||
- name: spr
|
||||
arg: SPR
|
||||
desc: Special Purpose Register
|
||||
bits: 11..21
|
||||
split: true
|
||||
# Floating-point registers
|
||||
- name: frS
|
||||
arg: FPR
|
||||
desc: Source Floating-Point Register
|
||||
bits: 6..11
|
||||
- name: frD
|
||||
arg: FPR
|
||||
desc: Destination Floating-Point Register
|
||||
bits: 6..11
|
||||
- name: frA
|
||||
arg: FPR
|
||||
desc: Floating-Point Register A
|
||||
bits: 11..16
|
||||
- name: frB
|
||||
arg: FPR
|
||||
desc: Floating-Point Register B
|
||||
bits: 16..21
|
||||
- name: frC
|
||||
arg: FPR
|
||||
desc: Floating-Point Register C
|
||||
bits: 21..26
|
||||
# Condition register bits
|
||||
- name: crbD
|
||||
arg: CRBit
|
||||
desc: Condition Register Bit Destination
|
||||
bits: 6..11
|
||||
- name: crbA
|
||||
arg: CRBit
|
||||
desc: Condition Register Bit A
|
||||
bits: 11..16
|
||||
- name: crbB
|
||||
arg: CRBit
|
||||
desc: Condition Register Bit B
|
||||
bits: 16..21
|
||||
# Condition register fields
|
||||
- name: crfD
|
||||
arg: CRField
|
||||
desc: Condition Register Field Destination
|
||||
bits: 6..9
|
||||
- name: crfS
|
||||
arg: CRField
|
||||
desc: Condition Register Field Source
|
||||
bits: 11..14
|
||||
# Condition register misc
|
||||
- name: crm
|
||||
arg: OpaqueU
|
||||
desc: Condition Register Mask
|
||||
bits: 12..20
|
||||
# Paired single fields
|
||||
- name: ps_I
|
||||
|
@ -152,37 +178,46 @@ fields:
|
|||
desc: Bitset for cmp, cmpi, cmpl, cmpli
|
||||
bits: 10..11
|
||||
- name: xer
|
||||
desc: Fixed-Point Exception Register
|
||||
- name: ctr
|
||||
desc: Count Register
|
||||
- name: lr
|
||||
desc: Link Register
|
||||
|
||||
modifiers:
|
||||
- name: OE
|
||||
desc: Field used by XO-form instructions to enable setting OV and SO in the XER.
|
||||
suffix: o
|
||||
bit: 21
|
||||
side_effects: [ xer ]
|
||||
- name: Rc
|
||||
desc: Record Bit
|
||||
suffix: .
|
||||
bit: 31
|
||||
side_effects: [ cr0 ]
|
||||
- name: LK
|
||||
desc: Link Bit
|
||||
suffix: l
|
||||
bit: 31
|
||||
side_effects: [ lr ]
|
||||
- name: AA
|
||||
desc: Absolute Address Bit
|
||||
suffix: a
|
||||
bit: 30
|
||||
# Predict branch to be taken
|
||||
- name: BP
|
||||
desc: Predict branch to be taken
|
||||
suffix: +
|
||||
condition: BO & 1 == 1 && BD >= 0
|
||||
# Predict branch not to be taken (fall through)
|
||||
bit: 10
|
||||
condition: BD >= 0
|
||||
- name: BNP
|
||||
desc: Predict branch not to be taken (fall through)
|
||||
suffix: '-'
|
||||
condition: BO & 1 == 1 && BD < 0
|
||||
# Predict branch to be taken (implicit dest for LR/CTR)
|
||||
bit: 10
|
||||
condition: BD < 0
|
||||
- name: BP_ND
|
||||
desc: Predict branch to be taken (implicit dest for LR/CTR)
|
||||
suffix: +
|
||||
condition: BO & 1 == 1
|
||||
bit: 10
|
||||
|
||||
opcodes:
|
||||
- name: add
|
||||
|
@ -1998,24 +2033,40 @@ mnemonics:
|
|||
condition: rA == 0
|
||||
- name: subis
|
||||
opcode: addis
|
||||
args: [ rD, rA, simm=-simm ]
|
||||
args: [ rD, rA, simm ]
|
||||
condition: simm < 0 && simm != -0x8000
|
||||
replace:
|
||||
simm: -simm
|
||||
replace_assemble:
|
||||
simm: -simm
|
||||
- name: li
|
||||
opcode: addi
|
||||
args: [ rD, simm ]
|
||||
condition: rA == 0
|
||||
- name: subi
|
||||
opcode: addi
|
||||
args: [ rD, rA, simm=-simm ]
|
||||
args: [ rD, rA, simm ]
|
||||
condition: simm < 0 && simm != -0x8000
|
||||
replace:
|
||||
simm: -simm
|
||||
replace_assemble:
|
||||
simm: -simm
|
||||
- name: subic
|
||||
opcode: addic
|
||||
args: [ rD, rA, simm=-simm ]
|
||||
args: [ rD, rA, simm ]
|
||||
condition: simm < 0 && simm != -0x8000
|
||||
replace:
|
||||
simm: -simm
|
||||
replace_assemble:
|
||||
simm: -simm
|
||||
- name: subic.
|
||||
opcode: addic.
|
||||
args: [ rD, rA, simm=-simm ]
|
||||
args: [ rD, rA, simm ]
|
||||
condition: simm < 0 && simm != -0x8000
|
||||
replace:
|
||||
simm: -simm
|
||||
replace_assemble:
|
||||
simm: -simm
|
||||
- name: mr
|
||||
opcode: or
|
||||
args: [ rA, rS ]
|
||||
|
@ -2035,8 +2086,12 @@ mnemonics:
|
|||
# Rotates/Shifts Immediate
|
||||
- name: clrrwi
|
||||
opcode: rlwinm
|
||||
args: [ rA, rS, ME=31-ME ]
|
||||
condition: SH == 0 && MB == 0 && ME < 32
|
||||
args: [ rA, rS, ME ]
|
||||
condition: SH == 0 && MB == 0
|
||||
replace:
|
||||
ME: 31 - ME
|
||||
replace_assemble:
|
||||
ME: 31 - ME
|
||||
- name: clrlwi
|
||||
opcode: rlwinm
|
||||
args: [ rA, rS, MB ]
|
||||
|
@ -2047,8 +2102,12 @@ mnemonics:
|
|||
condition: MB == 0 && ME == 31 && SH <= 16
|
||||
- name: rotrwi
|
||||
opcode: rlwinm
|
||||
args: [ rA, rS, SH=32-SH ]
|
||||
args: [ rA, rS, SH ]
|
||||
condition: MB == 0 && ME == 31 && SH > 16
|
||||
replace:
|
||||
SH: 32 - SH
|
||||
replace_assemble:
|
||||
SH: 32 - SH
|
||||
- name: slwi
|
||||
opcode: rlwinm
|
||||
args: [ rA, rS, SH ]
|
||||
|
@ -2059,16 +2118,30 @@ mnemonics:
|
|||
condition: ME == 31 && SH == 32 - MB
|
||||
- name: clrlslwi
|
||||
opcode: rlwinm
|
||||
args: [ rA, rS, MB=MB+SH, SH ]
|
||||
args: [ rA, rS, MB, SH ]
|
||||
condition: SH < 32 && ME == 31 - SH
|
||||
replace:
|
||||
MB: MB + SH
|
||||
replace_assemble:
|
||||
MB: MB - SH
|
||||
- name: extlwi
|
||||
opcode: rlwinm
|
||||
args: [ rA, rS, ME=ME+1, SH ]
|
||||
args: [ rA, rS, ME, SH ]
|
||||
condition: MB == 0
|
||||
replace:
|
||||
ME: ME + 1
|
||||
replace_assemble:
|
||||
ME: ME - 1
|
||||
- name: extrwi
|
||||
opcode: rlwinm
|
||||
args: [ rA, rS, MB=32-MB, SH=SH-(32-MB) ]
|
||||
args: [ rA, rS, MB, SH ]
|
||||
condition: ME == 31 && SH >= 32 - MB
|
||||
replace:
|
||||
MB: 32 - MB
|
||||
SH: SH - (32 - MB)
|
||||
replace_assemble:
|
||||
MB: 32 - MB
|
||||
SH: SH + MB
|
||||
|
||||
# Compares Word
|
||||
- name: cmpwi
|
||||
|
|
|
@ -1,13 +0,0 @@
|
|||
[package]
|
||||
name = "ppc750cl-rand"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
authors = ["Richard Patel <me@terorie.dev>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
description = "Generate random PowerPC 750CL instructions"
|
||||
repository = "https://github.com/terorie/ppc750cl"
|
||||
|
||||
[dependencies]
|
||||
ppc750cl = { path = "../disasm", version = "0.2.0" }
|
||||
rand_core = "0.6"
|
||||
sfmt = "0.7"
|
|
@ -1,16 +0,0 @@
|
|||
use rand_core::{RngCore, SeedableRng};
|
||||
use sfmt::SFMT;
|
||||
|
||||
use ppc750cl::formatter::FormattedIns;
|
||||
use ppc750cl::{Ins, Opcode};
|
||||
|
||||
fn main() {
|
||||
let mut rng = SFMT::seed_from_u64(42);
|
||||
loop {
|
||||
let ins = Ins::new(rng.next_u32(), 0);
|
||||
if ins.op == Opcode::Illegal {
|
||||
continue;
|
||||
}
|
||||
println!("{}", FormattedIns(ins));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
use_field_init_shorthand = true
|
||||
use_small_heuristics = "Max"
|
Loading…
Reference in New Issue