Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When printing asm also include relevant constants #261

Merged
merged 7 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Change Log

## [0.2.31] - 2024-04-04
- include relevant constants in produced asm output
this can be disabled with `--no-constants`
- bump deps

## [0.2.30] - 2024-02-11
- Add an option `-c` / `--context` to recursively include functions called from target as
additional context
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ $ cargo install cargo-show-asm

Show the code rustc generates for any function

**Usage**: **`cargo asm`** \[**`-p`**=_`SPEC`_\] \[_`ARTIFACT`_\] \[**`-M`**=_`ARG`_\]... \[_`TARGET-CPU`_\] \[**`--rust`**\] \[**`-c`**=_`COUNT`_\] \[**`--simplify`**\] \[**`--this-workspace`** | **`--all-crates`** | **`--all-sources`**\] \[_`OUTPUT-FORMAT`_\] \[**`--everything`** | _`FUNCTION`_ \[_`INDEX`_\]\]
**Usage**: **`cargo asm`** \[**`-p`**=_`SPEC`_\] \[_`ARTIFACT`_\] \[**`-M`**=_`ARG`_\]... \[_`TARGET-CPU`_\] \[**`--rust`**\] \[**`-c`**=_`COUNT`_\] \[**`--simplify`**\] \[**`--no-constants`**\] \[**`--this-workspace`** | **`--all-crates`** | **`--all-sources`**\] \[_`OUTPUT-FORMAT`_\] \[**`--everything`** | _`FUNCTION`_ \[_`INDEX`_\]\]

Usage:
1. Focus on a single assembly producing target:
Expand Down Expand Up @@ -133,6 +133,8 @@ Show the code rustc generates for any function
more verbose output, can be specified multiple times
- **` --simplify`** —
Try to strip some of the non-assembly instruction information
- **` --no-constants`** —
Don't detect/include sections containing string literals and other constants
- **`-b`**, **`--keep-blank`** —
Keep blank lines
- **` --this-workspace`** —
Expand Down
8 changes: 3 additions & 5 deletions release-plz.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
[workspace]
# path of the git-cliff configuration
changelog_config = "cliff.toml"

# enable changelog updates
changelog_update = true
changelog_update = false

# update dependencies with `cargo update`
dependencies_update = true
dependencies_update = false

# create tags for the releases
git_tag_enable = true
Expand All @@ -24,4 +22,4 @@ allow_dirty = false
publish_allow_dirty = false

# disable running `cargo-semver-checks`
semver_check = false
semver_check = false
7 changes: 6 additions & 1 deletion sample/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ pub fn main() -> u32 {
1 + 1
}

pub struct Bar(u32);
#[inline(never)]
pub fn panics() {
panic!("oh noes asdf wef wef wf wefwefwef wef! {}", "bob");
}

pub struct Bar(pub u32);
impl Bar {
#[no_mangle]
pub fn make_bar(a: u32, b: u32) -> Self {
Expand Down
78 changes: 72 additions & 6 deletions src/asm.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#![allow(clippy::missing_errors_doc)]
use crate::asm::statements::{GenericDirective, Label};
use crate::asm::statements::{GenericDirective, Instruction, Label};
use crate::cached_lines::CachedLines;
use crate::demangle::LabelKind;
use crate::{
color, demangle, esafeprintln, get_context_for, get_dump_range, safeprintln, Item, RawLines,
URange,
};
// TODO, use https://sourceware.org/binutils/docs/as/index.html
use crate::opts::{Format, NameDisplay, RedundantLabels, SourcesFrom, ToDump};
Expand Down Expand Up @@ -196,13 +197,28 @@ fn used_labels<'a>(stmts: &'_ [Statement<'a>]) -> BTreeSet<&'a str> {
.collect::<BTreeSet<_>>()
}

pub fn dump_range(
/// Scans for referenced constants
fn scan_constant(name: &str, sections: &[(usize, &str)], body: &[Statement]) -> Option<URange> {
let start = sections
.iter()
.find_map(|(ix, ss)| ss.contains(name).then_some(*ix))?;
let end = body[start..]
.iter()
.position(|s| matches!(s, Statement::Nothing))
.map_or_else(|| body.len(), |e| start + e);
Some(URange { start, end })
}

fn dump_range(
files: &BTreeMap<u64, SourceFile>,
fmt: &Format,
stmts: &[Statement],
print_range: Range<usize>,
body: &[Statement], // full body
) -> anyhow::Result<()> {
let print_range = URange::from(print_range);
let mut prev_loc = Loc::default();

let stmts = &body[print_range];
let used = if fmt.redundant_labels == RedundantLabels::Keep {
BTreeSet::new()
} else {
Expand Down Expand Up @@ -290,6 +306,56 @@ pub fn dump_range(
}
}
}

if fmt.include_constants {
// scan for referenced constants such as strings, scan needs to be done recursively
let mut pending = vec![print_range];
let mut seen: BTreeSet<URange> = BTreeSet::new();

let sections = body
.iter()
.enumerate()
.filter_map(|(ix, stmt)| match stmt {
Statement::Directive(Directive::SectionStart(ss)) => Some((ix, *ss)),
_ => None,
})
.collect::<Vec<_>>();
while let Some(subset) = pending.pop() {
seen.insert(subset);
for s in &body[subset] {
if let Statement::Instruction(Instruction {
args: Some(arg), ..
})
| Statement::Directive(Directive::Generic(GenericDirective(arg))) = s
{
for label in crate::demangle::LOCAL_LABELS.find_iter(arg) {
let referenced_label = label.as_str().trim();
if let Some(constant_range) =
scan_constant(referenced_label, &sections, body)
{
if !seen.contains(&constant_range)
&& !print_range.fully_contains(constant_range)
{
pending.push(constant_range);
}
}
}
}
}
}
seen.remove(&print_range);
for range in &seen {
safeprintln!("");
for line in &body[*range] {
match fmt.name_display {
NameDisplay::Full => safeprintln!("{line:#}"),
NameDisplay::Short => safeprintln!("{line}"),
NameDisplay::Mangled => safeprintln!("{line:-}"),
}
}
}
}

Ok(())
}

Expand Down Expand Up @@ -500,21 +566,21 @@ pub fn dump_function(

if let Some(range) = get_dump_range(goal, fmt, &functions) {
let context = get_context_for(fmt.context, &statements[..], range.clone(), &functions);
dump_range(&files, fmt, &statements[range])?;
dump_range(&files, fmt, range, &statements)?;
if !context.is_empty() {
safeprintln!(
"\n\n======================= Additional context ========================="
);
for range in context {
safeprintln!("\n");
dump_range(&files, fmt, &statements[range])?;
dump_range(&files, fmt, range, &statements)?;
}
}
} else {
if fmt.verbosity > 0 {
safeprintln!("Going to print the whole file");
}
dump_range(&files, fmt, &statements)?;
dump_range(&files, fmt, 0..statements.len(), &statements)?;
}
Ok(())
}
2 changes: 1 addition & 1 deletion src/demangle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const TEMP_LABELS_REGEX: &str = r"\b(Ltmp[0-9]+)\b";
static GLOBAL_LABELS: Lazy<Regex> =
Lazy::new(|| Regex::new(GLOBAL_LABELS_REGEX).expect("regexp should be valid"));

static LOCAL_LABELS: Lazy<Regex> =
pub(crate) static LOCAL_LABELS: Lazy<Regex> =
Lazy::new(|| Regex::new(LOCAL_LABELS_REGEX).expect("regexp should be valid"));

static LABEL_KINDS: Lazy<RegexSet> = Lazy::new(|| {
Expand Down
26 changes: 26 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,3 +290,29 @@ pub fn dump_function<T: Dumpable>(goal: ToDump, path: &Path, fmt: &Format) -> an
};
Ok(())
}

/// Mostly the same as Range, but Copy and Ord
#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq)]
pub struct URange {
start: usize,
end: usize,
}

impl From<Range<usize>> for URange {
fn from(Range { start, end }: Range<usize>) -> Self {
Self { start, end }
}
}

impl<T> std::ops::Index<URange> for [T] {
type Output = [T];
fn index(&self, index: URange) -> &Self::Output {
&self[index.start..index.end]
}
}

impl URange {
pub fn fully_contains(&self, other: Self) -> bool {
self.start >= other.start && self.end <= other.end
}
}
4 changes: 4 additions & 0 deletions src/opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,10 @@ pub struct Format {
/// Try to strip some of the non-assembly instruction information
pub simplify: bool,

/// Don't detect/include sections containing string literals and other constants
#[bpaf(long("no-constants"), flag(false, true))]
pub include_constants: bool,

/// Keep blank lines
#[bpaf(short('b'), long, hide_usage)]
pub keep_blank: bool,
Expand Down
Loading